Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/NEMO_book.tex
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/NEMO_book.tex	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/NEMO_book.tex	(revision 5075)
@@ -215,6 +215,6 @@
 %\date{\today}
 \date{
-January 2012  \\
-{\small  -- version 3.4 --} \\
+November 2014  \\
+{\small  -- version 3.6 --} \\
 ~  \\
 \textit{\small Note du P\^ole de mod\'{e}lisation de l'Institut Pierre-Simon Laplace No 27 }\\
@@ -227,5 +227,5 @@
 \Large Gurvan Madec, and the NEMO team  \\
  \texttt{\small gurvan.madec@locean-ipsl.umpc.fr} \\
- \texttt{\small nemo\_st@hermes.locean-ipsl.umpc.fr} \\
+ \texttt{\small nemo\_st@locean-ipsl.umpc.fr} \\
 %{\small Laboratoire d'Oc\'{e}anographie  et du Climat: Exp\'{e}rimentation et Approches Num\'{e}riques }
 }
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_DIA.tex
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_DIA.tex	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_DIA.tex	(revision 5075)
@@ -466,5 +466,5 @@
 \end{verbatim}
 }}\end{alltt} 
-However it is often very convienent to define the file name with the name of the experiment, the output file frequency and the date of the beginning and the end of the simulation (which are informations stored either in the namelist or in the XML file). To do so, we added the following rule: if the id of the tag file is ''fileN''(where N = 1 to 99) or one of the predefined sections or moorings (see next subsection), the following part of the name and the name\_suffix (that can be inherited) will be automatically replaced by:\\
+However it is often very convienent to define the file name with the name of the experiment, the output file frequency and the date of the beginning and the end of the simulation (which are informations stored either in the namelist or in the XML file). To do so, we added the following rule: if the id of the tag file is ''fileN''(where N = 1 to 999 on 1 to 3 digits) or one of the predefined sections or moorings (see next subsection), the following part of the name and the name\_suffix (that can be inherited) will be automatically replaced by:\\
 \\
 \begin{tabular}{|p{4cm}|p{8cm}|}
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_DYN.tex
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_DYN.tex	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_DYN.tex	(revision 5075)
@@ -795,5 +795,5 @@
 %>   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >   >
 \begin{figure}[!t]    \begin{center}
-\includegraphics[width=0.7\textwidth]{./TexFiles/Figures/Fig_time_split.pdf}
+\includegraphics[width=0.7\textwidth]{./TexFiles/Figures/Fig_DYN_dynspg_ts.pdf}
 \caption{  \label{Fig_DYN_dynspg_ts}
 Schematic of the split-explicit time stepping scheme for the external 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_SBC.tex
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_SBC.tex	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Chap_SBC.tex	(revision 5075)
@@ -348,6 +348,6 @@
 horizontal and vertical dimensions of the associated variable and should 
 be equal to 1 over land and 0 elsewhere.
-The procedure can be recursively applied setting nn_lsm > 1 in namsbc namelist. 
-Note that nn_lsm=0 forces the code to not apply the procedure even if a file for land/sea mask is supplied.
+The procedure can be recursively applied setting nn\_lsm > 1 in namsbc namelist. 
+Note that nn\_lsm=0 forces the code to not apply the procedure even if a file for land/sea mask is supplied.
 
 \subsubsection{Bilinear Interpolation}
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Introduction.tex
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Introduction.tex	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/DOC/TexFiles/Chapters/Introduction.tex	(revision 5075)
@@ -19,5 +19,5 @@
 the model design. More specific information about running the model on different 
 computers, or how to set up a configuration, are found on the \NEMO web site 
-(www.locean-ipsl.upmc.fr/NEMO). 
+(www.nemo-ocean.eu). 
 
 The ocean component of \NEMO has been developed from the OPA model, 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso.fcm	(revision 5075)
@@ -17,4 +17,5 @@
 %NCDF_INC            -I/usr/local/netcdf-3.6.3/include
 %NCDF_LIB            -L/usr/local/netcdf-3.6.3/lib -lnetcdf
+%CPP                 cpp
 %FC                  mpxlf90_r
 %FCFLAGS             -O3 -qsuffix=f=f90  -qstrict -qalias=intptr -qsuppress=1501-245 -qarch=pwr6 -q64 -qrealsize=8 -qtune=pwr6 -qextname -qlargepage -qmaxmem=-1
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_debug.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_debug.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_debug.fcm	(revision 5075)
@@ -17,4 +17,5 @@
 %NCDF_INC            -I/usr/local/netcdf-3.6.3/include
 %NCDF_LIB            -L/usr/local/netcdf-3.6.3/lib -lnetcdf
+%CPP                 cpp
 %FC                  mpxlf90_r
 %FCFLAGS             -g -qsuffix=f=f90  -qstrict -qalias=intptr -qsuppress=1501-245 -qarch=pwr6 -q64 -qrealsize=8 -qtune=pwr6 -qextname -qlargepage -qmaxmem=-1
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_tools.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_tools.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-PW6_calypso_tools.fcm	(revision 5075)
@@ -17,4 +17,5 @@
 %NCDF_INC            -I/usr/local/netcdf-3.6.3/include
 %NCDF_LIB            -L/usr/local/netcdf-3.6.3/lib -lnetcdf
+%CPP                 cpp
 %FC                  xlf90
 %FCFLAGS             -O3 -qsuffix=f=f90  -qstrict -qsuppress=1501-245 -qarch=pwr6 -q64 -qrealsize=8 -qtune=pwr6 -qextname -qlargepage -qmaxmem=-1
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-gfortran_athena_xios.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-gfortran_athena_xios.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-gfortran_athena_xios.fcm	(revision 5075)
@@ -44,4 +44,5 @@
 %XIOS_LIB            -L%XIOS_HOME/lib -lxios
 
+%CPP                 cpp
 %FC                  mpif90
 %FCFLAGS             -fdefault-real-8 -fno-second-underscore -Dgfortran -ffree-line-length-none
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena.fcm	(revision 5075)
@@ -17,4 +17,5 @@
 %NCDF_INC -I$NETCDF/include
 %NCDF_LIB -L$NETCDF/lib -lnetcdf -lnetcdff
+%CPP                 cpp
 %FC mpiifort
 %FCFLAGS -r8 -O3 -xHost -fp-model source -traceback
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_debug.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_debug.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_debug.fcm	(revision 5075)
@@ -17,4 +17,5 @@
 %NCDF_INC -I$NETCDF/include
 %NCDF_LIB -L$NETCDF/lib -lnetcdf -lnetcdff
+%CPP                 cpp
 %FC mpiifort
 %FCFLAGS -fpe0 -g -r8 -O1 -xHost -fp-model source -traceback
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_tools.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_tools.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_tools.fcm	(revision 5075)
@@ -17,4 +17,5 @@
 %NCDF_INC -I$NETCDF/include
 %NCDF_LIB -L$NETCDF/lib -lnetcdf -lnetcdff
+%CPP                 cpp
 %FC ifort
 %FCFLAGS -r8 -O3 -xHost -fp-model source -traceback
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_xios.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_xios.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/CMCC/arch-ifort_athena_xios.fcm	(revision 5075)
@@ -32,16 +32,19 @@
 
 # required modules
-# module load  INTEL/intel_xe_2013 NETCDF/netcdf-4.3_parallel NETCDF/parallel-netcdf-1.3.1 HDF5/hdf5-1.8.11_parallel 
+# module load  INTEL/intel_xe_2013 NETCDF/netcdf-4.3_parallel NETCDF/parallel-netcdf-1.3.1 HDF5/hdf5-1.8.11_parallel
 
+# Environment variables set by user. Others should automatically define when loading modules.
+# export XIOS=/users/home/models/nemo/xios
 
 %NCDF_INC            -I$NETCDF/include -I$PNETCDF/include
 %NCDF_LIB            -L$NETCDF/lib -lnetcdff -lnetcdf -L$PNETCDF/lib -lpnetcdf
-%HDF5_INC            -I/users/home/opt/hdf5/hdf5-1.8.11_parallel/include
-%HDF5_LIB            -L/users/home/opt/hdf5/hdf5-1.8.11_parallel/lib -lhdf5_hl -lhdf5
-%XIOS_INC            -I/users/home/ans040/SOFTWARE/XIOS_athena/trunk/inc
-%XIOS_LIB            -L/users/home/ans040/SOFTWARE/XIOS_athena/trunk/lib -lxios
+%HDF5_INC            -I$PHDF5/include
+%HDF5_LIB            -L$PHDF5/lib -lhdf5_hl -lhdf5
+%XIOS_INC            -I$XIOS/inc
+%XIOS_LIB            -L$XIOS/lib -lxios
+%CPP                 cpp
 %FC                  mpiifort
-%FCFLAGS 	     -g -r8 -O3 -xHost -fp-model source -traceback
-%FFLAGS 	     -g -r8 -O3 -xHost -fp-model source -traceback
+%FCFLAGS             -r8 -O3 -xHost -fp-model source -traceback
+%FFLAGS              %FCFLAGS
 %LD                  mpiifort
 %FPPFLAGS            -P -C -traditional
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/INGV/arch-IBM_EKMAN_INGV.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/INGV/arch-IBM_EKMAN_INGV.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/INGV/arch-IBM_EKMAN_INGV.fcm	(revision 5075)
@@ -20,4 +20,5 @@
 %XIOS_ROOT           /home/delrosso/XIOS_447/trunk
 %MPI_INTEL           -I/srv/intel/impi/4.1.0.024/include
+%CPP                 cpp
 %FC                  mpiifort
 %FCFLAGS             -r8 -O3 -g -traceback 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-ALTIX_NAUTILUS_MPT.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-ALTIX_NAUTILUS_MPT.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-ALTIX_NAUTILUS_MPT.fcm	(revision 5075)
@@ -42,4 +42,5 @@
 %OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
 
+%CPP	             cpp
 %FC                  ifort
 %FCFLAGS             -r8 -O3 -fp-model precise -xT -ip -vec-report0
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_C2A_XIO.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_C2A_XIO.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_C2A_XIO.fcm	(revision 5075)
@@ -35,4 +35,6 @@
 
 %XLF90_LIB           -lxlf90_r
+
+%CPP	             cpp
 %FC                  mpxlf90_r
 %FCFLAGS             -qsuffix=f=f90 -qsuffix=cpp=F90 -qfree=f90 -O3 -qrealsize=8 -qarch=auto -qtune=auto -qinitauto
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_METO.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_METO.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_METO.fcm	(revision 5075)
@@ -19,9 +19,10 @@
 %NCDF_INC            -I/home/cr/ocean/hadcv/netcdf/4.1.3_seq/include
 %NCDF_LIB            -L/home/cr/ocean/hadcv/netcdf/4.1.3_seq/lib -lnetcdf -lnetcdff -lhdf5 -lhdf5_hl -lhdf5_fortran -lz
-%XIOS_INC            -I/data/nwp/ofrd/share/NEMO/xios_lib/seq/xios_r451/inc
-%XIOS_LIB            -L/data/nwp/ofrd/share/NEMO/xios_lib/seq/xios_r451/lib -lxios
+%XIOS_INC            -I/home/cr/ocean/hadcv/xios_lib/par/r521/xios/inc
+%XIOS_LIB            -L/home/cr/ocean/hadcv/xios_lib/par/r521/xios/lib -lxios
+%CPP	             cpp
 %FC                  mpxlf90_r
 %FCFLAGS             -qrealsize=8 -qextname -qsuffix=f=f90 -qarch=pwr7 -qtune=pwr7 -g -O2 -qstrict -qinitauto=7FBFFFFF
-%FFLAGS              -qrealsize=8 -qextname -qsuffix=f=f90 -qarch=pwr7 -qtune=pwr7 -g -O2 -qstrict -qinitauto=7FBFFFFF
+%FFLAGS              -qrealsize=8 -qextname -qarch=pwr7 -qtune=pwr7 -g -O2 -qstrict -qinitauto=7FBFFFFF -qfixed
 %LD                  mpCC_r
 %LDFLAGS             -lxlf90 -L/projects/um1/lib -lsig -O2 -L MASS
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_MONSOON.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_MONSOON.fcm	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-PW7_MONSOON.fcm	(revision 5075)
@@ -0,0 +1,33 @@
+# IBM POWER7  UKMO
+# NCDF_INC    netcdf include file
+# NCDF_LIB    netcdf library
+# XIOS_INC    XIOS include files
+# XIOS_LIB    XIOS library
+# FC          Fortran compiler command
+# FCFLAGS     Fortran compiler flags
+# FFLAGS      Fortran 77 compiler flags
+# LD          linker
+# LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries in a
+# FPPFLAGS    pre-processing flags
+# AR          assembler
+# ARFLAGS     assembler flags
+# MK          make
+# USER_INC    additional include files for the compiler,  e.g. -I<include dir>
+# USER_LIB    additional libraries to pass to the linker, e.g. -l<library>
+
+%NCDF_INC            -I/home/dcalve/netcdf/4.1.3_seq/include
+%NCDF_LIB            -L/home/dcalve/netcdf/4.1.3_seq/lib -lnetcdf -lnetcdff -lhdf5 -lhdf5_hl -lhdf5_fortran -lz
+%XIOS_INC            -I/home/dstork/xios_lib/par/r521/xios/inc
+%XIOS_LIB            -L/home/dstork/xios_lib/par/r521/xios/lib -lxios
+%CPP	             cpp
+%FC                  mpxlf90_r
+%FCFLAGS             -qrealsize=8 -qextname -qsuffix=f=f90 -qarch=pwr7 -qtune=pwr7 -g -O2 -qstrict -qinitauto=7FBFFFFF
+%FFLAGS              -qrealsize=8 -qextname -qarch=pwr7 -qtune=pwr7 -g -O2 -qstrict -qinitauto=7FBFFFFF -qfixed
+%LD                  mpCC_r
+%LDFLAGS             -lxlf90 -L/projects/um1/lib -lsig -O2 -L MASS
+%FPPFLAGS            -E -P -traditional -I/opt/ibmhpc/pecurrent/ppe.poe/include -I/usr/lpp/ppe.poe/include/thread64
+%AR                  ar
+%ARFLAGS             rs
+%MK                  gmake
+%USER_INC            %NCDF_INC %XIOS_INC
+%USER_LIB            %NCDF_LIB %XIOS_LIB
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_ADA.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_ADA.fcm	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_ADA.fcm	(revision 5075)
@@ -0,0 +1,54 @@
+# Ada  IBM x3750 at french IDRIS, http://www.idris.fr/ada/ada-hw-ada.html
+#
+# NCDF_HOME   root directory containing lib and include subdirectories for netcdf4
+# HDF5_HOME   root directory containing lib and include subdirectories for HDF5
+# XIOS_HOME   root directory containing lib for XIOS
+# OASIS_HOME  root directory containing lib for OASIS
+#
+# NCDF_INC    netcdf4 include file
+# NCDF_LIB    netcdf4 library
+# XIOS_INC    xios include file    (taken into accound only if key_iomput is activated)
+# XIOS_LIB    xios library         (taken into accound only if key_iomput is activated)
+# OASIS_INC   oasis include file   (taken into accound only if key_oasis3 is activated)
+# OASIS_LIB   oasis library        (taken into accound only if key_oasis3 is activated)
+#
+# FC          Fortran compiler command
+# FCFLAGS     Fortran compiler flags
+# FFLAGS      Fortran 77 compiler flags
+# LD          linker
+# LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries
+# FPPFLAGS    pre-processing flags
+# AR          assembler
+# ARFLAGS     assembler flags
+# MK          make
+# USER_INC    complete list of include files
+# USER_LIB    complete list of libraries to pass to the linker
+#
+# Note that:
+#  - unix variables "$..." are accpeted and will be evaluated before calling fcm.
+#  - fcm variables are starting with a % (and not a $)
+#
+%NCDF_HOME           /smplocal/pub/NetCDF/4.1.3/mpi
+%HDF5_HOME           /smplocal/pub/HDF5/1.8.9/par
+%XIOS_HOME           $WORKDIR/XIOS
+%OASIS_HOME          /not/yet/defined
+
+%NCDF_INC            -I%NCDF_HOME/include 
+%NCDF_LIB            -L%NCDF_HOME/lib -Bstatic -lnetcdff -lnetcdf -Bdynamic -L%HDF5_HOME/lib -Bstatic -lhdf5hl_fortran -lhdf5_hl -lhdf5_fortran -lhdf5 -Bdynamic -lz 
+%XIOS_INC            -I%XIOS_HOME/inc 
+%XIOS_LIB            -L%XIOS_HOME/lib -lxios
+%OASIS_INC           -I%OASIS_HOME/build/lib/mct -I%OASIS_HOME/build/lib/psmile.MPI1
+%OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
+
+%CPP	             cpp
+%FC                  mpiifort -c -cpp
+%FCFLAGS             -DCPP_PARA -i4 -r8 -O3 -xAVX -fp-model precise
+%FFLAGS              %FCFLAGS
+%LD                  mpiifort
+%LDFLAGS             -lstdc++
+%FPPFLAGS            -P -C -traditional
+%AR                  ar
+%ARFLAGS             rs
+%MK                  gmake
+%USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
+%USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_ADA_O0.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_ADA_O0.fcm	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_ADA_O0.fcm	(revision 5075)
@@ -0,0 +1,54 @@
+# Ada  IBM x3750 at french IDRIS, http://www.idris.fr/ada/ada-hw-ada.html
+#
+# NCDF_HOME   root directory containing lib and include subdirectories for netcdf4
+# HDF5_HOME   root directory containing lib and include subdirectories for HDF5
+# XIOS_HOME   root directory containing lib for XIOS
+# OASIS_HOME  root directory containing lib for OASIS
+#
+# NCDF_INC    netcdf4 include file
+# NCDF_LIB    netcdf4 library
+# XIOS_INC    xios include file    (taken into accound only if key_iomput is activated)
+# XIOS_LIB    xios library         (taken into accound only if key_iomput is activated)
+# OASIS_INC   oasis include file   (taken into accound only if key_oasis3 is activated)
+# OASIS_LIB   oasis library        (taken into accound only if key_oasis3 is activated)
+#
+# FC          Fortran compiler command
+# FCFLAGS     Fortran compiler flags
+# FFLAGS      Fortran 77 compiler flags
+# LD          linker
+# LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries
+# FPPFLAGS    pre-processing flags
+# AR          assembler
+# ARFLAGS     assembler flags
+# MK          make
+# USER_INC    complete list of include files
+# USER_LIB    complete list of libraries to pass to the linker
+#
+# Note that:
+#  - unix variables "$..." are accpeted and will be evaluated before calling fcm.
+#  - fcm variables are starting with a % (and not a $)
+#
+%NCDF_HOME           /smplocal/pub/NetCDF/4.1.3/mpi
+%HDF5_HOME           /smplocal/pub/HDF5/1.8.9/par
+%XIOS_HOME           $WORKDIR/XIOS
+%OASIS_HOME          /not/yet/defined
+
+%NCDF_INC            -I%NCDF_HOME/include 
+%NCDF_LIB            -L%NCDF_HOME/lib -Bstatic -lnetcdff -lnetcdf -Bdynamic -L%HDF5_HOME/lib -Bstatic -lhdf5hl_fortran -lhdf5_hl -lhdf5_fortran -lhdf5 -Bdynamic -lz 
+%XIOS_INC            -I%XIOS_HOME/inc 
+%XIOS_LIB            -L%XIOS_HOME/lib -lxios
+%OASIS_INC           -I%OASIS_HOME/build/lib/mct -I%OASIS_HOME/build/lib/psmile.MPI1
+%OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
+
+%CPP	             cpp
+%FC                  mpiifort -c -cpp
+%FCFLAGS             -DCPP_PARA -i4 -r8 -O0 -xAVX -fp-model precise
+%FFLAGS              %FCFLAGS
+%LD                  mpiifort
+%LDFLAGS             -lstdc++
+%FPPFLAGS            -P -C -traditional
+%AR                  ar
+%ARFLAGS             rs
+%MK                  gmake
+%USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
+%USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_CURIE.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_CURIE.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_CURIE.fcm	(revision 5075)
@@ -41,4 +41,5 @@
 %OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
 
+%CPP	             cpp
 %FC                  mpif90 -c -cpp
 # for Curie Fat Node
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_MOBILIS.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_MOBILIS.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_MOBILIS.fcm	(revision 5075)
@@ -46,4 +46,5 @@
 %OASIS_LIB           
 
+%CPP	             cpp
 %FC                  mpif90 -c -cpp
 %FCFLAGS             -i4 -r8 -O3 -fp-model source -xAVX
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_VAYU.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_VAYU.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_VAYU.fcm	(revision 5075)
@@ -41,4 +41,5 @@
 %OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
 
+%CPP	             cpp
 %FC                  mpif90 -c -cpp
 %FCFLAGS             -i4 -r8
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_YELLOWSTONE.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_YELLOWSTONE.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-X64_YELLOWSTONE.fcm	(revision 5075)
@@ -41,4 +41,5 @@
 %OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
 
+%CPP	             cpp
 %FC                  mpif90 -c -cpp
 %FCFLAGS            -i4 -r8 -O3 -fp-model precise -xAVX
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-XC_ARCHER.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-XC_ARCHER.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-XC_ARCHER.fcm	(revision 5075)
@@ -41,4 +41,5 @@
 #OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
 
+%CPP	             cpp
 %FC                  ftn
 #FCFLAGS             -em -s integer32 -s real64 -O3
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-XC_ARCHER_INTEL.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-XC_ARCHER_INTEL.fcm	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-XC_ARCHER_INTEL.fcm	(revision 5075)
@@ -0,0 +1,56 @@
+# compiler options for Archer CRAY XC-30 (using intel compiler)
+#
+# NCDF_HOME   root directory containing lib and include subdirectories for netcdf4
+# HDF5_HOME   root directory containing lib and include subdirectories for HDF5
+# XIOS_HOME   root directory containing lib for XIOS
+# OASIS_HOME  root directory containing lib for OASIS
+#
+# NCDF_INC    netcdf4 include file
+# NCDF_LIB    netcdf4 library
+# XIOS_INC    xios include file    (taken into accound only if key_iomput is activated)
+# XIOS_LIB    xios library         (taken into accound only if key_iomput is activated)
+# OASIS_INC   oasis include file   (taken into accound only if key_oasis3 is activated)
+# OASIS_LIB   oasis library        (taken into accound only if key_oasis3 is activated)
+#
+# FC          Fortran compiler command
+# FCFLAGS     Fortran compiler flags
+# FFLAGS      Fortran 77 compiler flags
+# LD          linker
+# LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries
+# FPPFLAGS    pre-processing flags
+# AR          assembler
+# ARFLAGS     assembler flags
+# MK          make
+# USER_INC    complete list of include files
+# USER_LIB    complete list of libraries to pass to the linker
+#
+# Note that:
+#  - unix variables "$..." are accpeted and will be evaluated before calling fcm.
+#  - fcm variables are starting with a % (and not a $)
+#
+%NCDF_HOME           $NETCDF_DIR
+%HDF5_HOME           $HDF5_DIR
+%XIOS_HOME           /work/n01/n01/acc/XIOS_r484
+#OASIS_HOME          
+
+%NCDF_INC            -I%NCDF_HOME/include -I%HDF5_HOME/include
+%NCDF_LIB            -L%HDF5_HOME/lib -L%NCDF_HOME/lib -lnetcdff -lnetcdf -lhdf5_hl -lhdf5 -lz
+%XIOS_INC            -I%XIOS_HOME/inc 
+%XIOS_LIB            -L%XIOS_HOME/lib -lxios
+#OASIS_INC           -I%OASIS_HOME/build/lib/mct -I%OASIS_HOME/build/lib/psmile.MPI1
+#OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
+
+%CPP	             cpp
+%FC                  ftn
+%FCFLAGS             -integer-size 32 -real-size 64 -O3 -fp-model source -zero -fpp -warn all
+%FFLAGS              -integer-size 32 -real-size 64 -O3 -fp-model source -zero -fpp -warn all
+%LD                  CC -Wl,"--allow-multiple-definition"
+%FPPFLAGS            -P -C -traditional
+%LDFLAGS
+%AR                  ar 
+%ARFLAGS             -r
+%MK                  gmake
+%USER_INC            %XIOS_INC %NCDF_INC
+%USER_LIB            %XIOS_LIB %NCDF_LIB
+#USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
+#USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-macport_osx.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-macport_osx.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-macport_osx.fcm	(revision 5075)
@@ -50,4 +50,5 @@
 %OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
 
+%CPP	             cpp-mp-4.8
 %FC	             mpif90 
 %FCFLAGS             -fdefault-real-8 -O3 -funroll-all-loops -fcray-pointer 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-openmpi_NAVITI_MERCATOR.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-openmpi_NAVITI_MERCATOR.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-openmpi_NAVITI_MERCATOR.fcm	(revision 5075)
@@ -19,4 +19,5 @@
 %NCDF_LIB            -L$NETCDF_LIB -lnetcdff -lnetcdf -L$HDF5_LIB -lhdf5_hl -lhdf5 -lz
 
+%CPP	             cpp
 %FC                  mpif90
 %FCFLAGS             -O2 -fp-model precise  -traceback -r8  -convert big_endian -assume byterecl
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-x3750_ADA.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/ARCH/arch-x3750_ADA.fcm	(revision 5074)
+++ 	(revision )
@@ -1,53 +1,0 @@
-# Ada  IBM x3750 at french IDRIS, http://www.idris.fr/ada/ada-hw-ada.html
-#
-# NCDF_HOME   root directory containing lib and include subdirectories for netcdf4
-# HDF5_HOME   root directory containing lib and include subdirectories for HDF5
-# XIOS_HOME   root directory containing lib for XIOS
-# OASIS_HOME  root directory containing lib for OASIS
-#
-# NCDF_INC    netcdf4 include file
-# NCDF_LIB    netcdf4 library
-# XIOS_INC    xios include file    (taken into accound only if key_iomput is activated)
-# XIOS_LIB    xios library         (taken into accound only if key_iomput is activated)
-# OASIS_INC   oasis include file   (taken into accound only if key_oasis3 is activated)
-# OASIS_LIB   oasis library        (taken into accound only if key_oasis3 is activated)
-#
-# FC          Fortran compiler command
-# FCFLAGS     Fortran compiler flags
-# FFLAGS      Fortran 77 compiler flags
-# LD          linker
-# LDFLAGS     linker flags, e.g. -L<lib dir> if you have libraries
-# FPPFLAGS    pre-processing flags
-# AR          assembler
-# ARFLAGS     assembler flags
-# MK          make
-# USER_INC    complete list of include files
-# USER_LIB    complete list of libraries to pass to the linker
-#
-# Note that:
-#  - unix variables "$..." are accpeted and will be evaluated before calling fcm.
-#  - fcm variables are starting with a % (and not a $)
-#
-%NCDF_HOME           /smplocal/pub/NetCDF/4.1.3/mpi
-%HDF5_HOME           /smplocal/pub/HDF5/1.8.9/par
-%XIOS_HOME           $WORKDIR/XIOS
-%OASIS_HOME          /not/yet/defined
-
-%NCDF_INC            -I%NCDF_HOME/include 
-%NCDF_LIB            -L%NCDF_HOME/lib -Bstatic -lnetcdff -lnetcdf -Bdynamic -L%HDF5_HOME/lib -Bstatic -lhdf5hl_fortran -lhdf5_hl -lhdf5_fortran -lhdf5 -Bdynamic -lz 
-%XIOS_INC            -I%XIOS_HOME/inc 
-%XIOS_LIB            -L%XIOS_HOME/lib -lxios
-%OASIS_INC           -I%OASIS_HOME/build/lib/mct -I%OASIS_HOME/build/lib/psmile.MPI1
-%OASIS_LIB           -L%OASIS_HOME/lib -lpsmile.MPI1 -lmct -lmpeu -lscrip
-
-%FC                  mpiifort -c -cpp
-%FCFLAGS             -DCPP_PARA -i4 -r8 -O3 -xAVX -fp-model precise
-%FFLAGS              %FCFLAGS
-%LD                  mpiifort
-%LDFLAGS             -lstdc++
-%FPPFLAGS            -P -C -traditional
-%AR                  ar
-%ARFLAGS             rs
-%MK                  gmake
-%USER_INC            %XIOS_INC %OASIS_INC %NCDF_INC
-%USER_LIB            %XIOS_LIB %OASIS_LIB %NCDF_LIB
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/AMM12/EXP00/iodef.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/AMM12/EXP00/iodef.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/AMM12/EXP00/iodef.xml	(revision 5075)
@@ -85,20 +85,4 @@
 	</file>
 	
-	<file id="file8" name_suffix="_icemod" description="ice variables" >
-	  <field field_ref="ice_pres"                     />
-	  <field field_ref="snowthic_cea" name="snd"     long_name="surface_snow_thickness"   />
-	  <field field_ref="icethic_cea"  name="sit"     long_name="sea_ice_thickness"        />
-	  <field field_ref="iceprod_cea"  name="sip"     long_name="sea_ice_thickness"        />
-	  <field field_ref="ist_ipa"      />
-	  <field field_ref="ioceflxb"     />
-	  <field field_ref="uice_ipa"     />
-	  <field field_ref="vice_ipa"     />
-	  <field field_ref="utau_ice"     />
-	  <field field_ref="vtau_ice"     />
-	  <field field_ref="qsr_io_cea"   />
-	  <field field_ref="qns_io_cea"   />
-	  <field field_ref="snowpre"      />
-	</file>
-	
       </file_group>
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/AMM12/EXP00/namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/AMM12/EXP00/namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/AMM12/EXP00/namelist_cfg	(revision 5075)
@@ -14,5 +14,4 @@
    cn_ocerst_in   = "amm12_restart_oce"   !  suffix of ocean restart name (input)
    cn_ocerst_out  = "restart_oce_out"   !  suffix of ocean restart name (input)
-   nn_istate   =       1   !  output the initial state (1) or not (0)
    nn_stock    =    1296   !  frequency of creation of a restart file (modulo referenced to 1)
    nn_write    =     144   !  frequency of write in the output file   (modulo referenced to nit000) 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/EXP00/iodef.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/EXP00/iodef.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/EXP00/iodef.xml	(revision 5075)
@@ -21,5 +21,5 @@
     -->
     
-    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
+    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
     
       <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/EXP00/namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/EXP00/namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/EXP00/namelist_cfg	(revision 5075)
@@ -7,9 +7,9 @@
    cn_exp      =  "PAPA"   !  experience name
    nn_it000    =       1   !  first time step
-   nn_itend    =   78840   !  last  time step
+   nn_itend    =   87600   !  last  time step
    nn_date0    =  20100615 !  date at nit_0000 (format yyyymmdd) used if ln_rstart=F or (ln_rstart=T and nn_rstctl=0 or 1)
    nn_leapy    =       1   !  Leap year calendar (1) or not (0)
-   nn_stock    =   78840   !  frequency of creation of a restart file (modulo referenced to 1)
-   nn_write    =      60   !  frequency of write in the output file   (modulo referenced to nn_it000)
+   nn_stock    =   87600   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =     240   !  frequency of write in the output file   (modulo referenced to nn_it000)
 /
 !-----------------------------------------------------------------------
@@ -38,7 +38,8 @@
 &namdom        !   space and time domain (bathymetry, mesh, timestep)
 !-----------------------------------------------------------------------
+   nn_bathy    =    0      !  compute (=0) or read (=1) the bathymetry file
    rn_bathy    = 4198.     !  value of the bathymetry. if (=0) bottom flat at jpkm1
-   nn_msh      =    3      !  create (=1) a mesh file or not (=0)
-   rn_rdt      =  400.     !  time step for the dynamics (and tracer if nn_acc=0)
+   nn_msh      =    0      !  create (=1) a mesh file or not (=0)
+   rn_rdt      =  360.     !  time step for the dynamics (and tracer if nn_acc=0)
    rn_rdtmin   =  360.           !  minimum time step on tracers (used if nn_acc=1)
    rn_rdtmax   =  360.           !  maximum time step on tracers (used if nn_acc=1)
@@ -72,4 +73,9 @@
 /
 !-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d")
+!-----------------------------------------------------------------------
+   ln_c1d_locpt= .false.   ! Localization of 1D config in a grid (T) or independant point (F)
+/
+!-----------------------------------------------------------------------
 &namtsd    !   data : Temperature  & Salinity
 !-----------------------------------------------------------------------
@@ -81,5 +87,5 @@
    cn_dir        = './'     !  root directory for the location of the runoff files
    ln_tsd_init   = .true.   !  Initialisation of ocean T & S with T &S input data (T) or not (F)
-   ln_tsd_tradmp = .true.   !  damping of ocean T & S toward T &S input data (T) or not (F)
+   ln_tsd_tradmp = .false.   !  damping of ocean T & S toward T &S input data (T) or not (F)
 /
 !-----------------------------------------------------------------------
@@ -112,12 +118,12 @@
 !              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
 !              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_wndi     = 'forcing_PAPASTATION' ,         1         , 'wndwe'   ,   .true.     , .false. , 'yearly' , '' , '', ''
-   sn_wndj     = 'forcing_PAPASTATION' ,         1         , 'wndsn'   ,   .true.     , .false. , 'yearly' , '' , '', ''
-   sn_qsr      = 'forcing_PAPASTATION' ,         1         , 'qsr'     ,   .false.    , .false. , 'yearly' , '' , '', ''
-   sn_qlw      = 'forcing_PAPASTATION' ,         1         , 'qlw'     ,   .false.    , .false. , 'yearly' , '' , '', ''
-   sn_tair     = 'forcing_PAPASTATION' ,         1         , 'tair'    ,   .true.     , .false. , 'yearly' , '' , '', ''
-   sn_humi     = 'forcing_PAPASTATION' ,         1         , 'humi'    ,   .true.     , .false. , 'yearly' , '' , '', ''
-   sn_prec     = 'forcing_PAPASTATION' ,         1         , 'prec'    ,   .false.    , .false. , 'yearly' , '' , '', ''
-   sn_snow     = 'forcing_PAPASTATION' ,         1         , 'snow'    ,   .false.    , .false. , 'yearly' , '' , '', ''
+   sn_wndi     = 'forcing_PAPASTATION_1h' ,         1         , 'wndwe'   ,   .true.     , .false. , 'yearly' , '' , '', ''
+   sn_wndj     = 'forcing_PAPASTATION_1h' ,         1         , 'wndsn'   ,   .true.     , .false. , 'yearly' , '' , '', ''
+   sn_qsr      = 'forcing_PAPASTATION_1h' ,         1         , 'qsr'     ,   .false.    , .false. , 'yearly' , '' , '', ''
+   sn_qlw      = 'forcing_PAPASTATION_1h' ,         1         , 'qlw'     ,   .false.    , .false. , 'yearly' , '' , '', ''
+   sn_tair     = 'forcing_PAPASTATION_1h' ,         1         , 'tair'    ,   .true.     , .false. , 'yearly' , '' , '', ''
+   sn_humi     = 'forcing_PAPASTATION_1h' ,         1         , 'humi'    ,   .true.     , .false. , 'yearly' , '' , '', ''
+   sn_prec     = 'forcing_PAPASTATION_1h' ,         1         , 'prec'    ,   .false.    , .false. , 'yearly' , '' , '', ''
+   sn_snow     = 'forcing_PAPASTATION_1h' ,         1         , 'snow'    ,   .false.    , .false. , 'yearly' , '' , '', ''
    ln_2m         = .true.    !  air temperature and humidity referenced at 2m (T) instead 10m (F)
 /
@@ -225,4 +231,7 @@
 &namtra_ldf    !   lateral diffusion scheme for tracers
 !----------------------------------------------------------------------------------
+!----------------------------------------------------------------------------------
+   ln_traldf_hor    =  .true.   !  horizontal (geopotential)   (needs "key_ldfslp" when ln_sco=T)
+   ln_traldf_iso    =  .false.  !  iso-neutral                 (needs "key_ldfslp")
    rn_aeiv_0        =     0.    !  eddy induced velocity coefficient [m2/s]
    rn_aht_0         =     0.    !  horizontal eddy diffusivity for tracers [m2/s]
@@ -244,4 +253,8 @@
 /
 !-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namdyn_hpg    !   Hydrostatic pressure gradient option
 !-----------------------------------------------------------------------
@@ -258,6 +271,6 @@
 &namzdf        !   vertical physics
 !-----------------------------------------------------------------------
-   rn_avm0     =   5.0e-6  !rbb 1.2e-4  !  vertical eddy viscosity   [m2/s]          (background Kz if not "key_zdfcst")
-   rn_avt0     =   5.0e-6  !rbb 1.2e-5  !  vertical eddy diffusivity [m2/s]          (background Kz if not "key_zdfcst")
+!   rn_avm0     =   5.0e-6  !rbb 1.2e-4  !  vertical eddy viscosity   [m2/s]          (background Kz if not "key_zdfcst")
+!   rn_avt0     =   5.0e-6  !rbb 1.2e-5  !  vertical eddy diffusivity [m2/s]          (background Kz if not "key_zdfcst")
    ln_zdfevd   = .false. !rbb .true.    !  enhanced vertical diffusion (evd) (T) or not (F)
 /
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/cpp_C1D_PAPA.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/cpp_C1D_PAPA.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/C1D_PAPA/cpp_C1D_PAPA.fcm	(revision 5075)
@@ -1,1 +1,1 @@
- bld::tool::fppkeys key_c1d key_dynspg_flt key_diahth key_zdfgls key_iomput key_mpp_mpi
+ bld::tool::fppkeys key_c1d key_zdfgls
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE/EXP00/namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE/EXP00/namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE/EXP00/namelist_cfg	(revision 5075)
@@ -11,4 +11,7 @@
    nn_stock    =    4320   !  frequency of creation of a restart file (modulo referenced to 1)
    nn_write    =      60   !  frequency of write in the output file   (modulo referenced to nn_it000)
+
+   ln_clobber  = .true.    !  clobber (overwrite) an existing file
+
 /
 !-----------------------------------------------------------------------
@@ -82,5 +85,5 @@
 !-----------------------------------------------------------------------
    nn_fsbc     = 1         !  frequency of surface boundary condition computation
-                           !     (also = the frequency of sea-ice model call)
+   !                       !     (also = the frequency of sea-ice model call)
    ln_ana      = .true.    !  analytical formulation                    (T => fill namsbc_ana )
    ln_blk_core = .false.   !  CORE bulk formulation                     (T => fill namsbc_core)
@@ -198,10 +201,33 @@
 &nameos        !   ocean physical parameters
 !-----------------------------------------------------------------------
-   nn_eos      =   2       !  type of equation of state and Brunt-Vaisala frequency
+   nn_eos      =  0       !  type of equation of state and Brunt-Vaisala frequency
+                                 !  =-1, TEOS-10 
+                                 !  = 0, EOS-80 
+                                 !  = 1, S-EOS   (simplified eos)
+   ln_useCT    = .false.  ! use of Conservative Temp. ==> surface CT converted in Pot. Temp. in sbcssm
+   !                             !
+   !                      ! S-EOS coefficients :
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  1.6550e-1      !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  7.6554e-1      !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  5.9520e-2      !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  7.4914e-4      !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  1.4970e-4      !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  1.1090e-5      !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  2.4341e-3      !  cabbeling coeff in T*S  (=0 for linear eos)
+!!org GYRE   rn_alpha    =   2.0e-4  !  thermal expension coefficient (nn_eos= 1 or 2)
+!!org GYRE   rn_beta     =   7.7e-4  !  saline  expension coefficient (nn_eos= 2)
+!!org  caution  now a0 = alpha / rau0   with rau0 = 1026
 /
 !-----------------------------------------------------------------------
 &namtra_adv    !   advection scheme for tracer
 !-----------------------------------------------------------------------
-   ln_traadv_msc_ups=  .false.  !  use upstream scheme within muscl 
+   ln_traadv_cen2   =  .false.   !  2nd order centered scheme
+   ln_traadv_tvd    =  .true.    !  TVD scheme
+   ln_traadv_muscl  =  .false.   !  MUSCL scheme
+   ln_traadv_muscl2 =  .false.   !  MUSCL2 scheme + cen2 at boundaries
+   ln_traadv_ubs    =  .false.   !  UBS scheme
+   ln_traadv_qck    =  .false.   !  QUICKEST scheme
+   ln_traadv_msc_ups=  .false.   !  use upstream scheme within muscl
 /
 !-----------------------------------------------------------------------
@@ -242,4 +268,5 @@
 !namdyn_spg    !   surface pressure gradient   (CPP key only)
 !-----------------------------------------------------------------------
+
 !-----------------------------------------------------------------------
 &namdyn_ldf    !   lateral diffusion on momentum
@@ -301,5 +328,21 @@
 !              !       or mixed-layer trends or barotropic vorticity    ("key_trdmld" or     "key_trdvor")
 !-----------------------------------------------------------------------
-/
+   ln_glo_trd  = .false.   ! (T) global domain averaged diag for T, T^2, KE, and PE
+   ln_dyn_trd  = .false.   ! (T) 3D momentum trend output
+   ln_dyn_mxl  = .FALSE.   ! (T) 2D momentum trends averaged over the mixed layer (not coded yet)
+   ln_vor_trd  = .FALSE.   ! (T) 2D barotropic vorticity trends (not coded yet)
+   ln_KE_trd   = .false.   ! (T) 3D Kinetic   Energy     trends
+   ln_PE_trd   = .false.   ! (T) 3D Potential Energy     trends
+   ln_tra_trd  = .false.    ! (T) 3D tracer trend output
+   ln_tra_mxl  = .false.   ! (T) 2D tracer trends averaged over the mixed layer (not coded yet)
+   nn_trd      = 365       !  print frequency (ln_glo_trd=T) (unit=time step)
+/
+!!gm   nn_ctls     =   0       !  control surface type in mixed-layer trends (0,1 or n<jpk)
+!!gm   rn_ucf      =   1.      !  unit conversion factor (=1 -> /seconds ; =86400. -> /day)
+!!gm   cn_trdrst_in      = "restart_mld"   ! suffix of ocean restart name (input)
+!!gm   cn_trdrst_out     = "restart_mld"   ! suffix of ocean restart name (output)
+!!gm   ln_trdmld_restart = .false.         !  restart for ML diagnostics
+!!gm   ln_trdmld_instant = .false.         !  flag to diagnose trends of instantantaneous or mean ML T/S
+!!gm
 !-----------------------------------------------------------------------
 &namflo       !   float parameters                                      ("key_float")
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE/cpp_GYRE.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE/cpp_GYRE.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE/cpp_GYRE.fcm	(revision 5075)
@@ -1,1 +1,1 @@
- bld::tool::fppkeys key_dynspg_flt key_ldfslp key_zdftke key_iomput key_mpp_mpi
+ bld::tool::fppkeys key_dynspg_flt key_ldfslp key_zdftke key_iomput key_mpp_mpi key_nosignedzero
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_BFM/EXP00/namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_BFM/EXP00/namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_BFM/EXP00/namelist_cfg	(revision 5075)
@@ -206,5 +206,22 @@
 &nameos        !   ocean physical parameters
 !-----------------------------------------------------------------------
-   nn_eos      =   2       !  type of equation of state and Brunt-Vaisala frequency
+   nn_eos      =  0       !  type of equation of state and Brunt-Vaisala frequency
+                                 !  =-1, TEOS-10
+                                 !  = 0, EOS-80
+                                 !  = 1, S-EOS   (simplified eos)
+   ln_useCT    = .false.  ! use of Conservative Temp. ==> surface CT converted in Pot. Temp. in sbcssm
+   !                             !
+   !                      ! S-EOS coefficients :
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  1.6550e-1      !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  7.6554e-1      !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  5.9520e-2      !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  7.4914e-4      !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  1.4970e-4      !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  1.1090e-5      !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  2.4341e-3      !  cabbeling coeff in T*S  (=0 for linear eos)
+!!org GYRE   rn_alpha    =   2.0e-4  !  thermal expension coefficient (nn_eos= 1 or 2)
+!!org GYRE   rn_beta     =   7.7e-4  !  saline  expension coefficient (nn_eos= 2)
+!!org  caution  now a0 = alpha / rau0   with rau0 = 1026
 /
 !-----------------------------------------------------------------------
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_PISCES/EXP00/namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_PISCES/EXP00/namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_PISCES/EXP00/namelist_cfg	(revision 5075)
@@ -121,5 +121,22 @@
 &nameos        !   ocean physical parameters
 !-----------------------------------------------------------------------
-   nn_eos      =   2       !  type of equation of state and Brunt-Vaisala frequency
+   nn_eos      =  0       !  type of equation of state and Brunt-Vaisala frequency
+                                 !  =-1, TEOS-10
+                                 !  = 0, EOS-80
+                                 !  = 1, S-EOS   (simplified eos)
+   ln_useCT    = .false.  ! use of Conservative Temp. ==> surface CT converted in Pot. Temp. in sbcssm
+   !                             !
+   !                      ! S-EOS coefficients :
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  1.6550e-1      !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  7.6554e-1      !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  5.9520e-2      !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  7.4914e-4      !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  1.4970e-4      !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  1.1090e-5      !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  2.4341e-3      !  cabbeling coeff in T*S  (=0 for linear eos)
+!!org GYRE   rn_alpha    =   2.0e-4  !  thermal expension coefficient (nn_eos= 1 or 2)
+!!org GYRE   rn_beta     =   7.7e-4  !  saline  expension coefficient (nn_eos= 2)
+!!org  caution  now a0 = alpha / rau0   with rau0 = 1026
 /
 !-----------------------------------------------------------------------
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_PISCES/cpp_GYRE_PISCES.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_PISCES/cpp_GYRE_PISCES.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/GYRE_PISCES/cpp_GYRE_PISCES.fcm	(revision 5075)
@@ -1,1 +1,1 @@
-bld::tool::fppkeys  key_dynspg_flt key_ldfslp key_zdftke key_top key_pisces_reduced key_iomput key_mpp_mpi 
+bld::tool::fppkeys  key_dynspg_flt key_ldfslp key_zdftke key_top key_pisces_reduced key_iomput key_mpp_mpi
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/domain_def.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/domain_def.xml	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/domain_def.xml	(revision 5075)
@@ -0,0 +1,1 @@
+link ../../SHARED/domain_def.xml
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/field_def.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/field_def.xml	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/field_def.xml	(revision 5075)
@@ -0,0 +1,1 @@
+link ../../SHARED/field_def.xml
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/iodef.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/iodef.xml	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/iodef.xml	(revision 5075)
@@ -0,0 +1,115 @@
+<?xml version="1.0"?>
+<simulation> 
+
+ <context id="nemo" time_origin="1900-01-01 00:00:00" >
+    
+    <!-- $id$ -->
+    
+    <!-- 
+============================================================================================================
+=                                  definition of all existing variables                                    =
+=                                            DO NOT CHANGE                                                 =
+============================================================================================================
+    -->
+    <field_definition src="./field_def.xml"/>
+    <!-- 
+============================================================================================================
+=                                           output files definition                                        =
+=                                            Define your own files                                         =
+=                                         put the variables you want...                                    =
+============================================================================================================
+    -->
+    
+    <file_definition type="one_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
+    
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."/> <!-- 1h files -->
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->
+     
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."/> <!-- 1d files -->
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->  
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."/> <!-- real monthly files -->
+	<file id="file1" output_freq="1mo" name_suffix="_grid_T" description="ocean T grid variables" >
+	  <field field_ref="toce"         name="votemper"  />
+	  <field field_ref="soce"         name="vosaline"  />
+	  <field field_ref="sst"          name="sosstsst"  />
+	  <field field_ref="sss"          name="sosaline"  />
+	  <field field_ref="ssh"          name="sossheig"  />
+          <!-- variable for ice shelf -->
+          <field field_ref="qisf"         name="sohflisf"  />
+          <field field_ref="fwfisf"       name="sowflisf"  />
+          <field field_ref="isfgammat"    name="sogammat"  />
+          <field field_ref="isfgammas"    name="sogammas"  />
+        </file>
+	<file id="file2" output_freq="1mo" name_suffix="_grid_U" description="ocean U grid variables" >
+          <field field_ref="uoce"         name="vozocrtx"  />
+        </file>
+	<file id="file3" output_freq="1mo" name_suffix="_grid_V" description="ocean V grid variables" >
+          <field field_ref="voce"         name="vomecrty"  /> 
+        </file>
+      </file_group>
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."/> <!-- real yearly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
+
+   </file_definition>
+    
+    <!-- 
+============================================================================================================
+= grid definition = = DO NOT CHANGE =
+============================================================================================================
+    -->
+    
+   <axis_definition>  
+      <axis id="deptht" long_name="Vertical T levels" unit="m" positive="down" />
+      <axis id="depthu" long_name="Vertical U levels" unit="m" positive="down" />
+      <axis id="depthv" long_name="Vertical V levels" unit="m" positive="down" />
+      <axis id="depthw" long_name="Vertical W levels" unit="m" positive="down" />
+      <axis id="nfloat" long_name="Float number"      unit="-"  />
+      <axis id="icbcla" long_name="Iceberg class"     unit="-"  />
+   </axis_definition> 
+    
+   <domain_definition src="./domain_def.xml"/>
+   
+   <grid_definition>    
+     <grid id="grid_T_2D" domain_ref="grid_T"/>
+     <grid id="grid_T_3D" domain_ref="grid_T" axis_ref="deptht"/>
+     <grid id="grid_U_2D" domain_ref="grid_U"/>
+     <grid id="grid_U_3D" domain_ref="grid_U" axis_ref="depthu"/>
+     <grid id="grid_V_2D" domain_ref="grid_V"/>
+     <grid id="grid_V_3D" domain_ref="grid_V" axis_ref="depthv"/>
+     <grid id="grid_W_2D" domain_ref="grid_W"/>
+     <grid id="grid_W_3D" domain_ref="grid_W" axis_ref="depthw"/>
+    </grid_definition> 
+
+  </context>
+  
+
+  <context id="xios">
+
+      <variable_definition>
+	
+     <!-- 
+        We must have buffer_size > jpi*jpj*jpk*8 (with jpi and jpj the subdomain size)
+-->
+	  <variable id="buffer_size"               type="integer">10000000</variable>
+	  <variable id="buffer_server_factor_size" type="integer">2</variable>
+	  <variable id="info_level"                type="integer">0</variable>
+	  <variable id="using_server"              type="boolean">false</variable>
+	  <variable id="using_oasis"               type="boolean">false</variable>
+	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
+	
+      </variable_definition>
+               
+  </context>
+  
+</simulation>
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/namelist_cfg	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/namelist_cfg	(revision 5075)
@@ -0,0 +1,664 @@
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+!! NEMO/OPA  :  1 - run manager      (namrun, namcfg)
+!! namelists    2 - Domain           (namzgr, namzgr_sco, namdom, namtsd)
+!!              3 - Surface boundary (namsbc, namsbc_ana, namsbc_flx, namsbc_clio, namsbc_core, namsbc_sas
+!!                                    namsbc_cpl, namtra_qsr, namsbc_rnf,
+!!                                    namsbc_apr, namsbc_ssr, namsbc_alb)
+!!              4 - lateral boundary (namlbc, namcla, namobc, namagrif, nambdy, nambdy_tide)
+!!              5 - bottom  boundary (nambfr, nambbc, nambbl)
+!!              6 - Tracer           (nameos, namtra_adv, namtra_ldf, namtra_dmp)
+!!              7 - dynamics         (namdyn_adv, namdyn_vor, namdyn_hpg, namdyn_spg, namdyn_ldf)
+!!              8 - Verical physics  (namzdf, namzdf_ric, namzdf_tke, namzdf_kpp, namzdf_ddm, namzdf_tmx)
+!!              9 - diagnostics      (namnc4, namtrd, namspr, namflo, namptr, namhsb)
+!!             10 - miscellaneous    (namsol, nammpp, namctl)
+!!             11 - Obs & Assim      (namobs, nam_asminc)
+!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+
+!!======================================================================
+!!                   ***  Run management namelists  ***
+!!======================================================================
+!!   namrun        parameters of the run
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namrun        !   parameters of the run
+!-----------------------------------------------------------------------
+   nn_no       =  1        !  job number (no more used...)
+   cn_exp      =  "ISOMIP" !  experience name
+   nn_it000    =  1        !  first time step
+   nn_itend    =  490560   !  last  time step (std 5475)
+   nn_date0    =  010101   !  date at nit_0000 (format yyyymmdd) used if ln_rstart=F or (ln_rstart=T and nn_rstctl=0 or 1)
+   nn_leapy    =       0   !  Leap year calendar (1) or not (0)
+   ln_rstart   = .false.   !  start from rest (F) or from a restart file (T)
+   nn_euler    =       1   !  = 0 : start with forward time step if ln_rstart=.true.
+   nn_rstctl   =       0   !  restart control => activated only if ln_rstart = T
+                           !    = 0 nn_date0 read in namelist ; nn_it000 : read in namelist
+                           !    = 1 nn_date0 read in namelist ; nn_it000 : check consistancy between namelist and restart
+                           !    = 2 nn_date0 read in restart  ; nn_it000 : check consistancy between namelist and restart
+   cn_ocerst_in  = "restart"   !  suffix of ocean restart name (input)
+   cn_ocerst_out = "restart"   !  suffix of ocean restart name (output)
+   nn_istate   =       0   !  output the initial state (1) or not (0)
+   nn_stock    =  999999   !  frequency of creation of a restart file (modulo referenced to 1)
+   nn_write    =  999999   !  frequency of write in the output file   (modulo referenced to nn_it000)
+   ln_dimgnnn  = .false.   !  DIMG file format: 1 file for all processors (F) or by processor (T)
+   ln_mskland  = .false.   !  mask land points in NetCDF outputs (costly: + ~15%)
+   ln_clobber  = .false.   !  clobber (overwrite) an existing file
+   nn_chunksz  =       0   !  chunksize (bytes) for NetCDF file (works only with iom_nf90 routines)
+/
+!
+!-----------------------------------------------------------------------
+&namcfg     !   default parameters of the configuration      
+!-----------------------------------------------------------------------
+   cp_cfg      =  "isomip"            !  name of the configuration
+   cp_cfz      =         ''            !  name of the zoom of configuration
+   jp_cfg      =     0.3               !  resolution of the configuration
+   jpidta      =      51               !  1st lateral dimension ( >= jpi )
+   jpjdta      =     101               !  2nd    "         "    ( >= jpj )
+   jpkdta      =      31               !  number of levels      ( >= jpk )
+   jpiglo      =      51               !  1st dimension of global domain --> i =jpidta
+   jpjglo      =     101               !  2nd    -                  -    --> j  =jpjdta
+   jpizoom     =       1               !  left bottom (i,j) indices of the zoom
+   jpjzoom     =       1               !  in data domain indices
+   jperio      =       0               !  lateral cond. type (between 0 and 6)
+                                       !  = 0 closed                 ;   = 1 cyclic East-West
+                                       !  = 2 equatorial symmetric   ;   = 3 North fold T-point pivot 
+                                       !  = 4 cyclic East-West AND North fold T-point pivot
+                                       !  = 5 North fold F-point pivot
+                                       !  = 6 cyclic East-West AND North fold F-point pivot
+/
+!!======================================================================
+!!                      ***  Domain namelists  ***
+!!======================================================================
+!!   namzgr       vertical coordinate
+!!   namzgr_sco   s-coordinate or hybrid z-s-coordinate
+!!   namdom       space and time domain (bathymetry, mesh, timestep)
+!!   namtsd       data: temperature & salinity
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzgr        !   vertical coordinate
+!-----------------------------------------------------------------------
+   ln_zco      = .false.   !  z-coordinate - full    steps   (T/F)      ("key_zco" may also be defined)
+   ln_zps      = .true.    !  z-coordinate - partial steps   (T/F)
+   ln_sco      = .false.   !  s- or hybrid z-s-coordinate    (T/F)
+   ln_isfcav   = .true.    !  ice shelf cavity
+/
+!-----------------------------------------------------------------------
+&namzgr_sco    !   s-coordinate or hybrid z-s-coordinate
+!-----------------------------------------------------------------------
+ 
+!-----------------------------------------------------------------------
+&namdom        !   space and time domain (bathymetry, mesh, timestep)
+!-----------------------------------------------------------------------
+   nn_bathy    =    0      !  compute (=0) or read (=1) the bathymetry file
+   rn_bathy    =    0.     !  value of the bathymetry. if (=0) bottom flat at jpkm1
+   nn_closea   =    0      !  remove (=0) or keep (=1) closed seas and lakes (ORCA)
+   nn_msh      =    3      !  create (=1) a mesh file or not (=0)
+   rn_hmin     =   -3.     !  min depth of the ocean (>0) or min number of ocean level (<0)
+   rn_e3zps_min=   20.     !  partial step thickness is set larger than the minimum of
+   rn_e3zps_rat=    0.1    !  rn_e3zps_min and rn_e3zps_rat*e3t, with 0<rn_e3zps_rat<1
+                           !
+   rn_rdt      = 1800.     !  time step for the dynamics (and tracer if nn_acc=0)
+   rn_atfp     =    0.1    !  asselin time filter parameter
+   nn_acc      =    0      !  acceleration of convergence : =1      used, rdt < rdttra(k)
+                                 !                          =0, not used, rdt = rdttra
+   rn_rdtmin   = 1800.           !  minimum time step on tracers (used if nn_acc=1)
+   rn_rdtmax   = 1800.           !  maximum time step on tracers (used if nn_acc=1)
+   rn_rdth     =  800.           !  depth variation of tracer time step  (used if nn_acc=1)
+   ln_crs      = .false.      !  Logical switch for coarsening module
+   jphgr_msh   =       1               !  type of horizontal mesh
+                                       !  = 0 curvilinear coordinate on the sphere read in coordinate.nc
+                                       !  = 1 geographical mesh on the sphere with regular grid-spacing
+                                       !  = 2 f-plane with regular grid-spacing
+                                       !  = 3 beta-plane with regular grid-spacing
+                                       !  = 4 Mercator grid with T/U point at the equator
+   ppglam0     =       0.0             !  longitude of first raw and column T-point (jphgr_msh = 1)
+   ppgphi0     =     -80.0             ! latitude  of first raw and column T-point (jphgr_msh = 1)
+   ppe1_deg    =       0.3             !  zonal      grid-spacing (degrees)
+   ppe2_deg    =       0.1             !  meridional grid-spacing (degrees)
+   ppe1_m      =   999999.0            !  zonal      grid-spacing (degrees)
+   ppe2_m      =   999999.0            !  meridional grid-spacing (degrees)
+   ppsur       =   999999.0            !  ORCA r4, r2 and r05 coefficients
+   ppa0        =   999999.0            ! (default coefficients)
+   ppa1        =   999999.0            !
+   ppkth       =        0.0            !
+   ppacr       =        7.0            !
+   ppdzmin     =       30.             !  Minimum vertical spacing
+   pphmax      =      900.             !  Maximum depth
+   ldbletanh   =    .FALSE.            !  Use/do not use double tanf function for vertical coordinates
+   ppa2        =    999999.0           !  Double tanh function parameters
+   ppkth2      =    999999.0           !
+   ppacr2      =    999999.0           !
+/
+!-----------------------------------------------------------------------
+&namsplit      !   time splitting parameters                            ("key_dynspg_ts")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcrs        !   Grid coarsening for dynamics output and/or
+               !   passive tracer coarsened online simulations
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtsd    !   data : Temperature  & Salinity
+!-----------------------------------------------------------------------
+!-----------------------------------------------------------------------
+!          !  file name                            ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
+!          !                                       !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
+   sn_tem  = 'data_1m_potential_temperature_nomask',         -1        ,'votemper' ,    .true.    , .true. , 'yearly'   , ''       ,   ''    ,    ''
+   sn_sal  = 'data_1m_salinity_nomask'             ,         -1        ,'vosaline' ,    .true.    , .true. , 'yearly'   , ''       ,   ''    ,    ''
+   !
+   cn_dir        = './'     !  root directory for the location of the runoff files
+   ln_tsd_init   = .false.   !  Initialisation of ocean T & S with T &S input data (T) or not (F)
+   ln_tsd_tradmp = .false.   !  damping of ocean T & S toward T &S input data (T) or not (F)
+/
+!!======================================================================
+!!            ***  Surface Boundary Condition namelists  ***
+!!======================================================================
+!!   namsbc          surface boundary condition
+!!   namsbc_ana      analytical         formulation
+!!   namsbc_flx      flux               formulation
+!!   namsbc_clio     CLIO bulk formulae formulation
+!!   namsbc_core     CORE bulk formulae formulation
+!!   namsbc_mfs      MFS  bulk formulae formulation
+!!   namsbc_cpl      CouPLed            formulation                     ("key_coupled")
+!!   namsbc_sas      StAndalone Surface module
+!!   namtra_qsr      penetrative solar radiation
+!!   namsbc_rnf      river runoffs
+!!   namsbc_isf      ice shelf melting/freezing
+!!   namsbc_apr      Atmospheric Pressure
+!!   namsbc_ssr      sea surface restoring term (for T and/or S)
+!!   namsbc_alb      albedo parameters
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsbc        !   Surface Boundary Condition (surface module)
+!-----------------------------------------------------------------------
+   nn_fsbc     = 6         !  frequency of surface boundary condition computation
+                           !     (also = the frequency of sea-ice model call)
+   ln_ana      = .true.    !  analytical formulation                    (T => fill namsbc_ana )
+   ln_blk_core = .false.   !  CORE bulk formulation                     (T => fill namsbc_core)
+   nn_ice      = 0         !  =0 no ice boundary condition   ,
+                           !  =1 use observed ice-cover      , 
+                           !  =2 ice-model used                
+   nn_ice_embd = 0         !  =0 levitating ice (no mass exchange, concentration/dilution effect)
+                           !  =1 levitating ice with mass and salt exchange but no presure effect
+                           !  =2 embedded sea-ice (full salt and mass exchanges and pressure)
+   ln_rnf      = .false.   !  runoffs                                   (T => fill namsbc_rnf)
+   nn_isf      = 1         !  ice shelf melting/freezing                (/=0 => fill namsbc_isf)
+                           !  0 = no isf               / 1 = presence of ISF 
+                           !  2 = bg03 parametrisation / 3 = rnf file for isf
+                           !  4 = ISF are prescribed
+                           !  options 1 and 4 need ln_isfcav = .true. (domzgr)
+   ln_ssr      = .false.   !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
+   nn_fwb      = 1         !  FreshWater Budget: =0 unchecked
+                           !     =1 global mean of e-p-r set to zero at each time step
+                           !     =2 annual global mean of e-p-r set to zero
+/
+!-----------------------------------------------------------------------
+&namsbc_ana    !   analytical surface boundary condition
+!-----------------------------------------------------------------------
+   nn_tau000   =   0       !  gently increase the stress over the first ntau_rst time-steps
+   rn_utau0    =   0.e0    !  uniform value for the i-stress
+   rn_vtau0    =   0.e0    !  uniform value for the j-stress
+   rn_qns0     =   0.e0    !  uniform value for the total heat flux
+   rn_qsr0     =   0.e0    !  uniform value for the solar radiation
+   rn_emp0     =   0.e0    !  uniform value for the freswater budget (E-P)
+/
+!-----------------------------------------------------------------------
+&namsbc_flx    !   surface boundary condition : flux formulation
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_clio   !   namsbc_clio  CLIO bulk formulae
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_core   !   namsbc_core  CORE bulk formulae
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_mfs   !   namsbc_mfs  MFS bulk formulae
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_coupled")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_sas    !   analytical surface boundary condition
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_qsr    !   penetrative solar radiation
+!-----------------------------------------------------------------------
+   ln_traqsr   = .false.    !  Light penetration (T) or not (F)
+/
+!-----------------------------------------------------------------------
+&namsbc_rnf    !   runoffs namelist surface boundary condition
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF) 
+!-----------------------------------------------------------------------
+!              ! file name ! frequency (hours) ! variable ! time interpol. !  clim   ! 'yearly'/ ! weights  ! rotation !
+!              !           !  (if <0  months)  !   name   !    (logical)   !  (T/F)  ! 'monthly' ! filename ! pairing  !
+! nn_isf == 4
+   sn_qisf      = 'rnfisf' ,         -12      ,'sohflisf',    .false.      , .true.  , 'yearly'  ,  ''      ,   ''
+   sn_fwfisf    = 'rnfisf' ,         -12      ,'sowflisf',    .false.      , .true.  , 'yearly'  ,  ''      ,   ''
+! nn_isf == 3
+   sn_rnfisf    = 'runoffs' ,         -12      ,'sofwfisf',    .false.      , .true.  , 'yearly'  ,  ''      ,   ''
+! nn_isf == 2 and 3
+   sn_depmax_isf = 'runoffs' ,       -12        ,'sozisfmax' ,   .false.  , .true.  , 'yearly'  ,  ''      ,   ''
+   sn_depmin_isf = 'runoffs' ,       -12        ,'sozisfmin' ,   .false.  , .true.  , 'yearly'  ,  ''      ,   ''
+! nn_isf == 2
+   sn_Leff_isf = 'rnfisf' ,       0          ,'Leff'         ,   .false.  , .true.  , 'yearly'  ,  ''      ,   ''
+! for all case
+   ln_divisf   = .true.  ! apply isf melting as a mass flux or in the salinity trend. (maybe I should remove this option as for runoff?)
+! only for nn_isf = 1 or 2
+   rn_gammat0  = 1.0e-4   ! gammat coefficient used in blk formula
+   rn_gammas0  = 1.0e-4   ! gammas coefficient used in blk formula
+! only for nn_isf = 1
+   nn_isfblk   =  1       ! 1 ISOMIP ; 2 conservative (3 equation formulation, Jenkins et al. 1991 ??)
+   rn_hisf_tbl =  30.      ! thickness of the top boundary layer           (Losh et al. 2008)
+                          ! 0 => thickness of the tbl = thickness of the first wet cell
+   ln_conserve = .true.   ! conservative case (take into account meltwater advection)
+   nn_gammablk = 0        ! 0 = cst Gammat (= gammat/s)
+                          ! 1 = velocity dependend Gamma (u* * gammat/s)  (Jenkins et al. 2010)
+                          !     if you want to keep the cd as in global config, adjust rn_gammat0 to compensate
+                          ! 2 = velocity and stability dependent Gamma    Holland et al. 1999
+/
+!-----------------------------------------------------------------------
+&namsbc_apr    !   Atmospheric pressure used as ocean forcing or in bulk
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_ssr    !   surface boundary condition : sea surface restoring
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_alb    !   albedo parameters
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namberg       !   iceberg parameters
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!               ***  Lateral boundary condition  ***
+!!======================================================================
+!!   namlbc        lateral momentum boundary condition
+!!   namcla        cross land advection
+!!   namobc        open boundaries parameters                           ("key_obc")
+!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
+!!   nambdy        Unstructured open boundaries                         ("key_bdy")
+!!   namtide       Tidal forcing at open boundaries                     ("key_bdy_tides")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namlbc        !   lateral momentum boundary condition
+!-----------------------------------------------------------------------
+   rn_shlat    =    0.     !  shlat = 0  !  0 < shlat < 2  !  shlat = 2  !  2 < shlat
+                           !  free slip  !   partial slip  !   no slip   ! strong slip
+/
+!-----------------------------------------------------------------------
+&namcla        !   cross land advection
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namobc        !   open boundaries parameters                           ("key_obc")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namagrif      !  AGRIF zoom                                            ("key_agrif")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_tide      !   tide parameters (#ifdef key_tide)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy        !  unstructured open boundaries                          ("key_bdy")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_dta      !  open boundaries - external data           ("key_bdy")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nambdy_tide     ! tidal forcing at open boundaries
+!-----------------------------------------------------------------------
+/
+!!======================================================================
+!!                 ***  Bottom boundary condition  ***
+!!======================================================================
+!!   nambfr        bottom friction
+!!   nambbc        bottom temperature boundary condition
+!!   nambbl        bottom boundary layer scheme                         ("key_trabbl")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nambfr        !   bottom/top friction
+!-----------------------------------------------------------------------
+   nn_bfr      =    2      !  type of bottom friction :   = 0 : free slip,  = 1 : linear friction
+                           !                              = 2 : nonlinear friction
+   rn_bfri1    =    4.e-4  !  bottom drag coefficient (linear case)
+   rn_bfri2    =    1.e-3  !  bottom drag coefficient (non linear case). Minimum coeft if ln_loglayer=T
+   rn_bfri2_max =   1.e-1  !  max. bottom drag coefficient (non linear case and ln_loglayer=T)
+   rn_bfeb2    =    2.5e-3 !  bottom turbulent kinetic energy background  (m2/s2)
+   rn_bfrz0    =    3.e-3  !  bottom roughness [m] if ln_loglayer=T 
+   ln_bfr2d    = .false.   !  horizontal variation of the bottom friction coef (read a 2D mask file )
+   rn_bfrien   =    50.    !  local multiplying factor of bfr (ln_bfr2d=T)
+   rn_tfri1    =    4.e-4  !  top drag coefficient (linear case)
+   rn_tfri2    =    2.5e-3 !  top drag coefficient (non linear case). Minimum coeft if ln_loglayer=T
+   rn_tfri2_max =   1.e-1  !  max. top drag coefficient (non linear case and ln_loglayer=T)
+   rn_tfeb2    =    0.0    !  top turbulent kinetic energy background  (m2/s2)
+   rn_tfrz0    =    3.e-3  !  top roughness [m] if ln_loglayer=T
+   ln_tfr2d    = .false.   !  horizontal variation of the top friction coef (read a 2D mask file )
+   rn_tfrien   =    50.    !  local multiplying factor of tfr (ln_tfr2d=T)
+
+   ln_bfrimp   = .true.    !  implicit bottom friction (requires ln_zdfexp = .false. if true)
+   ln_loglayer = .false.   !  logarithmic formulation (non linear case)
+/
+!-----------------------------------------------------------------------
+&nambbc        !   bottom temperature boundary condition
+!-----------------------------------------------------------------------
+   ln_trabbc   = .false.    !  Apply a geothermal heating at the ocean bottom
+/
+!-----------------------------------------------------------------------
+&nambbl        !   bottom boundary layer scheme
+!-----------------------------------------------------------------------
+   nn_bbl_ldf  =  0      !  diffusive bbl (=1)   or not (=0)
+   nn_bbl_adv  =  0      !  advective bbl (=1/2) or not (=0)
+/
+
+!!======================================================================
+!!                        Tracer (T & S ) namelists
+!!======================================================================
+!!   nameos        equation of state
+!!   namtra_adv    advection scheme
+!!   namtra_ldf    lateral diffusion scheme
+!!   namtra_dmp    T & S newtonian damping
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&nameos        !   ocean physical parameters
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_adv    !   advection scheme for tracer
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_adv_mle !   mixed layer eddy parametrisation (Fox-Kemper param)
+!-----------------------------------------------------------------------
+   ln_mle    = .false.      ! (T) use the Mixed Layer Eddy (MLE) parameterisation
+/
+!----------------------------------------------------------------------------------
+&namtra_ldf    !   lateral diffusion scheme for tracers
+!----------------------------------------------------------------------------------
+   !                       !  Operator type:
+   ln_traldf_lap    =  .true.   !  laplacian operator
+   ln_traldf_bilap  =  .false.  !  bilaplacian operator
+   !                       !  Direction of action:
+   ln_traldf_level  =  .false.  !  iso-level
+   ln_traldf_hor    =  .true.   !  horizontal (geopotential)   (needs "key_ldfslp" when ln_sco=T)
+   ln_traldf_iso    =  .false   !  iso-neutral                 (needs "key_ldfslp")
+   !		       	   !  Griffies parameters              (all need "key_ldfslp")
+   ln_traldf_grif   =  .false.  !  use griffies triads
+   ln_traldf_gdia   =  .false.  !  output griffies eddy velocities
+   ln_triad_iso     =  .false.  !  pure lateral mixing in ML
+   ln_botmix_grif   =  .false.  !  lateral mixing on bottom
+   !                       !  Coefficients
+   ! Eddy-induced (GM) advection always used with Griffies; otherwise needs "key_traldf_eiv"
+   ! Value rn_aeiv_0 is ignored unless = 0 with Held-Larichev spatially varying aeiv
+   !                                  (key_traldf_c2d & key_traldf_eiv & key_orca_r2, _r1 or _r05)
+   rn_aeiv_0        =     0.    !  eddy induced velocity coefficient [m2/s]
+   rn_aht_0         =   100.    !  horizontal eddy diffusivity for tracers [m2/s]
+   rn_ahtb_0        =     0.    !  background eddy diffusivity for ldf_iso [m2/s]
+   !                                           (normally=0; not used with Griffies)
+   rn_slpmax        =     0.01  !  slope limit
+   rn_chsmag        =     1.    !  multiplicative factor in Smagorinsky diffusivity
+   rn_smsh          =     1.    !  Smagorinsky diffusivity: = 0 - use only sheer
+   rn_aht_m         =   100.    !  upper limit or stability criteria for lateral eddy diffusivity (m2/s)
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping
+!-----------------------------------------------------------------------
+   ln_tradmp   =  .false.   !  add a damping termn (T) or not (F)
+/
+
+!!======================================================================
+!!                      ***  Dynamics namelists  ***
+!!======================================================================
+!!   namdyn_adv    formulation of the momentum advection
+!!   namdyn_vor    advection scheme
+!!   namdyn_hpg    hydrostatic pressure gradient
+!!   namdyn_spg    surface pressure gradient                            (CPP key only)
+!!   namdyn_ldf    lateral diffusion scheme
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namdyn_adv    !   formulation of the momentum advection
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_vvl    !   vertical coordinate options
+!-----------------------------------------------------------------------
+   ln_vvl_zstar  = .false.           !  zstar vertical coordinate                   
+/
+!-----------------------------------------------------------------------
+&namdyn_vor    !   option of physics/algorithm (not control by CPP keys)
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_hpg    !   Hydrostatic pressure gradient option
+!-----------------------------------------------------------------------
+   ln_hpg_zps  = .false.   !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .true.    !  s-coordinate (standard jacobian formulation)
+   ln_dynhpg_imp = .false. !  time stepping: semi-implicit time scheme  (T)
+                                 !           centered      time scheme  (F)
+/
+!-----------------------------------------------------------------------
+!namdyn_spg    !   surface pressure gradient   (CPP key only)
+!-----------------------------------------------------------------------
+!                          !  explicit free surface                     ("key_dynspg_exp")
+!                          !  filtered free surface                     ("key_dynspg_flt")
+!                          !  split-explicit free surface               ("key_dynspg_ts")
+
+!-----------------------------------------------------------------------
+&namdyn_ldf    !   lateral diffusion on momentum
+!-----------------------------------------------------------------------
+   !                       !  Type of the operator :
+   ln_dynldf_lap    =  .true.   !  laplacian operator
+   ln_dynldf_bilap  =  .false.  !  bilaplacian operator
+   !                       !  Direction of action  :
+   ln_dynldf_level  =  .false.  !  iso-level
+   ln_dynldf_hor    =  .true.   !  horizontal (geopotential)            (require "key_ldfslp" in s-coord.)
+   ln_dynldf_iso    =  .false.  !  iso-neutral                          (require "key_ldfslp")
+   !                       !  Coefficient
+   rn_ahm_0_lap     =   600.    !  horizontal laplacian eddy viscosity   [m2/s]
+   rn_ahmb_0        =     0.    !  background eddy viscosity for ldf_iso [m2/s]
+   rn_ahm_0_blp     =     0.    !  horizontal bilaplacian eddy viscosity [m4/s]
+   rn_cmsmag_1      =     3.    !  constant in laplacian Smagorinsky viscosity
+   rn_cmsmag_2      =     3     !  constant in bilaplacian Smagorinsky viscosity
+   rn_cmsh          =     1.    !  1 or 0 , if 0 -use only shear for Smagorinsky viscosity
+   rn_ahm_m_blp     =    -1.e12 !  upper limit for bilap  abs(ahm) < min( dx^4/128rdt, rn_ahm_m_blp)
+   rn_ahm_m_lap     =   600.    !  upper limit for lap  ahm < min(dx^2/16rdt, rn_ahm_m_lap)
+/
+
+!!======================================================================
+!!             Tracers & Dynamics vertical physics namelists
+!!======================================================================
+!!    namzdf        vertical physics
+!!    namzdf_ric    richardson number dependent vertical mixing         ("key_zdfric")
+!!    namzdf_tke    TKE dependent vertical mixing                       ("key_zdftke")
+!!    namzdf_kpp    KPP dependent vertical mixing                       ("key_zdfkpp")
+!!    namzdf_ddm    double diffusive mixing parameterization            ("key_zdfddm")
+!!    namzdf_tmx    tidal mixing parameterization                       ("key_zdftmx")
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namzdf        !   vertical physics
+!-----------------------------------------------------------------------
+   rn_avm0     =   1.0e-3  !  vertical eddy viscosity   [m2/s]          (background Kz if not "key_zdfcst")
+   rn_avt0     =   5.0e-5  !  vertical eddy diffusivity [m2/s]          (background Kz if not "key_zdfcst")
+   nn_avb      =    0      !  profile for background avt & avm (=1) or not (=0)
+   nn_havtb    =    0      !  horizontal shape for avtb (=1) or not (=0)
+   ln_zdfevd   = .true.    !  enhanced vertical diffusion (evd) (T) or not (F)
+   nn_evdm     =    1      !  evd apply on tracer (=0) or on tracer and momentum (=1)
+   rn_avevd    =   0.1     !  evd mixing coefficient [m2/s]
+   ln_zdfnpc   = .false.   !  Non-Penetrative Convective algorithm (T) or not (F)
+   nn_npc      =    1            !  frequency of application of npc
+   nn_npcp     =  365            !  npc control print frequency
+   ln_zdfexp   = .false.   !  time-stepping: split-explicit (T) or implicit (F) time stepping
+   nn_zdfexp   =    3            !  number of sub-timestep for ln_zdfexp=T
+/
+!-----------------------------------------------------------------------
+&namzdf_ric    !   richardson number dependent vertical diffusion       ("key_zdfric" )
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  ("key_zdftke")
+!-----------------------------------------------------------------------
+/
+!------------------------------------------------------------------------
+&namzdf_kpp    !   K-Profile Parameterization dependent vertical mixing  ("key_zdfkpp", and optionally:
+!------------------------------------------------------------------------ "key_kppcustom" or "key_kpplktb")
+/
+!-----------------------------------------------------------------------
+&namzdf_gls                !   GLS vertical diffusion                   ("key_zdfgls")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_ddm    !   double diffusive mixing parameterization             ("key_zdfddm")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namzdf_tmx    !   tidal mixing parameterization                        ("key_zdftmx")
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!                  ***  Miscellaneous namelists  ***
+!!======================================================================
+!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi)
+!!   namctl            Control prints & Benchmark
+!!   namsol            elliptic solver / island / free surface
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namsol        !   elliptic solver / island / free surface
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
+!-----------------------------------------------------------------------
+   cn_mpi_send =  'I'      !  mpi send/recieve type   ='S', 'B', or 'I' for standard send,
+                           !  buffer blocking send or immediate non-blocking sends, resp.
+   nn_buffer   =   0       !  size in bytes of exported buffer ('B' case), 0 no exportation
+   ln_nnogather=  .false.  !  activate code to avoid mpi_allgather use at the northfold
+   jpni        =   0       !  jpni   number of processors following i (set automatically if < 1)
+   jpnj        =   0       !  jpnj   number of processors following j (set automatically if < 1)
+   jpnij       =   0       !  jpnij  number of local domains (set automatically if < 1)
+/
+!-----------------------------------------------------------------------
+&namctl        !   Control prints & Benchmark
+!-----------------------------------------------------------------------
+   ln_ctl      = .false.   !  trends control print (expensive!)
+   nn_print    =    0      !  level of print (0 no extra print)
+   nn_ictls    =    0      !  start i indice of control sum (use to compare mono versus
+   nn_ictle    =    0      !  end   i indice of control sum        multi processor runs
+   nn_jctls    =    0      !  start j indice of control               over a subdomain)
+   nn_jctle    =    0      !  end   j indice of control
+   nn_isplt    =    1      !  number of processors in i-direction
+   nn_jsplt    =    1      !  number of processors in j-direction
+   nn_bench    =    0      !  Bench mode (1/0): CAUTION use zero except for bench
+                           !     (no physical validity of the results)
+   nn_timing   =    0      !  timing by routine activated (=1) creates timing.output file, or not (=0)
+/
+!-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d_uvd    !   data: U & V currents                                 ("key_c1d")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d")
+!-----------------------------------------------------------------------
+   ln_dyndmp   =  .false.  !  add a damping term (T) or not (F)
+/
+!!======================================================================
+!!                  ***  Diagnostics namelists  ***
+!!======================================================================
+!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
+!!   namtrd       dynamics and/or tracer trends                         ("key_trddyn","key_trdtra","key_trdmld")
+!!   namflo       float parameters                                      ("key_float")
+!!   namptr       Poleward Transport Diagnostics
+!!   namhsb       Heat and salt budgets
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namnc4        !   netcdf4 chunking and compression settings            ("key_netcdf4")
+!-----------------------------------------------------------------------
+   nn_nchunks_i=   4       !  number of chunks in i-dimension
+   nn_nchunks_j=   4       !  number of chunks in j-dimension
+   nn_nchunks_k=   31      !  number of chunks in k-dimension
+                           !  setting nn_nchunks_k = jpk will give a chunk size of 1 in the vertical which
+                           !  is optimal for postprocessing which works exclusively with horizontal slabs
+   ln_nc4zip   = .true.    !  (T) use netcdf4 chunking and compression
+                           !  (F) ignore chunking information and produce netcdf3-compatible files
+/
+!-----------------------------------------------------------------------
+&namtrd        !   diagnostics on dynamics and/or tracer trends         ("key_trddyn" and/or "key_trdtra")
+!              !       or mixed-layer trends or barotropic vorticity    ("key_trdmld" or     "key_trdvor")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namflo       !   float parameters                                      ("key_float")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namptr       !   Poleward Transport Diagnostic
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namhsb       !  Heat and salt budgets
+!-----------------------------------------------------------------------
+   ln_diahsb  = .false.    !  check the heat and salt budgets (T) or not (F)
+/ 
+!-----------------------------------------------------------------------
+&nam_diaharm   !   Harmonic analysis of tidal constituents ('key_diaharm')
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdct        ! transports through sections
+!-----------------------------------------------------------------------
+/
+
+!!======================================================================
+!!            ***  Observation & Assimilation namelists ***
+!!======================================================================
+!!   namobs       observation and model comparison                      ('key_diaobs')
+!!   nam_asminc   assimilation increments                               ('key_asminc')
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namobs       !  observation usage switch                               ('key_diaobs')
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc   !   assimilation increments                               ('key_asminc')
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namsbc_wave   ! External fields from wave model
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namdyn_nept  !   Neptune effect (simplified: lateral and vertical diffusions removed)
+!-----------------------------------------------------------------------
+/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/namelist_ref
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/namelist_ref	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/EXP00/namelist_ref	(revision 5075)
@@ -0,0 +1,1 @@
+link ../../SHARED/namelist_ref
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/cpp_ISOMIP.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/cpp_ISOMIP.fcm	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ISOMIP/cpp_ISOMIP.fcm	(revision 5075)
@@ -0,0 +1,1 @@
+ bld::tool::fppkeys key_dynspg_flt key_zdfcst key_iomput key_mpp_mpi key_mpp_rep  key_ldfslp
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/1_namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/1_namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/1_namelist_cfg	(revision 5075)
@@ -55,4 +55,13 @@
 /
 !-----------------------------------------------------------------------
+&namsplit      !   time splitting parameters                            ("key_dynspg_ts")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcrs        !   Grid coarsening for dynamics output and/or
+               !   passive tracer coarsened online simulations
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namtsd    !   data : Temperature  & Salinity
 !-----------------------------------------------------------------------
@@ -72,10 +81,34 @@
 /
 !-----------------------------------------------------------------------
-&namsbc_core   !   namsbc_core  CORE bulk formulea
-!-----------------------------------------------------------------------
+&namsbc_core   !   namsbc_core  CORE bulk formulae
+!-----------------------------------------------------------------------
+!              !  file name                    ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights                               ! rotation ! land/sea mask !
+!              !                               !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename                              ! pairing  ! filename      !
+   sn_wndi     = 'u_10.15JUNE2009_fill'        ,         6         , 'U_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bicubic.nc'      , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'        ,         6         , 'V_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bicubic.nc'      , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'    ,        24         , 'SWDN_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'    ,        24         , 'LWDN_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'        ,         6         , 'T_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'        ,         6         , 'Q_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill' ,        -1         , 'PRC_MOD1',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill' ,        -1         , 'SNOW'    ,   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_tdif     = 'taudif_core'                 ,        24         , 'taudif'  ,   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   cn_dir      = './'      !  root directory for the location of the bulk files
+   ln_2m       = .false.   !  air temperature and humidity referenced at 2m (T) instead 10m (F)
+   ln_taudif   = .false.   !  HF tau contribution: use "mean of stress module - module of the mean stress" data
+   ln_bulk2z   = .false.   !  Air temperature/humidity and wind vectors are referenced at heights rn_zqt and rn_zu
+   rn_zqt      = 3.        !  Air temperature and humidity reference height (m) (ln_bulk2z)
+   rn_zu       = 4.        !  Wind vector reference height (m)                  (ln_bulk2z)
+   rn_pfac     = 1.        !  multiplicative factor for precipitation (total & snow)
+   rn_efac     = 1.        !  multiplicative factor for evaporation (0. or 1.)
+   rn_vfac     = 0.        !  multiplicative factor for ocean/ice velocity 
+                           !  in the calculation of the wind stress (0.=absolute winds or 1.=relative winds)
 /
 !-----------------------------------------------------------------------
 &namtra_qsr    !   penetrative solar radiation
 !-----------------------------------------------------------------------
+!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation !
+!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  !
+   sn_chl      ='chlorophyll',        -1         , 'CHLA'    ,   .true.     , .true. , 'yearly'  , 'weights_bilin.nc'       , ''
 /
 !-----------------------------------------------------------------------
@@ -106,4 +139,9 @@
 &nameos        !   ocean physical parameters
 !-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping
+!-----------------------------------------------------------------------
+   ln_tradmp   =  .false.   !  add a damping termn (T) or not (F)
 /
 !-----------------------------------------------------------------------
@@ -183,2 +221,10 @@
 !-----------------------------------------------------------------------
 /
+!-----------------------------------------------------------------------
+&namobs       !  observation usage                                      ('key_diaobs')
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc   !   assimilation increments                               ('key_asminc')
+!-----------------------------------------------------------------------
+/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/iodef.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/iodef.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/iodef.xml	(revision 5075)
@@ -82,5 +82,4 @@
 	  <field field_ref="iceprod_cea"  name="sip"     long_name="sea_ice_thickness"        />
 	  <field field_ref="ist_ipa"      />
-	  <field field_ref="ioceflxb"     />
 	  <field field_ref="uice_ipa"     />
 	  <field field_ref="vice_ipa"     />
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/EXP00/namelist_cfg	(revision 5075)
@@ -188,2 +188,10 @@
 !-----------------------------------------------------------------------
 /
+!-----------------------------------------------------------------------
+&namobs       !  observation usage                                      ('key_diaobs')
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc   !   assimilation increments                               ('key_asminc')
+!-----------------------------------------------------------------------
+/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/README
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/README	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/README	(revision 5075)
@@ -24,6 +24,10 @@
 
 
-
-
+#----------------------------------------------------------------------
+# HOW TO USE 
+#----------------------------------------------------------------------
+./std_main.sh -plot -pdf
+or
+./std_main.sh -ts -pdf
 
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_IceFrac.pro
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_IceFrac.pro	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_IceFrac.pro	(revision 5075)
@@ -21,9 +21,9 @@
   
   IF keyword_set(arc) THEN BEGIN 
-    domdef, 20, 380, 50, 90
+    domdef, 20, 380, 40, 90
     map = [90, 0, 0]
   ENDIF
   IF keyword_set(ant) THEN BEGIN 
-    domdef, 20, 380, -90, -50
+    domdef, 20, 380, -90, -40
     map = [-90, 0, 0]
   ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_MLD_ortho.pro
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_MLD_ortho.pro	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_MLD_ortho.pro	(revision 5075)
@@ -0,0 +1,48 @@
+pro std_plot_MLD_ortho, MLD1, MLD2, ARC = arc, ANT = ant, POSTSCRIPT = postscript, _extra = ex
+
+  compile_opt idl2, strictarrsubs
+
+@common  
+@std_common
+
+  cdti3 = string(cnt, format = '(i3.3)')
+  print, cdti3 + ') ' + blabla
+
+  var = 'MLD'
+  IF keyword_set(arc) THEN var = var+'_Arc'
+  IF keyword_set(ant) THEN var = var+'_Ant'
+
+  filename = cdti3 + '_'+var+'_'+std_file1_T
+  if std_file1_T NE std_file2_T then filename = filename + '_'+std_file2_T
+  if KEYWORD_SET(postscript) then openps, filename+'.ps', portrait = 1
+  
+  IF keyword_set(arc) THEN BEGIN 
+    domdef, 20, 380, 40, 90
+    map = [90, 0, 0]
+  ENDIF
+  IF keyword_set(ant) THEN BEGIN 
+    domdef, 20, 380, -90, -40
+    map = [-90, 0, 0]
+  ENDIF
+;
+;  varunit = .unit
+;
+  title = var+'!C'+std_file1_T
+;                                ;
+  plt, MLD1.arr, label=4, cb_label=[0, 15, 25, 50, 75, 100, 125, 150, 250, 400, 600, 850], format = '(I3)' $
+       , small = [1, 2, 1], COAST_THICK = 2, TITLE = title $
+       , /ORTHO, MAP = map, /PORTRAIT, _extra = ex
+  if std_file1_T NE std_file2_T then begin            
+    title = title + ' - '+ std_file2_T
+    plt, MLD1.arr - MLD2.arr,  MIN = -80., MAX = 80., INTER = 10., format = '(I3)' $
+       , small = [1, 2, 2], COAST_THICK = 2, TITLE = title $
+       , /ORTHO, MAP = map, /NOERASE, _extra = ex
+  endif
+
+  domdef
+
+  htmltxt = [ htmltxt, '<hr>'+blabla, '<br><img width="80%" src='+filename+'.png  />  ' ]
+  if KEYWORD_SET(postscript) then closeps
+
+  return
+end
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_all.pro
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_all.pro	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_all.pro	(revision 5075)
@@ -172,6 +172,6 @@
   Ithi_april_1 = {arr:1./float(cnt) * total(reform(Ithi_1.arr[*, *, temporary(april)],nxt,nyt,cnt), 3), unit:Ithi_1.unit}
   jan = where(mm EQ 1, cnt)
+  Ithi_jan_1 = {arr:1./float(cnt) * total(reform(Ithi_1.arr[*, *, temporary(jan)],nxt,nyt,cnt), 3), unit:Ithi_1.unit} 
   sept = where(mm EQ 9, cnt)
-  Ithi_jan_1 = {arr:1./float(cnt) * total(reform(Ithi_1.arr[*, *, temporary(jan)],nxt,nyt,cnt), 3), unit:Ithi_1.unit} 
   Ithi_sept_1 = {arr:1./float(cnt) * total(reform(Ithi_1.arr[*, *, temporary(sept)],nxt,nyt,cnt), 3), unit:Ithi_1.unit} 
   undefine, Ithi_1
@@ -288,5 +288,5 @@
      Isal_sept_2 = {arr:-1}
    ENDELSE
-;
+
   IvelU_1 = read_ncdf(getenv('VAR1_IvelU'), allrecords = allrec, filename = std_file1_I ) 
   IvelV_1 = read_ncdf(getenv('VAR1_IvelV'), allrecords = allrec, filename = std_file1_I ) 
@@ -335,5 +335,5 @@
     Ivelo_sept_2 = {arr:-1}
   ENDELSE
-;
+
   Iage_1 = read_ncdf(getenv('VAR1_Iage'), allrecords = allrec, filename = std_file1_I ) 
   caldat, time, mm
@@ -396,5 +396,5 @@
   cnt = cnt+1   &   blabla = 'Erp salinity damping term'
   IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_erp, ERP1, ERP2, _extra = ex
-;
+;;
   cnt = cnt+1   &   blabla = 'Evaporation - Precipitation - Runoff term'
   IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_emp, EMP1, EMP2, _extra = ex
@@ -439,4 +439,10 @@
   IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_mld, MLD1, MLD2, MLD, _extra = ex
 ;
+  cnt = cnt+1   &   blabla = 'Mixed layer depth ortho plan ARCTIC'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_MLD_ortho, MLD1, MLD2, /ARC, _extra = ex
+;sf
+  cnt = cnt+1   &   blabla = 'Mixed layer depth ortho plan ANTARTIC'
+  IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_MLD_ortho, MLD1, MLD2, /ANT, _extra = ex
+;sf
   cnt = cnt+1   &   blabla = 'Zonal mean Mixed layer depth'
   IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_ZonMld, MLD1, MLD2, MLD, _extra = ex
@@ -564,5 +570,5 @@
   cnt = cnt+1   &   blabla = 'Antartic Ice Velocity: SEPT'
   IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceVel, IvelU_sept_1, IvelU_sept_2, IvelV_sept_1, IvelV_sept_2, Ivelo_sept_1, Ivelo_sept_2, /ANT,  /SEPT, _extra = ex
-;
+
   cnt = cnt+1   &   blabla = 'Arctic Ice Age: MARCH'
   IF doplot EQ cnt OR doplot EQ 0 THEN std_plot_IceAge, Iage_march_1, Iage_march_2, Ifra_march_1, Ifra_march_2, /ARC, /MARCH, _extra = ex
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh	(revision 5075)
@@ -21,10 +21,10 @@
 #idl_command=idl71
 #
-PS_DIR=$( pwd )/OR2LPv36_ps_plot
-PDF_DIR=$( pwd )/OR2LPv36_pdf_plot
+PS_DIR=$( pwd )/p4H25a50-testht_ps_plot
+PDF_DIR=$( pwd )/p4H25a50-testht_pdf_plot
 HTML_DIR=$( pwd )/html_plot
 SAXO_DIR=/Users/sflod/SAXO_DIR
 #
-DIR_DATA=/Users/sflod/idl_PLOTS/DATA_STORE/RUN_CLIMATO/500y_pisces     # path of data in NetCDF format
+DIR_DATA=/Users/sflod/idl_PLOTS/DATA_STORE/RUN_CLIMATO/lim3_ada     # path of data in NetCDF format
 DIR_CLIMATO=/Users/sflod/idl_PLOTS/CLIMATOLOGIES    # path of climatological data
 DIR_MASK=/Users/sflod/idl_PLOTS/MASK  # path of mask files (ex: subbasins)
@@ -54,48 +54,48 @@
 #
 #===================== EXP1 =====================
-# 23610101_23701231
-FILE1_T=OR2LPv36_23610101_23701231_1Y_grid_T.nc   # exp1 grid T input file
-FILE1_U=OR2LPv36_23610101_23701231_1Y_grid_U.nc   # exp1 grid U input file
-FILE1_V=OR2LPv36_23610101_23701231_1Y_grid_V.nc   # exp1 grid V input file
-FILE1_I=OR2LPv36_23610101_23701231_1M_icemod.nc   # exp1 ice    input file
+#
+FILE1_T=p4H25a50_20410101_20501231_1Y_grid_T.nc   # exp1 grid T input file
+FILE1_U=p4H25a50_20410101_20501231_1Y_grid_U.nc   # exp1 grid U input file
+FILE1_V=p4H25a50_20410101_20501231_1Y_grid_V.nc   # exp1 grid V input file
+FILE1_I=p4H25a50_20410101_20501231_1M_icemod.nc   # exp1 ice    input file
 VAR1_T=thetao
 VAR1_S=so        
-VAR1_QNET=tohfls
-VAR1_ERP=sowafldp      
+VAR1_QNET=qt
+VAR1_ERP=wfcorr
 VAR1_EMP=wfo
 VAR1_MLD=mldr10_1
 VAR1_U=uocetr_eff
 VAR1_V=vocetr_eff
-VAR1_Ithick=iicethic
-VAR1_Ifrac=soicecov
-VAR1_Isnow=isnowthi
-#VAR1_Isal=sisali
-#VAR1_Iage=siages
-VAR1_IvelU=iicevelu
-VAR1_IvelV=iicevelv
-#VAR1_Ivelo=sivelo
+VAR1_Ithick=sithic
+VAR1_Ifrac=siconc
+VAR1_Isnow=snvolu
+VAR1_Isal=sisali
+VAR1_Iage=siages
+VAR1_IvelU=sivelu
+VAR1_IvelV=sivelv
+VAR1_Ivelo=sivelo
 #
 #===================== EXP2 =====================
 #
-FILE2_T=OR2LPv36_23610101_23701231_1Y_grid_T.nc   # exp1 grid T input file
-FILE2_U=OR2LPv36_23610101_23701231_1Y_grid_U.nc   # exp1 grid U input file
-FILE2_V=OR2LPv36_23610101_23701231_1Y_grid_V.nc   # exp1 grid V input file
-FILE2_I=OR2LPv36_23610101_23701231_1M_icemod.nc   # exp1 ice    input file
+FILE2_T=testht_20410101_20501231_1Y_grid_T.nc   # exp1 grid T input file
+FILE2_U=testht_20410101_20501231_1Y_grid_U.nc   # exp1 grid U input file
+FILE2_V=testht_20410101_20501231_1Y_grid_V.nc   # exp1 grid V input file
+FILE2_I=testht_20410101_20501231_1M_icemod.nc   # exp1 ice    input file
 VAR2_T=thetao
 VAR2_S=so
-VAR2_QNET=tohfls
-VAR2_ERP=sowafldp
+VAR2_QNET=qt
+VAR2_ERP=wfcorr
 VAR2_EMP=wfo
 VAR2_MLD=mldr10_1
 VAR2_U=uocetr_eff
 VAR2_V=vocetr_eff
-VAR2_Ithick=iicethic
-VAR2_Ifrac=soicecov
-VAR2_Isnow=isnowthi
-#VAR2_Isal=sisali
-#VAR2_Iage=siages
-VAR2_IvelU=iicevelu
-VAR2_IvelV=iicevelv
-#VAR2_Ivelo=sivelo
+VAR2_Ithick=sithic
+VAR2_Ifrac=siconc
+VAR2_Isnow=snvolu
+VAR2_Isal=sisali
+VAR2_Iage=siages
+VAR2_IvelU=sivelu
+VAR2_IvelV=sivelv
+VAR2_Ivelo=sivelo
 #
 ######################### Export Variables ###############################
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh.old_names
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh.old_names	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh.old_names	(revision 5075)
@@ -74,5 +74,5 @@
 VAR1_IvelU=iicevelu
 VAR1_IvelV=iicevelv
-VAR1_Ivelo=iicevelo
+#VAR1_Ivelo=iicevelo
 #
 #===================== EXP2 =====================
@@ -99,5 +99,5 @@
 VAR2_IvelU=iicevelu
 VAR2_IvelV=iicevelv
-VAR2_Ivelo=iicevelo
+#VAR2_Ivelo=iicevelo
 #
 ######################### Export Variables ###############################
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh.pstar4-testht
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh.pstar4-testht	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_plot_vardef.sh.pstar4-testht	(revision 5075)
@@ -0,0 +1,129 @@
+#!/bin/sh 
+#
+# AUTHOR - date
+# ===========
+# Sebastien Masson - 04/2011 - LOCEAN
+#
+# DESCRIPTION
+# ===========
+# define all varibles needed by std_plot.sh and std_plot.pro
+#
+# EXAMPLES
+# ========
+# $ . ./std_plot_vardef.sh
+#
+#
+#===================== User PATHS =====================
+#
+#idl_command=/Applications/itt/idl64/bin/idl
+idl_command=/Applications/itt/idl71/bin/idl
+#idl_command=/usr/local_linux/idl/idl_6.4/idl64/bin/idl
+#idl_command=idl71
+#
+PS_DIR=$( pwd )/pstar4-testht_ps_plot
+PDF_DIR=$( pwd )/pstar4-testht_pdf_plot
+HTML_DIR=$( pwd )/html_plot
+SAXO_DIR=/Users/sflod/SAXO_DIR
+#
+DIR_DATA=/Users/sflod/idl_PLOTS/DATA_STORE/RUN_CLIMATO/lim3_ada     # path of data in NetCDF format
+DIR_CLIMATO=/Users/sflod/idl_PLOTS/CLIMATOLOGIES    # path of climatological data
+DIR_MASK=/Users/sflod/idl_PLOTS/MASK  # path of mask files (ex: subbasins)
+#
+#===================== Model GRID =====================
+#
+FILE_MESH_MASK=/Users/sflod/idl_PLOTS/MASK/ORL2PISV35_mesh_mask.nc # meshmask
+FILE_MASK_SUBDOMAIN=subbasins_orca21_nored.nc              # sub-bassin masks
+#
+#===================== DATA =====================
+#
+VAR_TEMP_3D=votemper     ;   FILE_TEMP_3D=potT_annual_mean.nc                         # PHC3
+VAR_SAL_3D=vosaline      ;   FILE_SAL_3D=Salt_1y_corr_PHC3WOA09.nc                    # PHC3
+VAR_SST=sst              ;   FILE_SST=NewREY_ORCA2_1991_2000_1y.nc                   # Reynolds
+VAR_FLUX=qnet            ;   FILE_FLUX=OAFlux_1my_01_12_1984_2004_orca2_qnet.nc      # flux
+VAR_MLD=mld              ;   FILE_MLD=mld_DR003_c1m_ORCA2_1y.nc                      # Mixed layer depth
+VAR_ICE_EXT_NH=extt_NH   ;   FILE_ICE=sea_ice_index_2000.nc                               # Ice Extent North Emisphere
+VAR_ICE_EXT_SH=extt_SH   ;   FILE_ICE=sea_ice_index_2000.nc                               # Ice Extent South Emisphere
+VAR_ICE_area_NH=area_NH  ;   FILE_ICE=sea_ice_index_2000.nc                               # Ice Area North Emisphere
+VAR_ICE_area_SH=area_SH  ;   FILE_ICE=sea_ice_index_2000.nc                               # Ice Area South Emisphere
+VAR_SNOW_NH=SnowDepth    ;   FILE_SNOW_ARC=Warren99_1954_1991_arctic_snowdepth.nc    # Snow arctic 
+VAR_SNOW_SH=sno_dept_mm  ;   FILE_SNOW_ANT=SMMR_SSMI_antarc_sno_dep_mm1979_2004.nc   # Snow antartic
+#
+# Geothermal heating -> define FILE_GEOHEAT to 'NO' if there is not such forcing
+#                    -> define VAR_GEOHEAT to a constant if geothermal heating is constant over the domain
+VAR_GEOHEAT=heatflow   ;   FILE_GEOHEAT=geothermal_heating.nc 
+#
+#===================== EXP1 =====================
+#
+FILE1_T=pstar4_20410101_20501231_1Y_grid_T.nc   # exp1 grid T input file
+FILE1_U=pstar4_20410101_20501231_1Y_grid_U.nc   # exp1 grid U input file
+FILE1_V=pstar4_20410101_20501231_1Y_grid_V.nc   # exp1 grid V input file
+FILE1_I=pstar4_20410101_20501231_1M_icemod.nc   # exp1 ice    input file
+VAR1_T=thetao
+VAR1_S=so        
+VAR1_QNET=qt
+VAR1_ERP=wfcorr
+VAR1_EMP=wfo
+VAR1_MLD=mldr10_1
+VAR1_U=uocetr_eff
+VAR1_V=vocetr_eff
+VAR1_Ithick=sithic
+VAR1_Ifrac=siconc
+VAR1_Isnow=snvolu
+VAR1_Isal=sisali
+VAR1_Iage=siages
+VAR1_IvelU=sivelu
+VAR1_IvelV=sivelv
+VAR1_Ivelo=sivelo
+#
+#===================== EXP2 =====================
+#
+FILE2_T=testht_20410101_20501231_1Y_grid_T.nc   # exp1 grid T input file
+FILE2_U=testht_20410101_20501231_1Y_grid_U.nc   # exp1 grid U input file
+FILE2_V=testht_20410101_20501231_1Y_grid_V.nc   # exp1 grid V input file
+FILE2_I=testht_20410101_20501231_1M_icemod.nc   # exp1 ice    input file
+VAR2_T=thetao
+VAR2_S=so
+VAR2_QNET=qt
+VAR2_ERP=wfcorr
+VAR2_EMP=wfo
+VAR2_MLD=mldr10_1
+VAR2_U=uocetr_eff
+VAR2_V=vocetr_eff
+VAR2_Ithick=sithic
+VAR2_Ifrac=siconc
+VAR2_Isnow=snvolu
+VAR2_Isal=sisali
+VAR2_Iage=siages
+VAR2_IvelU=sivelu
+VAR2_IvelV=sivelv
+VAR2_Ivelo=sivelo
+#
+######################### Export Variables ###############################
+#
+#===================== User PATHS =====================
+export PS_DIR PDF_DIR HTML_DIR SAXO_DIR
+export DIR_DATA DIR_CLIMATO DIR_MASK
+#===================== Model GRID =====================
+export FILE_MESH_MASK FILE_MASK_SUBDOMAIN
+#===================== DATA =====================
+export FILE_TEMP_3D   VAR_TEMP_3D
+export FILE_SAL_3D    VAR_SAL_3D
+export FILE_SST       VAR_SST
+export FILE_GEOHEAT   VAR_GEOHEAT
+export FILE_FLUX      VAR_FLUX
+export FILE_MLD       VAR_MLD
+export FILE_ICE       VAR_ICE_EXT_NH  VAR_ICE_EXT_SH VAR_ICE_area_NH VAR_ICE_area_SH
+export FILE_SNOW_ARC  VAR_SNOW_NH
+export FILE_SNOW_ANT  VAR_SNOW_SH
+#===================== EXP1 =====================
+export READ_ONLY_FIRST_RECORD
+export FILE1_T     FILE1_U  FILE1_V   FILE1_I
+export VAR1_T      VAR1_S   VAR1_QNET VAR1_ERP VAR1_EMP VAR1_MLD 
+export VAR1_U      VAR1_V
+export VAR1_Ithick VAR1_Ifrac VAR1_Isnow VAR1_Isal VAR1_Iage VAR1_IvelU VAR1_IvelV VAR1_Ivelo
+#===================== EXP2 =====================
+export FILE2_T     FILE2_U    FILE2_V   FILE2_I
+export VAR2_T      VAR2_S     VAR2_QNET VAR2_ERP VAR2_EMP VAR2_MLD 
+export VAR2_U      VAR2_V
+export VAR2_Ithick VAR2_Ifrac VAR2_Isnow VAR2_Isal VAR2_Iage VAR2_IvelU VAR2_IvelV VAR2_Ivelo
+#
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE.pro
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE.pro	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE.pro	(revision 5075)
@@ -88,24 +88,25 @@
   ICE_S_15 = {arr:ICE_S_15 * 1.e-12, unit : '10^12 m^2'}
   ;
-  title = 'Northern Hemisphere'+'!C'+prefix+' (BLACK) '+d1_d2+'!C'+'OBSERVATION (light blue) '+'!C'+' Global Annual Mean Ice Area (CONTINUOUS) '+'!C'+ 'and Extend minus 15% (DASHED)'
+  ;;title = 'Northern Hemisphere'+'!C'+prefix+' (BLACK) '+d1_d2+'!C'+'OBSERVATION (light blue) '+'!C'+' Global Annual Mean Ice Area (CONTINUOUS) '+'!C'+ 'and Extend minus 15% (DASHED)'
+  title = 'Northern Hemisphere'+'!C'+prefix+' (BLACK) '+d1_d2+'!C'+'OBSERVATION (light blue) '+'!C'+' Global Annual Mean Ice Area (DASHED) '+'!C'+ 'and Extend minus 15% (CONTINUOUS)'
   jpt=12
   time=julday(1,15,1900)+30*lindgen(12)
-  pltt, ICE_N, 't', MIN = 4., MAX = 16., /REMPLI, /PORTRAIT, XGRIDSTYLE = 1, DATE_FORMAT = '%M' $
+  pltt, ICE_N, 't', MIN = 4., MAX = 16., /REMPLI, /PORTRAIT, LINESTYLE=2, XGRIDSTYLE = 1, DATE_FORMAT = '%M' $
        , COLOR = 000 , small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt, ICE_N_15, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $       ;;; dashed lines is LINESTYLE=2  $
+  pltt, ICE_N_15, 't', /REMPLI, /PORTRAIT $       ;;; dashed lines is LINESTYLE=2  $
         , /ov1d, COLOR = 000, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex 
-  pltt, vICE_area_NH, 't',  /REMPLI, /PORTRAIT  $ 
+  pltt, vICE_area_NH, 't',  /REMPLI, /PORTRAIT, LINESTYLE=2  $ 
         , /ov1d, COLOR = 100, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt, vICE_ext_NH, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $   ;;; dashed lines is LINESTYLE=2  $
+  pltt, vICE_ext_NH, 't', /REMPLI, /PORTRAIT $   ;;; dashed lines is LINESTYLE=2  $
         , /ov1d, COLOR = 100, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
 ;
-  title = 'Southern Hemisphere'+'!C'+prefix+' (BLACK) '+d1_d2+'!C'+'OBSERVATION (light blue) '+'!C'+' Global Annual Mean Ice Area (CONTINUOUS) '+'!C'+ 'and Extend minus 15% (DASHED)'
-  pltt, ICE_S, 't', MIN = 0., MAX = 20., /REMPLI, /NOERASE , XGRIDSTYLE = 1 , DATE_FORMAT = '%M' $
+  title = 'Southern Hemisphere'+'!C'+prefix+' (BLACK) '+d1_d2+'!C'+'OBSERVATION (light blue) '+'!C'+' Global Annual Mean Ice Area (DASHED) '+'!C'+ 'and Extend minus 15% (CONTINUOUS)'
+  pltt, ICE_S, 't', MIN = 0., MAX = 20., /REMPLI, LINESTYLE=2, /NOERASE , XGRIDSTYLE = 1 , DATE_FORMAT = '%M' $
         ,COLOR = 000, small = [1, 2, 2], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt, ICE_S_15, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $ 
+  pltt, ICE_S_15, 't', /REMPLI, /PORTRAIT $ 
         , /ov1d, COLOR = 000, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex 
-  pltt,  vICE_area_SH, 't', /REMPLI, /PORTRAIT  $ 
+  pltt,  vICE_area_SH, 't', /REMPLI, /PORTRAIT, LINESTYLE=2  $ 
          , /ov1d, COLOR = 100, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt,  vICE_ext_SH, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $ 
+  pltt,  vICE_ext_SH, 't', /REMPLI, /PORTRAIT $ 
         , /ov1d, COLOR = 100, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
 ;
@@ -159,33 +160,34 @@
 
 
-  title = 'Northern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'OBSERVATION (light blue) '+'!C'+' Global Annual Mean Ice Area (CONTINUOUS) '+'!C'+ 'and Extend minus 15% (DASHED)'
+  ;;title = 'Northern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'OBSERVATION (light blue) '+'!C'+' Global Annual Mean Ice Area (CONTINUOUS) '+'!C'+ 'and Extend minus 15% (DASHED)'
+  title = 'Northern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'OBSERVATION (light blue) '+'!C'+' Global Annual Mean Ice Area (DASHED) '+'!C'+ 'and Extend minus 15% (CONTINUOUS)'
   jpt=12
   time=julday(1,15,1900)+30*lindgen(12)
-  pltt, ICE_N, 't', MIN = 4, MAX = 16,  /REMPLI, /PORTRAIT, XGRIDSTYLE = 1, window = 2, DATE_FORMAT = '%M' $
+  pltt, ICE_N, 't', MIN = 4, MAX = 16,  /REMPLI, /PORTRAIT, LINESTYLE=2, XGRIDSTYLE = 1, window = 2, DATE_FORMAT = '%M' $
         , COLOR = 000, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex ; BLACK
-  pltt, ICE_N2, 't', /REMPLI, /PORTRAIT  $
+  pltt, ICE_N2, 't', /REMPLI, /PORTRAIT , LINESTYLE=2 $
         , /ov1d, COLOR = 250, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex  ; RED
-  pltt, ICE_N_15, 't', /REMPLI, /PORTRAIT, LINESTYLE=2  $ ; linee tratteggiate LINESTYLE=2  $
+  pltt, ICE_N_15, 't', /REMPLI, /PORTRAIT $ ; linee tratteggiate LINESTYLE=2  $
         , /ov1d, COLOR = 000, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex 
-  pltt, ICE_N2_15, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $ ; linee tratteggiate LINESTYLE=2  $
+  pltt, ICE_N2_15, 't', /REMPLI, /PORTRAIT $ ; linee tratteggiate LINESTYLE=2  $
         , /ov1d, COLOR = 250, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt, vICE_area_NH, 't', /REMPLI, /PORTRAIT  $ 
+  pltt, vICE_area_NH, 't', /REMPLI, /PORTRAIT, LINESTYLE=2  $ 
         , /ov1d, COLOR = 100, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex  ; light blue
-  pltt, vICE_ext_NH, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $ 
+  pltt, vICE_ext_NH, 't', /REMPLI, /PORTRAIT $ 
         , /ov1d, COLOR = 100, small = [1, 2, 1], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex  ; blu scuro
 ;
-  title ='Southern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'OBSERVATION (light blue) '+'!C'+'Global Annual Mean Ice Area (CONTINUS)'+'!C'+ 'and Extend minus 15% (DASHED)'
+  title ='Southern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'OBSERVATION (light blue) '+'!C'+'Global Annual Mean Ice Area (DASHED)'+'!C'+ 'and Extend minus 15% (CONTINUOUS)'
 ;  title ='Southern Hemisphere'+'!C'
-  pltt, ICE_S, 't', MIN = 0., MAX = 20.,  /REMPLI, /NOERASE, XGRIDSTYLE = 1, DATE_FORMAT = '%M' $
+  pltt, ICE_S, 't', MIN = 0., MAX = 20., /REMPLI, LINESTYLE=2, /NOERASE, XGRIDSTYLE = 1, DATE_FORMAT = '%M' $
          , COLOR = 000, small = [1, 2, 2], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt, ICE_S2, 't', /REMPLI, /NOERASE $
+  pltt, ICE_S2, 't', /REMPLI, /NOERASE, LINESTYLE=2 $
         , /ov1d, COLOR = 250, small = [1, 2, 2], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt, ICE_S_15 , 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $ ; linee tratteggiate LINESTYLE=2  $
+  pltt, ICE_S_15 , 't', /REMPLI, /PORTRAIT $ ; linee tratteggiate LINESTYLE=2  $
         , /ov1d, COLOR = 000, small = [1, 2, 2], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt, ICE_S2_15, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $ ; linee tratteggiate LINESTYLE=2  $
+  pltt, ICE_S2_15, 't', /REMPLI, /PORTRAIT $ ; linee tratteggiate LINESTYLE=2  $
         , /ov1d, COLOR = 250, small = [1, 2, 2], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt,  vICE_area_SH, 't', /REMPLI, /PORTRAIT $ 
+  pltt,  vICE_area_SH, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $ 
           , /ov1d, COLOR = 100, small = [1, 2, 2], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
-  pltt,  vICE_ext_SH, 't', /REMPLI, /PORTRAIT, LINESTYLE=2 $ 
+  pltt,  vICE_ext_SH, 't', /REMPLI, /PORTRAIT $ 
         , /ov1d, COLOR = 100, small = [1, 2, 2], YTITLE = '10^12 m^2 ', TITLE = title, _extra = ex
 ;
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE_FRAM.pro
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE_FRAM.pro	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE_FRAM.pro	(revision 5075)
@@ -5,5 +5,6 @@
 arr2d = arr2d[t1:t2]
 arr2d = reform(arr2d,12,nyear) ; put in 2D array
-arr2d = total(arr2d,2)/nyear ; total over 2th dimension (i.e.years)
+;arr2d = total(arr2d,2)/nyear ; total over 2th dimension (i.e.years)
+arr2d = arr2d[*, nyear-1] ;  select last year
 
 return, arr2d
@@ -34,4 +35,5 @@
 ;
   d1_d2 = '('+strtrim(date1, 1)+' - '+strtrim(date2, 1)+')'
+  d2 = '('+strtrim(date2, 1)+')'
 ;
   iodir = std_iodir_data
@@ -74,5 +76,6 @@
   ;; AREA
   ICE_area_export = reform(ICE_area_export, 12, nyr)
-  ICE_area_export = total(ICE_area_export,2)/nyr
+  ;ICE_area_export = total(ICE_area_export,2)/nyr  ; old version monthly mean average  over all years
+  ICE_area_export = ICE_area_export[*,nyr-1]  ; dim= 12, index 0-11; last year choosen
   ; ICE_area_export = {arr:ICE_area_export * 1.e-12 * 86400 * 365 , unit : '10^6 Km^2/year'}  ; annual mean
   ICE_area_export = {arr:ICE_area_export * 1.e-12 * 86400 * 30 , unit : '10^6 Km^2/month'}    ; monthly mean
@@ -80,10 +83,12 @@
   ;
   ICE_vol_export = reform(ICE_vol_export, 12, nyr)
-  ICE_vol_export = total(ICE_vol_export,2)/nyr
+  ;ICE_vol_export = total(ICE_vol_export,2)/nyr
+  ICE_vol_export = ICE_vol_export[*,nyr-1]
   ; ICE_vol_export = {arr:ICE_vol_export * 1.e-9 * 86400 * 365 , unit : '10^3 Km^3/year'}      ; annual mean
   ICE_vol_export = {arr:ICE_vol_export * 1.e-9 * 86400 * 30 , unit : '10^3 Km^3/month'}      ; monthly mean
 
   ;
-  title = 'Fram Strait Areal Export'+'!C'+prefix+' '+d1_d2
+  ;title = 'Fram Strait Areal Export: LAST YEAR'+'!C'+prefix+' '+d1_d2
+  title = 'Fram Strait Areal Export: LAST YEAR'+'!C'+prefix+' '+d2
   jpt=12
   time=julday(1,15,1900)+30*lindgen(12)
@@ -99,5 +104,6 @@
   xyouts, julday(7,15,1900), 0.41, 'Data from Kwok et al.(2004), 1979-2002 ', ALIGN = 0, CHARTHICK = 2, CHARSIZE=0.8, COLOR=2
   ;
-  title = 'Fram Strait Volume Export'+'!C'+prefix+' '+d1_d2
+  ;title = 'Fram Strait Volume Export LAST YEAR'+'!C'+prefix+' '+d1_d2
+  title = 'Fram Strait Volume Export LAST YEAR'+'!C'+prefix+' '+d2
   pltt, ICE_vol_export, 't',  /REMPLI, MIN = 60., MAX = 500. , /NOERASE, XGRIDSTYLE = 1 $
        , small = [1, 2, 2], YTITLE = '10^3 Km^3/month', TITLE = title, DATE_FORMAT = '%M', _extra = ex
@@ -118,4 +124,5 @@
 
     d1_d2_2 = '('+strtrim(date1_2, 1)+' - '+strtrim(date2_2, 1)+')'
+    d2_2 = '('+strtrim(date2_2, 1)+')'
     tsave = time
     domdef, indx1, indx2, indy1, indy2, /xindex, /yindex,/memeindices
@@ -140,10 +147,12 @@
     ;; AREA
     ICE_area_export_2 = reform(ICE_area_export_2, 12, nyr)
-    ICE_area_export_2 = total(ICE_area_export_2,2)/nyr
+    ;ICE_area_export_2 = total(ICE_area_export_2,2)/nyr
+    ICE_area_export_2 = ICE_area_export_2[*,nyr-1]
     ; ICE_area_export_2 = {arr:ICE_area_export_2 * 1.e-12 * 86400 * 365 , unit : '10^6 Km^2/year'}   ; annual mean
     ICE_area_export_2 = {arr:ICE_area_export_2 * 1.e-12 * 86400 * 30 , unit : '10^6 Km^2/month'}     ; monthly mean
     ;
     ICE_vol_export_2 = reform(ICE_vol_export_2, 12, nyr)
-    ICE_vol_export_2 = total(ICE_vol_export_2,2)/nyr
+    ;ICE_vol_export_2 = total(ICE_vol_export_2,2)/nyr
+    ICE_vol_export_2 = ICE_vol_export_2[*,nyr-1]
     ; ICE_vol_export_2 = {arr:ICE_vol_export_2 * 1.e-12 * 86400 * 365 , unit : '10^3 Km^3/year'}     ; annual mean
     ICE_vol_export_2 = {arr:ICE_vol_export_2 * 1.e-9 * 86400 * 30 , unit : '10^3 Km^3/month'}       ; monthly mean
@@ -152,5 +161,6 @@
     if KEYWORD_SET(postscript) then openps, filename+'_2.ps', portrait = 1
 
-    title = 'Fram Strait Areal Export'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2
+    ;title = 'Fram Strait Areal Export'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2
+    title = 'Fram Strait Areal Export LAST YEAR'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d2_2
     jpt=12
     time=julday(1,15,1900)+30*lindgen(12)
@@ -170,5 +180,6 @@
     xyouts, julday(7,15,1900), 0.41, 'Data from Kwok et al.(2004), 1979-2002 ', ALIGN = 0, CHARTHICK = 2, CHARSIZE=0.8, COLOR=2
     ;
-    title = 'Fram Strait Volume Export'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2
+    ;title = 'Fram Strait Volume Export'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2
+    title = 'Fram Strait Volume Export LAST YEAR'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d2_2
     pltt, ICE_vol_export, 't', /REMPLI,  MIN = 60., MAX = 500., /NOERASE, XGRIDSTYLE = 1 $
         , small = [1, 2, 2], YTITLE = '10^3 Km^3/month', TITLE = title, DATE_FORMAT = '%M', _extra = ex
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE_Vol.pro
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE_Vol.pro	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_ICE_Vol.pro	(revision 5075)
@@ -70,5 +70,5 @@
 ;
   title ='Southern Hemisphere' +'!C'+prefix+' '+d1_d2+' - '+'!C'+'Global Annual Mean Ice Volume (BLACK)'
-  pltt, ICE_vol_S, 't', MIN = 0., MAX = 11000., /REMPLI, /NOERASE, XGRIDSTYLE = 1 , DATE_FORMAT = '%M' $
+  pltt, ICE_vol_S, 't', MIN = 0., MAX = 12000., /REMPLI, /NOERASE, XGRIDSTYLE = 1 , DATE_FORMAT = '%M' $
         , small = [1, 2, 2], YTITLE = '10^9 Km^3 ', TITLE = title, _extra = ex
 ;
@@ -119,5 +119,5 @@
     ;
     title = 'Southern Hemisphere'+'!C'+prefix+' (BLACK) - '+prefix2+' (RED) '+d1_d2_2+'!C'+'Global Annual Mean Ice Volume'
-    pltt, ICE_vol_S, 't', MIN = 0., MAX = 11000., /REMPLI, /NOERASE, XGRIDSTYLE = 1, DATE_FORMAT = '%M' $
+    pltt, ICE_vol_S, 't', MIN = 0., MAX = 12000., /REMPLI, /NOERASE, XGRIDSTYLE = 1, DATE_FORMAT = '%M' $
           , small = [1, 2, 2], YTITLE = '10^9 Km^3 ', TITLE = title, _extra = ex   
     pltt, ICE_vol_S2, 't',  /REMPLI, /NOERASE $
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_all.pro
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_all.pro	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_all.pro	(revision 5075)
@@ -60,6 +60,6 @@
   IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_SSH, masknp, POSTSCRIPT = postscript, _extra = ex
 ;
-  cnt = cnt+1   &   blabla = 'Global Mean Q net'
-  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_Q, masknp, POSTSCRIPT = postscript, _extra = ex
+;;;;  cnt = cnt+1   &   blabla = 'Global Mean Q net'
+;;;;  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_Q, masknp, POSTSCRIPT = postscript, _extra = ex
 ;
   cnt = cnt+1   &   blabla = 'Global Mean EMP'
@@ -77,8 +77,8 @@
   cnt = cnt+1   &   blabla = 'Sea-Ice Volume'
   IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_ICE_Vol, masknp, POSTSCRIPT = postscript, _extra = ex
-;
-  cnt = cnt+1   &   blabla = 'ICE Velocity '
-  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_ICE_Vel, masknp, POSTSCRIPT = postscript, _extra = ex
-;
+;SF; and probably useless
+;SF  cnt = cnt+1   &   blabla = 'ICE Velocity '
+;SF  IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_ICE_Vel, masknp, POSTSCRIPT = postscript, _extra = ex
+;SF;
   cnt = cnt+1   &   blabla = 'Sea-Ice Volume Export at Fram Strait'
   IF doplot EQ cnt OR doplot EQ 0 THEN std_ts_ICE_FRAM, masknp, POSTSCRIPT = postscript, _extra = ex
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_vardef.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_vardef.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/IDL_scripts/std_ts_vardef.sh	(revision 5075)
@@ -18,10 +18,10 @@
 idl_command=/Applications/itt/idl64/bin/idl
 #
-PS_DIR=$( pwd )/ts_heatbug_ps
-PDF_DIR=$( pwd )/ts_heatbug_pdf
+PS_DIR=$( pwd )/ts_p4H25a50-testht_ps
+PDF_DIR=$( pwd )/ts_p4H25a50-testht_pdf
 HTML_DIR=$( pwd )/html
 SAXO_DIR=/Users/sflod/SAXO_DIR
 #
-DIR_DATA=/Users/sflod/idl_PLOTS/DATA_STORE/RUN_CLIMATO/lim3_ada      # path of data in NetCDF format
+DIR_DATA=/Users/sflod/idl_PLOTS/DATA_STORE/RUN_CLIMATO/lim3_ada     # path of data in NetCDF format
 DIR_CLIMATO=/Users/sflod/idl_PLOTS/CLIMATOLOGIES    # path of climatological data
 DIR_MASK=/Users/sflod/idl_PLOTS/MASK  # path of mask files (ex: subbasins)
@@ -52,39 +52,35 @@
 READ_ONLY_FIRST_RECORD=0   # if 0 then read all records in files else read only the first reacord in each file
 #
-#DATE1=20010101   ;   DATE2=25001231
-DATE1=20310101   ;   DATE2=20401231
-#DATE1=00010101  		;   DATE2=00101231
+DATE1=20010101  		  ;   DATE2=20501231
 #
-VAR1_T=thetao        ;   V1T_PREF=heatbug       ;   V1T_SUFF=_1Y_grid_T.nc
-VAR1_S=so            ;   V1S_PREF=heatbug      ;   V1S_SUFF=_1Y_grid_T.nc
-VAR1_SSH=zos         ;   V1SSH_PREF=heatbug    ;   V1SSH_SUFF=_1Y_grid_T.nc
-VAR1_Q=tohfls        ;   V1Q_PREF=heatbug      ;   V1Q_SUFF=_1Y_grid_T.nc
-VAR1_EMP=wfo         ;   V1EMP_PREF=heatbug    ;   V1EMP_SUFF=_1Y_grid_T.nc
-VAR1_U=uocetr_eff    ;   V1U_PREF=heatbug      ;   V1U_SUFF=_1Y_grid_U.nc
-VAR1_V=vocetr_eff    ;   V1V_PREF=heatbug      ;   V1V_SUFF=_1Y_grid_V.nc
-VAR1_ICE=siconc      ;   V1ICE_PREF=heatbug    ;   V1ICE_SUFF=_1M_icemod.nc
-VAR1_Ithick=sithic   ;   V1It_PREF=heatbug     ;   V1It_SUFF=_1M_icemod.nc
-VAR1_SNOW=sndept     ;   V1SNOW_PREF=heatbug   ;   V1SNOW_SUFF=_1M_icemod.nc
-VAR1_IvelV=sivelv    ;   V1IvV_PREF=heatbug    ;   V1IvV_SUFF=_1M_icemod.nc
-VAR1_Ivel=sivelo     ;   V1Iv_PREF=heatbug     ;   V1Iv_SUFF=_1M_icemod.nc
+VAR1_T=thetao          ;   V1T_PREF=p4H25a50      ;   V1T_SUFF=_1Y_grid_T.nc
+VAR1_S=so              ;   V1S_PREF=p4H25a50      ;   V1S_SUFF=_1Y_grid_T.nc
+VAR1_SSH=zos         ;   V1SSH_PREF=p4H25a50    ;   V1SSH_SUFF=_1Y_grid_T.nc
+##VAR1_Q=qt              ;   V1Q_PREF=p4H25a50      ;   V1Q_SUFF=_1Y_grid_T.nc
+VAR1_EMP=wfo         ;   V1EMP_PREF=p4H25a50    ;   V1EMP_SUFF=_1Y_grid_T.nc
+VAR1_U=uocetr_eff      ;   V1U_PREF=p4H25a50      ;   V1U_SUFF=_1Y_grid_U.nc
+VAR1_V=vocetr_eff      ;   V1V_PREF=p4H25a50      ;   V1V_SUFF=_1Y_grid_V.nc
+VAR1_ICE=siconc      ;   V1ICE_PREF=p4H25a50    ;   V1ICE_SUFF=_1M_icemod.nc
+VAR1_Ithick=sithic    ;   V1It_PREF=p4H25a50     ;   V1It_SUFF=_1M_icemod.nc
+VAR1_SNOW=snthic    ;   V1SNOW_PREF=p4H25a50   ;   V1SNOW_SUFF=_1M_icemod.nc
+VAR1_IvelV=sivelv    ;   V1IvV_PREF=p4H25a50    ;   V1IvV_SUFF=_1M_icemod.nc 
+VAR1_Ivel=sivelo      ;   V1Iv_PREF=p4H25a50     ;   V1Iv_SUFF=_1M_icemod.nc
 #
 #===================== EXP2 =====================
 #
-#DATE1_2=20010101   ;   DATE2_2=20101231
-DATE1_2=20310101   ;   DATE2_2=20401231
-#DATE1_2=20010101   ;   DATE2_2=25001231
+DATE1_2=20010101   	  ;   DATE2_2=20501231
 #
-VAR2_T=thetao      ;   V2T_PREF=heatbug      ;   V2T_SUFF=_1Y_grid_T.nc
-VAR2_S=so          ;   V2S_PREF=heatbug      ;   V2S_SUFF=_1Y_grid_T.nc
-VAR2_SSH=zos       ;   V2SSH_PREF=heatbug    ;   V2SSH_SUFF=_1Y_grid_T.nc
-VAR2_Q=tohfls      ;   V2Q_PREF=heatbug      ;   V2Q_SUFF=_1Y_grid_T.nc
-VAR2_EMP=wfo       ;   V2EMP_PREF=heatbug    ;   V2EMP_SUFF=_1Y_grid_T.nc
-VAR2_U=uocetr_eff  ;   V2U_PREF=heatbug      ;   V2U_SUFF=_1Y_grid_U.nc
-VAR2_V=vocetr_eff  ;   V2V_PREF=heatbug      ;   V2V_SUFF=_1Y_grid_V.nc
-VAR2_ICE=siconc    ;   V2ICE_PREF=heatbug    ;   V2ICE_SUFF=_1M_icemod.nc
-VAR2_Ithick=sithic ;   V2It_PREF=heatbug     ;   V2It_SUFF=_1M_icemod.nc
-VAR2_SNOW=sndept   ;   V2SNOW_PREF=heatbug   ;   V2SNOW_SUFF=_1M_icemod.nc
-VAR2_IvelV=sivelv  ;   V2IvV_PREF=heatbug    ;   V2IvV_SUFF=_1M_icemod.nc
-VAR2_Ivel=sivelo   ;   V2Iv_PREF=heatbug     ;   V2Iv_SUFF=_1M_icemod.nc
+VAR2_T=thetao     	  ;   V2T_PREF=testht     ;   V2T_SUFF=_1Y_grid_T.nc
+VAR2_S=so        	  ;   V2S_PREF=testht     ;   V2S_SUFF=_1Y_grid_T.nc
+VAR2_SSH=zos      	;   V2SSH_PREF=testht   ;   V2SSH_SUFF=_1Y_grid_T.nc
+##VAR2_Q=qt       	  ;   V2Q_PREF=testht     ;   V2Q_SUFF=_1Y_grid_T.nc
+VAR2_EMP=wfo            ;   V2EMP_PREF=testht   ;   V2EMP_SUFF=_1Y_grid_T.nc
+VAR2_U=uocetr_eff   	  ;   V2U_PREF=testht     ;   V2U_SUFF=_1Y_grid_U.nc
+VAR2_V=vocetr_eff   	  ;   V2V_PREF=testht     ;   V2V_SUFF=_1Y_grid_V.nc
+VAR2_ICE=siconc         ;   V2ICE_PREF=testht   ;   V2ICE_SUFF=_1M_icemod.nc
+VAR2_Ithick=sithic       ;   V2It_PREF=testht    ;   V2It_SUFF=_1M_icemod.nc
+VAR2_SNOW=snthic       ;   V2SNOW_PREF=testht  ;   V2SNOW_SUFF=_1M_icemod.nc
+VAR2_IvelV=sivelv       ;   V2IvV_PREF=testht   ;   V2IvV_SUFF=_1M_icemod.nc 
+VAR2_Ivel=sivelo        ;   V2IvV_PREF=testht   ;   V2IvV_SUFF=_1M_icemod.nc 
 #
 ######################### Export Variables ###############################
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/cpp_ORCA2_LIM.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/cpp_ORCA2_LIM.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM/cpp_ORCA2_LIM.fcm	(revision 5075)
@@ -1,1 +1,1 @@
- bld::tool::fppkeys key_trabbl key_lim2 key_dynspg_flt key_diaeiv key_ldfslp key_traldf_c2d key_traldf_eiv key_dynldf_c3d key_zdftke key_zdfddm key_zdftmx key_iomput key_mpp_mpi
+bld::tool::fppkeys key_trabbl key_lim2 key_dynspg_flt key_diaeiv key_ldfslp key_traldf_c2d key_traldf_eiv key_dynldf_c3d key_zdftke key_zdfddm key_zdftmx key_iomput key_mpp_mpi key_diaobs key_asminc
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/1_namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/1_namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/1_namelist_cfg	(revision 5075)
@@ -55,4 +55,13 @@
 /
 !-----------------------------------------------------------------------
+&namsplit      !   time splitting parameters                            ("key_dynspg_ts")
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namcrs        !   Grid coarsening for dynamics output and/or
+               !   passive tracer coarsened online simulations
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
 &namtsd    !   data : Temperature  & Salinity
 !-----------------------------------------------------------------------
@@ -72,17 +81,27 @@
 /
 !-----------------------------------------------------------------------
-&namsbc_core   !   namsbc_core  CORE bulk formulea
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation !
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  !
-   sn_wndi = 'u_10.15JUNE2009_orca2'       ,  6  , 'U_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_bicub.nc'       , ''
-   sn_wndj = 'v_10.15JUNE2009_orca2'       ,  6  , 'V_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_bicub.nc'       , ''
-   sn_qsr  = 'ncar_rad.15JUNE2009_orca2'   , 24  , 'SWDN_MOD',   .false.    , .true. , 'yearly'  , 'weights_bilin.nc'       , ''
-   sn_qlw  = 'ncar_rad.15JUNE2009_orca2'   , 24  , 'LWDN_MOD',   .false.    , .true. , 'yearly'  , 'weights_bilin.nc'       , ''
-   sn_tair = 't_10.15JUNE2009_orca2'       ,  6  , 'T_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_bilin.nc'       , ''
-   sn_humi = 'q_10.15JUNE2009_orca2'       ,  6  , 'Q_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_bilin.nc'       , ''
-   sn_prec = 'ncar_precip.15JUNE2009_orca2', -1  , 'PRC_MOD1',   .false.    , .true. , 'yearly'  , 'weights_bilin.nc'       , ''
-   sn_snow = 'ncar_precip.15JUNE2009_orca2', -1  , 'SNOW'    ,   .false.    , .true. , 'yearly'  , 'weights_bilin.nc'       , ''
-   sn_tdif = 'taudif_core'                 , 24  , 'taudif'  ,   .false.    , .true. , 'yearly'  , 'weights_bilin.nc'       , ''
+&namsbc_core   !   namsbc_core  CORE bulk formulae
+!-----------------------------------------------------------------------
+!              !  file name                    ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights                               ! rotation ! land/sea mask !
+!              !                               !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename                              ! pairing  ! filename      !
+   sn_wndi     = 'u_10.15JUNE2009_fill'        ,         6         , 'U_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bicubic.nc'      , 'Uwnd'   , ''
+   sn_wndj     = 'v_10.15JUNE2009_fill'        ,         6         , 'V_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bicubic.nc'      , 'Vwnd'   , ''
+   sn_qsr      = 'ncar_rad.15JUNE2009_fill'    ,        24         , 'SWDN_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_qlw      = 'ncar_rad.15JUNE2009_fill'    ,        24         , 'LWDN_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_tair     = 't_10.15JUNE2009_fill'        ,         6         , 'T_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_humi     = 'q_10.15JUNE2009_fill'        ,         6         , 'Q_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_prec     = 'ncar_precip.15JUNE2009_fill' ,        -1         , 'PRC_MOD1',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_snow     = 'ncar_precip.15JUNE2009_fill' ,        -1         , 'SNOW'    ,   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   sn_tdif     = 'taudif_core'                 ,        24         , 'taudif'  ,   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
+   cn_dir      = './'      !  root directory for the location of the bulk files
+   ln_2m       = .false.   !  air temperature and humidity referenced at 2m (T) instead 10m (F)
+   ln_taudif   = .false.   !  HF tau contribution: use "mean of stress module - module of the mean stress" data
+   ln_bulk2z   = .false.   !  Air temperature/humidity and wind vectors are referenced at heights rn_zqt and rn_zu
+   rn_zqt      = 3.        !  Air temperature and humidity reference height (m) (ln_bulk2z)
+   rn_zu       = 4.        !  Wind vector reference height (m)                  (ln_bulk2z)
+   rn_pfac     = 1.        !  multiplicative factor for precipitation (total & snow)
+   rn_efac     = 1.        !  multiplicative factor for evaporation (0. or 1.)
+   rn_vfac     = 0.        !  multiplicative factor for ocean/ice velocity 
+                           !  in the calculation of the wind stress (0.=absolute winds or 1.=relative winds)
 /
 !-----------------------------------------------------------------------
@@ -120,4 +139,9 @@
 &nameos        !   ocean physical parameters
 !-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namtra_dmp    !   tracer: T & S newtonian damping
+!-----------------------------------------------------------------------
+   ln_tradmp   =  .false.   !  add a damping termn (T) or not (F)
 /
 !-----------------------------------------------------------------------
@@ -197,2 +221,10 @@
 !-----------------------------------------------------------------------
 /
+!-----------------------------------------------------------------------
+&namobs       !  observation usage                                      ('key_diaobs')
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&nam_asminc   !   assimilation increments                               ('key_asminc')
+!-----------------------------------------------------------------------
+/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef.xml	(revision 5075)
@@ -47,25 +47,30 @@
 	  <field field_ref="mldkz5"       />
 	  <field field_ref="mldr10_1"     />
+      <field field_ref="heatc"        name="heatc"    long_name="Heat content vertically integrated"            />
+      <field field_ref="saltc"        name="saltc"    long_name="Salt content vertically integrated"            />
 	</file>
 
 	<file id="file2" name_suffix="_SBC" description="surface fluxes variables" > <!-- time step automaticaly defined based on nn_fsbc -->
 	  <field field_ref="empmr"        name="wfo"      long_name="water_flux_into_sea_water"                     />
-	  <field field_ref="qsr"          name="rsntds"   long_name="surface_net_downward_shortwave_flux"           />
-	  <field field_ref="qt"           name="tohfls"   long_name="surface_net_downward_total_heat_flux"          />
-	  <field field_ref="saltflx"      name="sosflxdo"  />
+	  <field field_ref="qsr_oce"      name="qsr_oce"  long_name="downward shortwave flux at ocean surface"           />
+	  <field field_ref="qns_oce"      name="qns_oce"  long_name="downward non solar flux at ocean surface"           />
+	  <field field_ref="qt_oce"       name="qt_oce"   long_name="downward total flux at ocean surface"           />
+	  <field field_ref="qsr_ice"      name="qsr_ice"  long_name="downward shortwave flux at ice surface"           />
+	  <field field_ref="qns_ice"      name="qns_ice"  long_name="downward non solar flux at ice surface"           />
+	  <field field_ref="qtr_ice"      name="qtr_ice"  long_name="shortwave flux transmitted thru the ice"           />
+	  <field field_ref="qt_ice"       name="qt_ice"   long_name="downward total flux at ice surface"           />
+	  <field field_ref="saltflx"      name="sfx"  />
 	  <field field_ref="taum"         name="taum" />
-	  <field field_ref="wspd"         name="sowindsp"  />
-          <field field_ref="precip"       name="soprecip" />
+	  <field field_ref="wspd"         name="windsp"  />
+      <field field_ref="precip"       name="precip" />
 	  <!-- ice and snow -->
 	  <field field_ref="snowpre"      />
-          <field field_ref="qsr_io"           name="iicesflx" />
-          <field field_ref="qns_io"           name="iicenflx" />
-          <field field_ref="utau_ice"         name="iicestru" />
-          <field field_ref="vtau_ice"         name="iicestrv" />
+      <field field_ref="utau_ice"         name="utau_ice" />
+      <field field_ref="vtau_ice"         name="vtau_ice" />
 
 	</file>
 
 	<file id="file3" name_suffix="_grid_U" description="ocean U grid variables" >
-	  <field field_ref="suoce"        name="uos"     long_name="sea_surface_x_velocity"    />
+	  <field field_ref="ssu"          name="uos"     long_name="sea_surface_x_velocity"    />
 	  <field field_ref="uoce"         name="uo"      long_name="sea_water_x_velocity"      />
 	  <field field_ref="utau"         name="tauuo"   long_name="surface_downward_x_stress" />
@@ -73,8 +78,9 @@
 	  <field field_ref="u_masstr"     name="vozomatr"  />
 	  <field field_ref="u_heattr"     name="sozohetr"  />
+      <field field_ref="u_salttr"     name="sozosatr"  />
 	</file>
 	
 	<file id="file4" name_suffix="_grid_V" description="ocean V grid variables" >
-	  <field field_ref="svoce"        name="vos"     long_name="sea_surface_y_velocity"    />
+	  <field field_ref="ssv"          name="vos"     long_name="sea_surface_y_velocity"    />
 	  <field field_ref="voce"         name="vo"      long_name="sea_water_y_velocity"      />
 	  <field field_ref="vtau"         name="tauvo"   long_name="surface_downward_y_stress" />
@@ -82,4 +88,5 @@
 	  <field field_ref="v_masstr"     name="vomematr"  />
 	  <field field_ref="v_heattr"     name="somehetr"  />
+      <field field_ref="v_salttr"     name="somesatr"  />
 	</file>
 	
@@ -90,44 +97,90 @@
 	</file>
 
-	<file id="file6" name_suffix="_icemod" description="ice variables" >
-	  <field field_ref="snowthic_cea" name="snd"     long_name="surface_snow_thickness"   />
-	  <field field_ref="icethic_cea"  name="sit"     long_name="sea_ice_thickness"        />
-          <field field_ref="icevolu"      name="iicevolu" />
-          <field field_ref="snowvol"      name="isnowvol" />
-          <field field_ref="iceconc"      name="iiceconc"  />
-
-          <field field_ref="icebopr"          name="iicebopr" />
-          <field field_ref="icedypr"          name="iicedypr" />
-          <field field_ref="ioceflxb"         name="ioceflxb" />
-          <field field_ref="uice_ipa"         name="iicevelu" />
-          <field field_ref="vice_ipa"         name="iicevelv" />
-          <field field_ref="isst"             name="isstempe" />
-          <field field_ref="isss"             name="isssalin" />
-          <field field_ref="micesalt"         name="iicesali" />
-          <field field_ref="miceage"          name="iiceages" />
-          <field field_ref="icelapr"          name="iicelapr" />
-          <field field_ref="icesipr"          name="iicesipr" />
-          <field field_ref="micet"            name="iicetemp" />
-          <field field_ref="icehc"            name="iiceheco" />
-          <field field_ref="isnowhc"          name="isnoheco" />
-          <field field_ref="icest"            name="iicesurt" />
-          <field field_ref="sfxbri"            name="iicefsbr" />
-          <field field_ref="sfxthd"            name="iicefseq" />
-          <field field_ref="ibrinv"           name="ibrinvol" />
-          <field field_ref="icecolf"          name="iicecolf" />
-          <field field_ref="icestr"           name="iicestre" />
-          <field field_ref="icevel"           name="iicevelo" />
-          <field field_ref="isume"            name="iicesume" />
-          <field field_ref="ibome"            name="iicebome" />
-          <field field_ref="idive"            name="iicedive" />
-          <field field_ref="ishear"           name="iiceshea" />
-          <field field_ref="icerepr"          name="iicerepr" />
-          <field field_ref="sfxmec"            name="iicefsrp" />
-          <field field_ref="sfxres"            name="iicefsre" />
-          <field field_ref="icetrp"           name="iicevtrp" />
-	</file>
-
-
-	<file id="file7" name_suffix="_scalar" description="scalar variables" >
+	<file id="file6" name_suffix="_icemod" description="ice variables" enabled=".true." >
+	  <field field_ref="snowthic_cea"     name="snthic"     long_name="surface_snow_thickness"   />
+	  <field field_ref="icethic_cea"      name="sithic"     long_name="sea_ice_thickness"        />
+          <field field_ref="icevolu"          name="sivolu" />
+          <field field_ref="snowvol"          name="snvolu" />
+          <field field_ref="iceconc"          name="siconc"  />
+
+          <field field_ref="vfxbog"          name="vfxbog" />
+          <field field_ref="vfxdyn"          name="vfxdyn" />
+          <field field_ref="vfxopw"          name="vfxopw" />
+          <field field_ref="vfxsni"          name="vfxsni" />
+          <field field_ref="vfxsum"          name="vfxsum" />
+          <field field_ref="vfxbom"          name="vfxbom" />
+          <field field_ref="vfxres"          name="vfxres" />
+          <field field_ref="vfxice"          name="vfxice" />
+          <field field_ref="vfxsnw"          name="vfxsnw" />
+          <field field_ref="vfxsub"          name="vfxsub" />
+          <field field_ref="vfxspr"          name="vfxspr" />
+
+          <field field_ref="icetrp"          name="sivtrp" />
+          <field field_ref="snwtrp"          name="snvtrp" />
+          <field field_ref="deitrp"          name="deitrp" />
+          <field field_ref="destrp"          name="destrp" />
+
+          <field field_ref="sfxbri"           name="sfxbri" />
+          <field field_ref="sfxdyn"           name="sfxdyn" />
+          <field field_ref="sfxres"           name="sfxres" />
+          <field field_ref="sfxbog"           name="sfxbog" />
+          <field field_ref="sfxbom"           name="sfxbom" />
+          <field field_ref="sfxsum"           name="sfxsum" />
+          <field field_ref="sfxsni"           name="sfxsni" />
+          <field field_ref="sfxopw"           name="sfxopw" />
+          <field field_ref="sfx"              name="sfx" />
+
+          <field field_ref="hfxsum"          name="hfxsum"    />
+          <field field_ref="hfxbom"          name="hfxbom"    />
+          <field field_ref="hfxbog"          name="hfxbog"    />
+          <field field_ref="hfxdif"          name="hfxdif"    />
+          <field field_ref="hfxopw"          name="hfxopw"    />
+          <field field_ref="hfxout"          name="hfxout"    />
+          <field field_ref="hfxin"           name="hfxin"    />
+          <field field_ref="hfxsnw"          name="hfxsnw"    />
+          <field field_ref="hfxerr"          name="hfxerr"    />
+          <field field_ref="hfxerr_rem"      name="hfxerr_rem"    />
+
+	  <!-- ice-ocean heat flux from mass exchange -->
+          <field field_ref="hfxdyn"          name="hfxdyn"    />
+          <field field_ref="hfxres"          name="hfxres"    />
+          <field field_ref="hfxthd"          name="hfxthd"    />
+	  <!-- ice-atm. heat flux from mass exchange -->
+          <field field_ref="hfxsub"          name="hfxsub"    />
+          <field field_ref="hfxspr"          name="hfxspr"    />
+
+	  <!-- diags -->
+          <field field_ref="hfxdhc"          name="hfxdhc"    />
+          <field field_ref="hfxtur"          name="hfxtur"    />
+
+          <field field_ref="isst"             name="sst" />
+          <field field_ref="isss"             name="sss" />
+          <field field_ref="micesalt"         name="sisali" />
+          <field field_ref="micet"            name="sitemp" />
+          <field field_ref="icest"            name="sistem" />
+          <field field_ref="icehc"            name="siheco" />
+          <field field_ref="isnowhc"          name="snheco" />
+          <field field_ref="miceage"          name="siages" />
+
+          <field field_ref="uice_ipa"         name="sivelu" />
+          <field field_ref="vice_ipa"         name="sivelv" />
+          <field field_ref="icevel"           name="sivelo" />
+          <field field_ref="idive"            name="sidive" />
+          <field field_ref="ishear"           name="sishea" />
+          <field field_ref="icestr"           name="sistre" />
+
+          <field field_ref="ibrinv"           name="sibrin" />
+          <field field_ref="icecolf"          name="sicolf" />
+
+          <field field_ref="iceage_cat"       name="siagecat"/>
+          <field field_ref="iceconc_cat"      name="siconcat"/>
+          <field field_ref="icethic_cat"      name="sithicat"/>
+          <field field_ref="snowthic_cat"     name="snthicat"/>
+          <field field_ref="salinity_cat"     name="salincat"/>
+          <field field_ref="brinevol_cat"     name="sibricat"/>
+
+	</file>
+
+        <file id="file7" name_suffix="_scalar" description="scalar variables" enabled=".true." >
           <field field_ref="voltot"       name="scvoltot"  />
           <field field_ref="sshtot"       name="scsshtot"  />
@@ -137,36 +190,67 @@
           <field field_ref="temptot"      name="sctemtot"  />
           <field field_ref="saltot"       name="scsaltot"  />
-	
-          <!-- available with ln_diahsb -->
-	  <field field_ref="bgtemper"     name="bgtemper"    />
-	  <field field_ref="bgsaline"     name="bgsaline"    />
-	  <field field_ref="bgheatco"     name="bgheatco"    />
-	  <field field_ref="bgsaltco"     name="bgsaltco"    />
-	  <field field_ref="bgvolssh"     name="bgvolssh"    />
-	  <field field_ref="bgvoltot"     name="bgvoltot"    />
-	  <field field_ref="bgsshtot"     name="bgsshtot"    />
-	  <field field_ref="bgfrcvol"     name="bgfrcvol"    />
-	  <field field_ref="bgfrctem"     name="bgfrctem"    />
-	  <field field_ref="bgfrcsal"     name="bgfrcsal"    />
-	  <!-- available with ln_limdiahsb -->
-	  <field field_ref="ibgvoltot"    name="ibgvoltot"   />
-	  <field field_ref="sbgvoltot"    name="sbgvoltot"   />
-	  <field field_ref="ibgarea"      name="ibgarea"     />
-	  <field field_ref="ibgsaline"    name="ibgsaline"   />
-	  <field field_ref="ibgtemper"    name="ibgtemper"   />
-	  <field field_ref="ibgheatco"    name="ibgheatco"   />
-	  <field field_ref="ibgsaltco"    name="ibgsaltco"   />
-	  <field field_ref="sbgheatco"    name="sbgheatco"   />
-	  <field field_ref="ibgfrcsfx"    name="ibgfrcsfx"  />
-	  <field field_ref="ibgfrcemp"    name="ibgfrcemp"   />
-	  <field field_ref="ibgsfx"       name="ibgsfx"     />
-	  <field field_ref="ibgemp"       name="ibgemp"      />
-	  <field field_ref="ibgsfxbri"    name="ibgsfxbri"    />
-	  <field field_ref="ibgsfxthd"    name="ibgsfxthd"    />
-	  <field field_ref="ibgsfxres"    name="ibgsfxres" />
-	  <field field_ref="ibgsfxmec"    name="ibgsfxmec" />
-	  <field field_ref="ibggrpme"     name="ibggrpme"    />
-
-	</file>
+
+          <field field_ref="bgtemper"     name="bgtemper"    />
+          <field field_ref="bgsaline"     name="bgsaline"    />
+          <field field_ref="bgheatco"     name="bgheatco"    />
+          <field field_ref="bgsaltco"     name="bgsaltco"    />
+          <field field_ref="bgvolssh"     name="bgvolssh"    /> 
+          <field field_ref="bgvole3t"     name="bgvole3t"    />
+          <field field_ref="bgfrcvol"     name="bgfrcvol"    />
+          <field field_ref="bgfrctem"     name="bgfrctem"    />
+          <field field_ref="bgfrcsal"     name="bgfrcsal"    />
+
+          <field field_ref="ibgvoltot"    name="ibgvoltot"   />
+          <field field_ref="sbgvoltot"    name="sbgvoltot"   />
+          <field field_ref="ibgarea"      name="ibgarea"     />
+          <field field_ref="ibgsaline"    name="ibgsaline"   />
+          <field field_ref="ibgtemper"    name="ibgtemper"   />
+          <field field_ref="ibgheatco"    name="ibgheatco"   />
+          <field field_ref="sbgheatco"    name="sbgheatco"   />
+          <field field_ref="ibgsaltco"    name="ibgsaltco"   />
+
+          <field field_ref="ibgvfx"       name="ibgvfx"      />
+          <field field_ref="ibgvfxbog"    name="ibgvfxbog"      />
+          <field field_ref="ibgvfxopw"    name="ibgvfxopw"      />
+          <field field_ref="ibgvfxsni"    name="ibgvfxsni"      />
+          <field field_ref="ibgvfxdyn"    name="ibgvfxdyn"      />
+          <field field_ref="ibgvfxbom"    name="ibgvfxbom"      />
+          <field field_ref="ibgvfxsum"    name="ibgvfxsum"      />
+          <field field_ref="ibgvfxres"    name="ibgvfxres"      />
+          <field field_ref="ibgvfxspr"    name="ibgvfxspr"      />
+          <field field_ref="ibgvfxsnw"    name="ibgvfxsnw"      />
+          <field field_ref="ibgvfxsub"    name="ibgvfxsub"      />
+
+          <field field_ref="ibgsfx"       name="ibgsfx"     />
+          <field field_ref="ibgsfxbri"    name="ibgsfxbri"    />
+          <field field_ref="ibgsfxdyn"    name="ibgsfxdyn" />
+          <field field_ref="ibgsfxres"    name="ibgsfxres" />
+          <field field_ref="ibgsfxbog"    name="ibgsfxbog"      />
+          <field field_ref="ibgsfxopw"    name="ibgsfxopw"      />
+          <field field_ref="ibgsfxsni"    name="ibgsfxsni"      />
+          <field field_ref="ibgsfxbom"    name="ibgsfxbom"      />
+          <field field_ref="ibgsfxsum"    name="ibgsfxsum"      />
+
+          <field field_ref="ibghfxdhc"    name="ibghfxdhc"    />
+          <field field_ref="ibghfxspr"    name="ibghfxspr"    />
+
+          <field field_ref="ibghfxres"    name="ibghfxres"    />
+          <field field_ref="ibghfxsub"    name="ibghfxsub"    />
+          <field field_ref="ibghfxdyn"    name="ibghfxdyn"    />
+          <field field_ref="ibghfxthd"    name="ibghfxthd"    />
+          <field field_ref="ibghfxsum"    name="ibghfxsum"    />
+          <field field_ref="ibghfxbom"    name="ibghfxbom"    />
+          <field field_ref="ibghfxbog"    name="ibghfxbog"    />
+          <field field_ref="ibghfxdif"    name="ibghfxdif"    />
+          <field field_ref="ibghfxopw"    name="ibghfxopw"    />
+          <field field_ref="ibghfxout"    name="ibghfxout"    />
+          <field field_ref="ibghfxin"    name="ibghfxin"    />
+          <field field_ref="ibghfxsnw"    name="ibghfxsnw"    />
+
+          <field field_ref="ibgfrcvol"    name="ibgfrcvol"   />
+          <field field_ref="ibgfrcsfx"    name="ibgfrcsfx"  />
+          <field field_ref="ibgvolgrm"    name="ibgvolgrm"    />
+
+        </file>
 
 	<!--
@@ -214,4 +298,5 @@
       <axis id="nfloat" long_name="Float number"      unit="-"  />
       <axis id="icbcla" long_name="Iceberg class"     unit="-"  />
+      <axis id="ncatice" long_name="Ice categories"   unit="-"  />
    </axis_definition> 
     
@@ -241,5 +326,5 @@
 	  <variable id="buffer_server_factor_size" type="integer">2</variable>
 	  <variable id="info_level"                type="integer">0</variable>
-	  <variable id="using_server"              type="boolean">true</variable>
+	  <variable id="using_server"              type="boolean">false</variable>
 	  <variable id="using_oasis"               type="boolean">false</variable>
 	  <variable id="oasis_codes_id"            type="string" >oceanx</variable>
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef_default.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef_default.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/iodef_default.xml	(revision 5075)
@@ -47,20 +47,25 @@
 	  <field field_ref="mldkz5"       />
 	  <field field_ref="mldr10_1"     />
+      <field field_ref="heatc"        name="heatc"    long_name="Heat content vertically integrated"            />
+      <field field_ref="saltc"        name="saltc"    long_name="Salt content vertically integrated"            />
 	</file>
 
 	<file id="file2" name_suffix="_SBC" description="surface fluxes variables" > <!-- time step automaticaly defined based on nn_fsbc -->
 	  <field field_ref="empmr"        name="wfo"      long_name="water_flux_into_sea_water"                     />
-	  <field field_ref="qsr"          name="rsntds"   long_name="surface_net_downward_shortwave_flux"           />
-	  <field field_ref="qt"           name="tohfls"   long_name="surface_net_downward_total_heat_flux"          />
-	  <field field_ref="saltflx"      name="sosflxdo"  />
+	  <field field_ref="qsr_oce"      name="qsr_oce"  long_name="downward shortwave flux at ocean surface"           />
+	  <field field_ref="qns_oce"      name="qns_oce"  long_name="downward non solar flux at ocean surface"           />
+	  <field field_ref="qt_oce"       name="qt_oce"   long_name="downward total flux at ocean surface"           />
+	  <field field_ref="qsr_ice"      name="qsr_ice"  long_name="downward shortwave flux at ice surface"           />
+	  <field field_ref="qns_ice"      name="qns_ice"  long_name="downward non solar flux at ice surface"           />
+	  <field field_ref="qtr_ice"      name="qtr_ice"  long_name="shortwave flux transmitted thru the ice"           />
+	  <field field_ref="qt_ice"       name="qt_ice"   long_name="downward total flux at ice surface"           />
+	  <field field_ref="saltflx"      name="sfx"  />
 	  <field field_ref="taum"         name="taum" />
-	  <field field_ref="wspd"         name="sowindsp"  />
-          <field field_ref="precip"       name="soprecip" />
+	  <field field_ref="wspd"         name="windsp"  />
+      <field field_ref="precip"       name="precip" />
 	  <!-- ice and snow -->
 	  <field field_ref="snowpre"      />
-          <field field_ref="qsr_io"           name="iicesflx" />
-          <field field_ref="qns_io"           name="iicenflx" />
-          <field field_ref="utau_ice"         name="iicestru" />
-          <field field_ref="vtau_ice"         name="iicestrv" />
+      <field field_ref="utau_ice"         name="utau_ice" />
+      <field field_ref="vtau_ice"         name="vtau_ice" />
 
 	</file>
@@ -73,4 +78,5 @@
 	  <field field_ref="u_masstr"     name="vozomatr"  />
 	  <field field_ref="u_heattr"     name="sozohetr"  />
+      <field field_ref="u_salttr"     name="sozosatr"  />
 	</file>
 	
@@ -82,4 +88,5 @@
 	  <field field_ref="v_masstr"     name="vomematr"  />
 	  <field field_ref="v_heattr"     name="somehetr"  />
+      <field field_ref="v_salttr"     name="somesatr"  />
 	</file>
 	
@@ -90,44 +97,90 @@
 	</file>
 
-	<file id="file6" name_suffix="_icemod" description="ice variables" >
-	  <field field_ref="snowthic_cea" name="snd"     long_name="surface_snow_thickness"   />
-	  <field field_ref="icethic_cea"  name="sit"     long_name="sea_ice_thickness"        />
-          <field field_ref="icevolu"      name="iicevolu" />
-          <field field_ref="snowvol"      name="isnowvol" />
-          <field field_ref="iceconc"      name="iiceconc"  />
-
-          <field field_ref="icebopr"          name="iicebopr" />
-          <field field_ref="icedypr"          name="iicedypr" />
-          <field field_ref="ioceflxb"         name="ioceflxb" />
-          <field field_ref="uice_ipa"         name="iicevelu" />
-          <field field_ref="vice_ipa"         name="iicevelv" />
-          <field field_ref="isst"             name="isstempe" />
-          <field field_ref="isss"             name="isssalin" />
-          <field field_ref="micesalt"         name="iicesali" />
-          <field field_ref="miceage"          name="iiceages" />
-          <field field_ref="icelapr"          name="iicelapr" />
-          <field field_ref="icesipr"          name="iicesipr" />
-          <field field_ref="micet"            name="iicetemp" />
-          <field field_ref="icehc"            name="iiceheco" />
-          <field field_ref="isnowhc"          name="isnoheco" />
-          <field field_ref="icest"            name="iicesurt" />
-          <field field_ref="sfxbri"            name="iicefsbr" />
-          <field field_ref="sfxthd"            name="iicefseq" />
-          <field field_ref="ibrinv"           name="ibrinvol" />
-          <field field_ref="icecolf"          name="iicecolf" />
-          <field field_ref="icestr"           name="iicestre" />
-          <field field_ref="icevel"           name="iicevelo" />
-          <field field_ref="isume"            name="iicesume" />
-          <field field_ref="ibome"            name="iicebome" />
-          <field field_ref="idive"            name="iicedive" />
-          <field field_ref="ishear"           name="iiceshea" />
-          <field field_ref="icerepr"          name="iicerepr" />
-          <field field_ref="sfxmec"            name="iicefsrp" />
-          <field field_ref="sfxres"            name="iicefsre" />
-          <field field_ref="icetrp"           name="iicevtrp" />
-	</file>
-
-
-	<file id="file7" name_suffix="_scalar" description="scalar variables" >
+	<file id="file6" name_suffix="_icemod" description="ice variables" enabled=".true." >
+	  <field field_ref="snowthic_cea"     name="snthic"     long_name="surface_snow_thickness"   />
+	  <field field_ref="icethic_cea"      name="sithic"     long_name="sea_ice_thickness"        />
+          <field field_ref="icevolu"          name="sivolu" />
+          <field field_ref="snowvol"          name="snvolu" />
+          <field field_ref="iceconc"          name="siconc"  />
+
+          <field field_ref="vfxbog"          name="vfxbog" />
+          <field field_ref="vfxdyn"          name="vfxdyn" />
+          <field field_ref="vfxopw"          name="vfxopw" />
+          <field field_ref="vfxsni"          name="vfxsni" />
+          <field field_ref="vfxsum"          name="vfxsum" />
+          <field field_ref="vfxbom"          name="vfxbom" />
+          <field field_ref="vfxres"          name="vfxres" />
+          <field field_ref="vfxice"          name="vfxice" />
+          <field field_ref="vfxsnw"          name="vfxsnw" />
+          <field field_ref="vfxsub"          name="vfxsub" />
+          <field field_ref="vfxspr"          name="vfxspr" />
+
+          <field field_ref="icetrp"          name="sivtrp" />
+          <field field_ref="snwtrp"          name="snvtrp" />
+          <field field_ref="deitrp"          name="deitrp" />
+          <field field_ref="destrp"          name="destrp" />
+
+          <field field_ref="sfxbri"           name="sfxbri" />
+          <field field_ref="sfxdyn"           name="sfxdyn" />
+          <field field_ref="sfxres"           name="sfxres" />
+          <field field_ref="sfxbog"           name="sfxbog" />
+          <field field_ref="sfxbom"           name="sfxbom" />
+          <field field_ref="sfxsum"           name="sfxsum" />
+          <field field_ref="sfxsni"           name="sfxsni" />
+          <field field_ref="sfxopw"           name="sfxopw" />
+          <field field_ref="sfx"              name="sfx" />
+
+          <field field_ref="hfxsum"          name="hfxsum"    />
+          <field field_ref="hfxbom"          name="hfxbom"    />
+          <field field_ref="hfxbog"          name="hfxbog"    />
+          <field field_ref="hfxdif"          name="hfxdif"    />
+          <field field_ref="hfxopw"          name="hfxopw"    />
+          <field field_ref="hfxout"          name="hfxout"    />
+          <field field_ref="hfxin"           name="hfxin"    />
+          <field field_ref="hfxsnw"          name="hfxsnw"    />
+          <field field_ref="hfxerr"          name="hfxerr"    />
+          <field field_ref="hfxerr_rem"      name="hfxerr_rem"    />
+
+	  <!-- ice-ocean heat flux from mass exchange -->
+          <field field_ref="hfxdyn"          name="hfxdyn"    />
+          <field field_ref="hfxres"          name="hfxres"    />
+          <field field_ref="hfxthd"          name="hfxthd"    />
+	  <!-- ice-atm. heat flux from mass exchange -->
+          <field field_ref="hfxsub"          name="hfxsub"    />
+          <field field_ref="hfxspr"          name="hfxspr"    />
+
+	  <!-- diags -->
+          <field field_ref="hfxdhc"          name="hfxdhc"    />
+          <field field_ref="hfxtur"          name="hfxtur"    />
+
+          <field field_ref="isst"             name="sst" />
+          <field field_ref="isss"             name="sss" />
+          <field field_ref="micesalt"         name="sisali" />
+          <field field_ref="micet"            name="sitemp" />
+          <field field_ref="icest"            name="sistem" />
+          <field field_ref="icehc"            name="siheco" />
+          <field field_ref="isnowhc"          name="snheco" />
+          <field field_ref="miceage"          name="siages" />
+
+          <field field_ref="uice_ipa"         name="sivelu" />
+          <field field_ref="vice_ipa"         name="sivelv" />
+          <field field_ref="icevel"           name="sivelo" />
+          <field field_ref="idive"            name="sidive" />
+          <field field_ref="ishear"           name="sishea" />
+          <field field_ref="icestr"           name="sistre" />
+
+          <field field_ref="ibrinv"           name="sibrin" />
+          <field field_ref="icecolf"          name="sicolf" />
+
+          <field field_ref="iceage_cat"       name="siagecat"/>
+          <field field_ref="iceconc_cat"      name="siconcat"/>
+          <field field_ref="icethic_cat"      name="sithicat"/>
+          <field field_ref="snowthic_cat"     name="snthicat"/>
+          <field field_ref="salinity_cat"     name="salincat"/>
+          <field field_ref="brinevol_cat"     name="sibricat"/>
+
+	</file>
+
+        <file id="file7" name_suffix="_scalar" description="scalar variables" enabled=".true." >
           <field field_ref="voltot"       name="scvoltot"  />
           <field field_ref="sshtot"       name="scsshtot"  />
@@ -137,36 +190,67 @@
           <field field_ref="temptot"      name="sctemtot"  />
           <field field_ref="saltot"       name="scsaltot"  />
-	
-          <!-- available with ln_diahsb -->
-	  <field field_ref="bgtemper"     name="bgtemper"    />
-	  <field field_ref="bgsaline"     name="bgsaline"    />
-	  <field field_ref="bgheatco"     name="bgheatco"    />
-	  <field field_ref="bgsaltco"     name="bgsaltco"    />
-	  <field field_ref="bgvolssh"     name="bgvolssh"    />
-	  <field field_ref="bgvoltot"     name="bgvoltot"    />
-	  <field field_ref="bgsshtot"     name="bgsshtot"    />
-	  <field field_ref="bgfrcvol"     name="bgfrcvol"    />
-	  <field field_ref="bgfrctem"     name="bgfrctem"    />
-	  <field field_ref="bgfrcsal"     name="bgfrcsal"    />
-	  <!-- available with ln_limdiahsb -->
-	  <field field_ref="ibgvoltot"    name="ibgvoltot"   />
-	  <field field_ref="sbgvoltot"    name="sbgvoltot"   />
-	  <field field_ref="ibgarea"      name="ibgarea"     />
-	  <field field_ref="ibgsaline"    name="ibgsaline"   />
-	  <field field_ref="ibgtemper"    name="ibgtemper"   />
-	  <field field_ref="ibgheatco"    name="ibgheatco"   />
-	  <field field_ref="ibgsaltco"    name="ibgsaltco"   />
-	  <field field_ref="sbgheatco"    name="sbgheatco"   />
-	  <field field_ref="ibgfrcsfx"    name="ibgfrcsfx"  />
-	  <field field_ref="ibgfrcemp"    name="ibgfrcemp"   />
-	  <field field_ref="ibgsfx"       name="ibgsfx"     />
-	  <field field_ref="ibgemp"       name="ibgemp"      />
-	  <field field_ref="ibgsfxbri"    name="ibgsfxbri"    />
-	  <field field_ref="ibgsfxthd"    name="ibgsfxthd"    />
-	  <field field_ref="ibgsfxres"    name="ibgsfxres" />
-	  <field field_ref="ibgsfxmec"    name="ibgsfxmec" />
-	  <field field_ref="ibggrpme"     name="ibggrpme"    />
-
-	</file>
+
+          <field field_ref="bgtemper"     name="bgtemper"    />
+          <field field_ref="bgsaline"     name="bgsaline"    />
+          <field field_ref="bgheatco"     name="bgheatco"    />
+          <field field_ref="bgsaltco"     name="bgsaltco"    />
+          <field field_ref="bgvolssh"     name="bgvolssh"    /> 
+          <field field_ref="bgvole3t"     name="bgvole3t"    />
+          <field field_ref="bgfrcvol"     name="bgfrcvol"    />
+          <field field_ref="bgfrctem"     name="bgfrctem"    />
+          <field field_ref="bgfrcsal"     name="bgfrcsal"    />
+
+          <field field_ref="ibgvoltot"    name="ibgvoltot"   />
+          <field field_ref="sbgvoltot"    name="sbgvoltot"   />
+          <field field_ref="ibgarea"      name="ibgarea"     />
+          <field field_ref="ibgsaline"    name="ibgsaline"   />
+          <field field_ref="ibgtemper"    name="ibgtemper"   />
+          <field field_ref="ibgheatco"    name="ibgheatco"   />
+          <field field_ref="sbgheatco"    name="sbgheatco"   />
+          <field field_ref="ibgsaltco"    name="ibgsaltco"   />
+
+          <field field_ref="ibgvfx"       name="ibgvfx"      />
+          <field field_ref="ibgvfxbog"    name="ibgvfxbog"      />
+          <field field_ref="ibgvfxopw"    name="ibgvfxopw"      />
+          <field field_ref="ibgvfxsni"    name="ibgvfxsni"      />
+          <field field_ref="ibgvfxdyn"    name="ibgvfxdyn"      />
+          <field field_ref="ibgvfxbom"    name="ibgvfxbom"      />
+          <field field_ref="ibgvfxsum"    name="ibgvfxsum"      />
+          <field field_ref="ibgvfxres"    name="ibgvfxres"      />
+          <field field_ref="ibgvfxspr"    name="ibgvfxspr"      />
+          <field field_ref="ibgvfxsnw"    name="ibgvfxsnw"      />
+          <field field_ref="ibgvfxsub"    name="ibgvfxsub"      />
+
+          <field field_ref="ibgsfx"       name="ibgsfx"     />
+          <field field_ref="ibgsfxbri"    name="ibgsfxbri"    />
+          <field field_ref="ibgsfxdyn"    name="ibgsfxdyn" />
+          <field field_ref="ibgsfxres"    name="ibgsfxres" />
+          <field field_ref="ibgsfxbog"    name="ibgsfxbog"      />
+          <field field_ref="ibgsfxopw"    name="ibgsfxopw"      />
+          <field field_ref="ibgsfxsni"    name="ibgsfxsni"      />
+          <field field_ref="ibgsfxbom"    name="ibgsfxbom"      />
+          <field field_ref="ibgsfxsum"    name="ibgsfxsum"      />
+
+          <field field_ref="ibghfxdhc"    name="ibghfxdhc"    />
+          <field field_ref="ibghfxspr"    name="ibghfxspr"    />
+
+          <field field_ref="ibghfxres"    name="ibghfxres"    />
+          <field field_ref="ibghfxsub"    name="ibghfxsub"    />
+          <field field_ref="ibghfxdyn"    name="ibghfxdyn"    />
+          <field field_ref="ibghfxthd"    name="ibghfxthd"    />
+          <field field_ref="ibghfxsum"    name="ibghfxsum"    />
+          <field field_ref="ibghfxbom"    name="ibghfxbom"    />
+          <field field_ref="ibghfxbog"    name="ibghfxbog"    />
+          <field field_ref="ibghfxdif"    name="ibghfxdif"    />
+          <field field_ref="ibghfxopw"    name="ibghfxopw"    />
+          <field field_ref="ibghfxout"    name="ibghfxout"    />
+          <field field_ref="ibghfxin"    name="ibghfxin"    />
+          <field field_ref="ibghfxsnw"    name="ibghfxsnw"    />
+
+          <field field_ref="ibgfrcvol"    name="ibgfrcvol"   />
+          <field field_ref="ibgfrcsfx"    name="ibgfrcsfx"  />
+          <field field_ref="ibgvolgrm"    name="ibgvolgrm"    />
+
+        </file>
 
 	<!--
@@ -214,4 +298,5 @@
       <axis id="nfloat" long_name="Float number"      unit="-"  />
       <axis id="icbcla" long_name="Iceberg class"     unit="-"  />
+      <axis id="ncatice" long_name="Ice categories"   unit="-"  />
    </axis_definition> 
     
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_cfg	(revision 5075)
@@ -139,4 +139,11 @@
 &namdyn_hpg    !   Hydrostatic pressure gradient option
 !-----------------------------------------------------------------------
+   ln_hpg_zco  = .false.   !  z-coordinate - full steps
+   ln_hpg_zps  = .false.   !  z-coordinate - partial steps (interpolation)
+   ln_hpg_sco  = .false.   !  s-coordinate (standard jacobian formulation)
+   ln_hpg_djc  = .false.   !  s-coordinate (Density Jacobian with Cubic polynomial)
+   ln_hpg_prj  = .true.    !  s-coordinate (Pressure Jacobian scheme)
+   ln_dynhpg_imp = .false. !  time stepping: semi-implicit time scheme  (T)
+                                 !           centered      time scheme  (F)
 /
 !-----------------------------------------------------------------------
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_ice_cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_ice_cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/EXP00/namelist_ice_cfg	(revision 5075)
@@ -16,9 +16,17 @@
 /
 !-----------------------------------------------------------------------
-&namicetrp     !   ice transport
+&namicethd     !   ice thermodynamic
 !-----------------------------------------------------------------------
 /
 !-----------------------------------------------------------------------
-&namicethd     !   ice thermodynamic
+&namicesal     !   ice salinity
 !-----------------------------------------------------------------------
 /
+!-----------------------------------------------------------------------
+&namiceitdme   !   parameters for mechanical redistribution of ice 
+!-----------------------------------------------------------------------
+/
+!-----------------------------------------------------------------------
+&namicedia     !   ice diagnostics
+!-----------------------------------------------------------------------
+/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/cpp_ORCA2_LIM3.fcm
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/cpp_ORCA2_LIM3.fcm	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM3/cpp_ORCA2_LIM3.fcm	(revision 5075)
@@ -1,1 +1,1 @@
- bld::tool::fppkeys key_trabbl key_lim3 key_dynspg_flt key_diaeiv key_ldfslp key_traldf_c2d key_traldf_eiv key_dynldf_c3d key_zdftke key_zdfddm key_zdftmx key_iomput key_mpp_mpi
+ bld::tool::fppkeys key_trabbl key_lim3 key_vvl key_dynspg_ts key_diaeiv key_ldfslp key_traldf_c2d key_traldf_eiv key_dynldf_c3d key_zdftke key_zdfddm key_zdftmx key_iomput key_mpp_mpi key_diaobs key_asminc
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM_PISCES/EXP00/iodef.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM_PISCES/EXP00/iodef.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_LIM_PISCES/EXP00/iodef.xml	(revision 5075)
@@ -46,5 +46,17 @@
 	  <field field_ref="svoce"        name="vos"     long_name="sea_surface_y_velocity"    />
 	</file>
-	
+
+        <file id="file4" name_suffix="_bioscalar" description="pisces sms variables" >
+          <field field_ref="tdenit"   name="tdenit"   unit="TgN/yr" operation="instant" > tdenit * 14. * 86400. * 365. / 1e12 </field>
+          <field field_ref="tnfix"    name="tnfix"    unit="TgN/yr" operation="instant" > tnfix * 14. * 86400. * 365. / 1e12 </field>
+          <field field_ref="tcflx"    name="tcflx"    unit="PgC/yr" operation="instant" > tcflx * -1. * 12. * 86400. * 365. / 1e15 </field>
+          <field field_ref="tcflxcum" name="tcflxcum" unit="PgC"    operation="instant" > tcflxcum * -1. * 12. / 1e15 </field>
+          <field field_ref="tcexp"    name="tcexp"    unit="PgC/yr" operation="instant" > tcexp * 12. * 86400. * 365. / 1e15 </field>
+          <field field_ref="tintpp"   name="tintpp"   unit="PgC/yr" operation="instant" > tintpp * 12. * 86400. * 365. / 1e15 </field>
+          <field field_ref="pno3tot"  name="pno3tot"  unit="umolN"  > pno3tot * 16. / 122. * 1e6 </field>
+          <field field_ref="psiltot"  name="psiltot"  unit="umolC"  > psiltot * 1e6  </field>
+          <field field_ref="palktot"  name="palktot"  unit="umolC"  > palktot * 1e6  </field>
+        <field field_ref="pfertot"  name="pfertot"  unit="nmolFe" > pfertot * 1e9  </field>
+                                                                                                                             </file>
       </file_group>
 
@@ -53,5 +65,5 @@
       <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE.">  <!-- 5d files -->   
 
-	<file id="file4" name_suffix="_grid_T" description="ocean T grid variables" >
+	<file id="file5" name_suffix="_grid_T" description="ocean T grid variables" >
 	  <field field_ref="toce"         name="thetao"   long_name="sea_water_potential_temperature"               />
 	  <field field_ref="soce"         name="so"       long_name="sea_water_salinity"                            />
@@ -72,5 +84,5 @@
 	</file>
 	
-	<file id="file5" name_suffix="_grid_U" description="ocean U grid variables" >
+	<file id="file6" name_suffix="_grid_U" description="ocean U grid variables" >
 	  <field field_ref="uoce"         name="uo"      long_name="sea_water_x_velocity"      />
 	  <field field_ref="suoce"        name="uos"     long_name="sea_surface_x_velocity"    />
@@ -81,5 +93,5 @@
 	</file>
 	
-	<file id="file6" name_suffix="_grid_V" description="ocean V grid variables" >
+	<file id="file7" name_suffix="_grid_V" description="ocean V grid variables" >
 	  <field field_ref="voce"         name="vo"      long_name="sea_water_y_velocity"      />
 	  <field field_ref="svoce"        name="vos"     long_name="sea_surface_y_velocity"    />
@@ -90,10 +102,10 @@
 	</file>
 	
-	<file id="file7" name_suffix="_grid_W" description="ocean W grid variables" >
+	<file id="file8" name_suffix="_grid_W" description="ocean W grid variables" >
 	  <field field_ref="woce"         name="wo"      long_name="ocean vertical velocity"         />
 	  <field field_ref="avt"          name="difvho"  long_name="ocean_vertical_heat_diffusivity" />
 	</file>
 	
-	<file id="file8" name_suffix="_icemod" description="ice variables" >
+	<file id="file9" name_suffix="_icemod" description="ice variables" >
 	  <field field_ref="ice_pres"                     />
 	  <field field_ref="snowthic_cea" name="snd"     long_name="surface_snow_thickness"   />
@@ -101,5 +113,4 @@
 	  <field field_ref="iceprod_cea"  name="sip"     long_name="sea_ice_thickness"        />
 	  <field field_ref="ist_ipa"      />
-	  <field field_ref="ioceflxb"     />
 	  <field field_ref="uice_ipa"     />
 	  <field field_ref="vice_ipa"     />
@@ -115,5 +126,5 @@
       <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
 
-	<file id="file9" name_suffix="_ptrc_T" description="pisces sms variables" >
+	<file id="file10" name_suffix="_ptrc_T" description="pisces sms variables" >
           <field field_ref="DIC"      />
           <field field_ref="Alkalini" />
@@ -127,5 +138,5 @@
 	</file>
 	
-	<file id="file10" name_suffix="_diad_T" description="additional pisces diagnostics" >
+	<file id="file11" name_suffix="_diad_T" description="additional pisces diagnostics" >
           <field field_ref="Cflx"     />
           <field field_ref="Dpco2"    />
@@ -141,5 +152,5 @@
       <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."> <!-- real yearly files -->
 
-	<file id="file11" name_suffix="_ptrc_T" description="pisces sms variables" >
+	<file id="file12" name_suffix="_ptrc_T" description="pisces sms variables" >
           <field field_ref="DIC"      />
           <field field_ref="Alkalini" />
@@ -168,5 +179,5 @@
 	</file>
 
-	<file id="file12" name_suffix="_diad_T" description="additional pisces diagnostics" >
+	<file id="file13" name_suffix="_diad_T" description="additional pisces diagnostics" >
           <field field_ref="PH"       />
           <field field_ref="CO3"      />
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_OFF_PISCES/EXP00/iodef.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_OFF_PISCES/EXP00/iodef.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_OFF_PISCES/EXP00/iodef.xml	(revision 5075)
@@ -30,5 +30,19 @@
       <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->
      
-      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."/> <!-- 1d files -->
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."> <!-- 1d files -->
+        <file id="file1" name_suffix="_bioscalar" description="pisces sms variables" >
+           <field field_ref="tdenit"   name="tdenit"   unit="TgN/yr" operation="instant" > tdenit * 14. * 86400. * 365. / 1e12 </field>
+           <field field_ref="tnfix"    name="tnfix"    unit="TgN/yr" operation="instant" > tnfix * 14. * 86400. * 365. / 1e12 </field>
+           <field field_ref="tcflx"    name="tcflx"    unit="PgC/yr" operation="instant" > tcflx * -1. * 12. * 86400. * 365. / 1e15 </field>
+           <field field_ref="tcflxcum" name="tcflxcum" unit="PgC"    operation="instant" > tcflxcum * -1. * 12. / 1e15 </field>
+           <field field_ref="tcexp"    name="tcexp"    unit="PgC/yr" operation="instant" > tcexp * 12. * 86400. * 365. / 1e15 </field>
+           <field field_ref="tintpp"   name="tintpp"   unit="PgC/yr" operation="instant" > tintpp * 12. * 86400. * 365. / 1e15 </field>
+           <field field_ref="pno3tot"  name="pno3tot"  unit="umolN"  > pno3tot * 16. / 122. * 1e6 </field>
+           <field field_ref="psiltot"  name="psiltot"  unit="umolC"  > psiltot * 1e6  </field>
+           <field field_ref="palktot"  name="palktot"  unit="umolC"  > palktot * 1e6  </field>
+           <field field_ref="pfertot"  name="pfertot"  unit="nmolFe" > pfertot * 1e9  </field>
+        </file>
+      </file_group>
+
       <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->    
       <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d files -->   
@@ -36,5 +50,5 @@
       <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."> <!-- real monthly files -->
 
-	<file id="file1" name_suffix="_ptrc_T" description="pisces sms variables" >
+	<file id="file2" name_suffix="_ptrc_T" description="pisces sms variables" >
           <field field_ref="DIC"      />
           <field field_ref="Alkalini" />
@@ -48,5 +62,5 @@
 	</file>
 	
-	<file id="file2" name_suffix="_diad_T" description="additional pisces diagnostics" >
+	<file id="file3" name_suffix="_diad_T" description="additional pisces diagnostics" >
           <field field_ref="Cflx"     />
           <field field_ref="Dpco2"    />
@@ -61,5 +75,5 @@
       <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."> <!-- real yearly files -->
 
-	<file id="file3" name_suffix="_ptrc_T" description="pisces sms variables" >
+	<file id="file4" name_suffix="_ptrc_T" description="pisces sms variables" >
           <field field_ref="DIC"      />
           <field field_ref="Alkalini" />
@@ -88,5 +102,5 @@
 	</file>
 
-	<file id="file4" name_suffix="_diad_T" description="additional pisces diagnostics" >
+	<file id="file5" name_suffix="_diad_T" description="additional pisces diagnostics" >
           <field field_ref="PH"       />
           <field field_ref="CO3"      />
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_SAS_LIM/EXP00/iodef.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_SAS_LIM/EXP00/iodef.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/ORCA2_SAS_LIM/EXP00/iodef.xml	(revision 5075)
@@ -84,5 +84,4 @@
 	  <field field_ref="iceprod_cea"  name="sip"     long_name="sea_ice_thickness"        />
 	  <field field_ref="ist_ipa"      />
-	  <field field_ref="ioceflxb"     />
 	  <field field_ref="uice_ipa"     />
 	  <field field_ref="vice_ipa"     />
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/1_namelist_ref
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/1_namelist_ref	(revision 5074)
+++ 	(revision )
@@ -1,1163 +1,0 @@
-!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-!! NEMO/OPA  :  1 - run manager      (namrun, namcfg)
-!! namelists    2 - Domain           (namzgr, namzgr_sco, namdom, namtsd)
-!!              3 - Surface boundary (namsbc, namsbc_ana, namsbc_flx, namsbc_clio, namsbc_core, namsbc_sas
-!!                                    namsbc_cpl, namtra_qsr, namsbc_rnf,
-!!                                    namsbc_apr, namsbc_ssr, namsbc_alb)
-!!              4 - lateral boundary (namlbc, namcla, namobc, namagrif, nambdy, nambdy_tide)
-!!              5 - bottom  boundary (nambfr, nambbc, nambbl)
-!!              6 - Tracer           (nameos, namtra_adv, namtra_ldf, namtra_dmp)
-!!              7 - dynamics         (namdyn_adv, namdyn_vor, namdyn_hpg, namdyn_spg, namdyn_ldf)
-!!              8 - Verical physics  (namzdf, namzdf_ric, namzdf_tke, namzdf_kpp, namzdf_ddm, namzdf_tmx)
-!!              9 - diagnostics      (namnc4, namtrd, namspr, namflo, namptr, namhsb)
-!!             10 - miscellaneous    (namsol, nammpp, namctl)
-!!             11 - Obs & Assim      (namobs, nam_asminc)
-!!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-
-!!======================================================================
-!!                   ***  Run management namelists  ***
-!!======================================================================
-!!   namrun        parameters of the run
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namrun        !   parameters of the run
-!-----------------------------------------------------------------------
-   nn_no       =       0   !  job number (no more used...)
-   cn_exp      =  "ORCA2"  !  experience name
-   nn_it000    =       1   !  first time step
-   nn_itend    =    5475   !  last  time step (std 5475)
-   nn_date0    =  010101   !  date at nit_0000 (format yyyymmdd) used if ln_rstart=F or (ln_rstart=T and nn_rstctl=0 or 1)
-   nn_time0    =       0   !  initial time of day in hours
-   nn_leapy    =       0   !  Leap year calendar (1) or not (0)
-   ln_rstart   = .false.   !  start from rest (F) or from a restart file (T)
-   nn_rstctl   =       0   !  restart control => activated only if ln_rstart = T
-                           !    = 0 nn_date0 read in namelist ; nn_it000 : read in namelist
-                           !    = 1 nn_date0 read in namelist ; nn_it000 : check consistancy between namelist and restart
-                           !    = 2 nn_date0 read in restart  ; nn_it000 : check consistancy between namelist and restart
-   cn_ocerst_in  = "restart"   !  suffix of ocean restart name (input)
-   cn_ocerst_out = "restart"   !  suffix of ocean restart name (output)
-   nn_istate   =       0   !  output the initial state (1) or not (0)
-   nn_stock    =    5475   !  frequency of creation of a restart file (modulo referenced to 1)
-   nn_write    =    5475   !  frequency of write in the output file   (modulo referenced to nn_it000)
-   ln_dimgnnn  = .false.   !  DIMG file format: 1 file for all processors (F) or by processor (T)
-   ln_mskland  = .false.   !  mask land points in NetCDF outputs (costly: + ~15%)
-   ln_clobber  = .false.   !  clobber (overwrite) an existing file
-   nn_chunksz  =       0   !  chunksize (bytes) for NetCDF file (works only with iom_nf90 routines)
-/
-!
-!-----------------------------------------------------------------------
-&namcfg     !   default parameters of the configuration      
-!-----------------------------------------------------------------------
-   cp_cfg      =  "default"            !  name of the configuration
-   cp_cfz      =         ''            !  name of the zoom of configuration
-   jp_cfg      =       0               !  resolution of the configuration
-   jpidta      =      10               !  1st lateral dimension ( >= jpi )
-   jpjdta      =      12               !  2nd    "         "    ( >= jpj )
-   jpkdta      =      31               !  number of levels      ( >= jpk )
-   jpiglo      =      10               !  1st dimension of global domain --> i =jpidta
-   jpjglo      =      12               !  2nd    -                  -    --> j  =jpjdta
-   jpizoom     =       1               !  left bottom (i,j) indices of the zoom
-   jpjzoom     =       1               !  in data domain indices
-   jperio      =       0               !  lateral cond. type (between 0 and 6)
-                                       !  = 0 closed                 ;   = 1 cyclic East-West
-                                       !  = 2 equatorial symmetric   ;   = 3 North fold T-point pivot 
-                                       !  = 4 cyclic East-West AND North fold T-point pivot
-                                       !  = 5 North fold F-point pivot
-                                       !  = 6 cyclic East-West AND North fold F-point pivot
-/
-!!======================================================================
-!!                      ***  Domain namelists  ***
-!!======================================================================
-!!   namzgr       vertical coordinate
-!!   namzgr_sco   s-coordinate or hybrid z-s-coordinate
-!!   namdom       space and time domain (bathymetry, mesh, timestep)
-!!   namtsd       data: temperature & salinity
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namzgr        !   vertical coordinate
-!-----------------------------------------------------------------------
-   ln_zco      = .false.   !  z-coordinate - full    steps   (T/F)      ("key_zco" may also be defined)
-   ln_zps      = .true.    !  z-coordinate - partial steps   (T/F)
-   ln_sco      = .false.   !  s- or hybrid z-s-coordinate    (T/F)
-/
-!-----------------------------------------------------------------------
-&namzgr_sco    !   s-coordinate or hybrid z-s-coordinate
-!-----------------------------------------------------------------------
-   ln_s_sh94   = .true.    !  Song & Haidvogel 1994 hybrid S-sigma   (T)|
-   ln_s_sf12   = .false.   !  Siddorn & Furner 2012 hybrid S-z-sigma (T)| if both are false the NEMO tanh stretching is applied
-   ln_sigcrit  = .false.   !  use sigma coordinates below critical depth (T) or Z coordinates (F) for Siddorn & Furner stretch
-                           !  stretching coefficients for all functions
-   rn_sbot_min =   10.0    !  minimum depth of s-bottom surface (>0) (m)
-   rn_sbot_max = 7000.0    !  maximum depth of s-bottom surface (= ocean depth) (>0) (m)
-   rn_hc       =  150.0    !  critical depth for transition to stretched coordinates
-                        !!!!!!!  Envelop bathymetry
-   rn_rmax     =    0.3    !  maximum cut-off r-value allowed (0<r_max<1)
-                        !!!!!!!  SH94 stretching coefficients  (ln_s_sh94 = .true.)
-   rn_theta    =    6.0    !  surface control parameter (0<=theta<=20)
-   rn_bb       =    0.8    !  stretching with SH94 s-sigma   
-                        !!!!!!!  SF12 stretching coefficient  (ln_s_sf12 = .true.)
-   rn_alpha    =    4.4    !  stretching with SF12 s-sigma
-   rn_efold    =    0.0    !  efold length scale for transition to stretched coord
-   rn_zs       =    1.0    !  depth of surface grid box
-                           !  bottom cell depth (Zb) is a linear function of water depth Zb = H*a + b
-   rn_zb_a     =    0.024  !  bathymetry scaling factor for calculating Zb
-   rn_zb_b     =   -0.2    !  offset for calculating Zb
-                        !!!!!!!! Other stretching (not SH94 or SF12) [also uses rn_theta above]
-   rn_thetb    =    1.0    !  bottom control parameter  (0<=thetb<= 1) 
-/
-!-----------------------------------------------------------------------
-&namdom        !   space and time domain (bathymetry, mesh, timestep)
-!-----------------------------------------------------------------------
-   nn_bathy    =    1      !  compute (=0) or read (=1) the bathymetry file
-   rn_bathy    =    0.     !  value of the bathymetry. if (=0) bottom flat at jpkm1
-   nn_closea   =    0      !  remove (=0) or keep (=1) closed seas and lakes (ORCA)
-   nn_msh      =    0      !  create (=1) a mesh file or not (=0)
-   rn_hmin     =   -3.     !  min depth of the ocean (>0) or min number of ocean level (<0)
-   rn_e3zps_min=   20.     !  partial step thickness is set larger than the minimum of
-   rn_e3zps_rat=    0.1    !  rn_e3zps_min and rn_e3zps_rat*e3t, with 0<rn_e3zps_rat<1
-                           !
-   rn_rdt      = 5760.     !  time step for the dynamics (and tracer if nn_acc=0)
-   nn_baro     =   64      !  number of barotropic time step            ("key_dynspg_ts")
-   rn_atfp     =    0.1    !  asselin time filter parameter
-   nn_acc      =    0      !  acceleration of convergence : =1      used, rdt < rdttra(k)
-                                 !                          =0, not used, rdt = rdttra
-   rn_rdtmin   = 28800.          !  minimum time step on tracers (used if nn_acc=1)
-   rn_rdtmax   = 28800.          !  maximum time step on tracers (used if nn_acc=1)
-   rn_rdth     =  800.           !  depth variation of tracer time step  (used if nn_acc=1)
-   ln_crs      = .false.      !  Logical switch for coarsening module
-   jphgr_msh   =       0               !  type of horizontal mesh
-                                       !  = 0 curvilinear coordinate on the sphere read in coordinate.nc
-                                       !  = 1 geographical mesh on the sphere with regular grid-spacing
-                                       !  = 2 f-plane with regular grid-spacing
-                                       !  = 3 beta-plane with regular grid-spacing
-                                       !  = 4 Mercator grid with T/U point at the equator
-   ppglam0     =       0.0             !  longitude of first raw and column T-point (jphgr_msh = 1)
-   ppgphi0     =     -35.0             ! latitude  of first raw and column T-point (jphgr_msh = 1)
-   ppe1_deg    =       1.0             !  zonal      grid-spacing (degrees)
-   ppe2_deg    =       0.5             !  meridional grid-spacing (degrees)
-   ppe1_m      =    5000.0             !  zonal      grid-spacing (degrees)
-   ppe2_m      =    5000.0             !  meridional grid-spacing (degrees)
-   ppsur       =    -4762.96143546300  !  ORCA r4, r2 and r05 coefficients
-   ppa0        =      255.58049070440  ! (default coefficients)
-   ppa1        =      245.58132232490  !
-   ppkth       =       21.43336197938  !
-   ppacr       =        3.0            !
-   ppdzmin     =       10.             !  Minimum vertical spacing
-   pphmax      =     5000.             !  Maximum depth
-   ldbletanh   =    .TRUE.             !  Use/do not use double tanf function for vertical coordinates
-   ppa2        =      100.760928500000 !  Double tanh function parameters
-   ppkth2      =       48.029893720000 !
-   ppacr2      =       13.000000000000 !
-/
-!-----------------------------------------------------------------------
-&namcrs        !   Grid coarsening for dynamics output and/or
-               !   passive tracer coarsened online simulations
-!-----------------------------------------------------------------------
-   nn_factx    = 3         !  Reduction factor of x-direction
-   nn_facty    = 3         !  Reduction factor of y-direction
-   nn_binref   = 0         !  Bin centering preference: NORTH or EQUAT
-                           !  0, coarse grid is binned with preferential treatment of the north fold
-                           !  1, coarse grid is binned with centering at the equator
-                           !    Symmetry with nn_facty being odd-numbered. Asymmetry with even-numbered nn_facty.
-   nn_msh_crs  = 1         !  create (=1) a mesh file or not (=0)
-   nn_crs_kz   = 0         ! 0, MEAN of volume boxes
-                           ! 1, MAX of boxes
-                           ! 2, MIN of boxes
-   ln_crs_wn   = .true.    ! wn coarsened (T) or computed using horizontal divergence ( F )
-/
-!-----------------------------------------------------------------------
-&namtsd    !   data : Temperature  & Salinity
-!-----------------------------------------------------------------------
-!-----------------------------------------------------------------------
-!          !  file name                            ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!          !                                       !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_tem  = 'data_1m_potential_temperature_nomask',         -1        ,'votemper' ,    .true.    , .true. , 'yearly'   , ''      ,   ''     ,    ''
-   sn_sal  = 'data_1m_salinity_nomask'             ,         -1        ,'vosaline' ,    .true.    , .true. , 'yearly'   , ''      ,   ''     ,    ''
-   !
-   cn_dir        = './'     !  root directory for the location of the runoff files
-   ln_tsd_init   = .true.   !  Initialisation of ocean T & S with T &S input data (T) or not (F)
-   ln_tsd_tradmp = .false.   !  damping of ocean T & S toward T &S input data (T) or not (F)
-/
-!!======================================================================
-!!            ***  Surface Boundary Condition namelists  ***
-!!======================================================================
-!!   namsbc          surface boundary condition
-!!   namsbc_ana      analytical         formulation
-!!   namsbc_flx      flux               formulation
-!!   namsbc_clio     CLIO bulk formulae formulation
-!!   namsbc_core     CORE bulk formulae formulation
-!!   namsbc_mfs      MFS  bulk formulae formulation
-!!   namsbc_cpl      CouPLed            formulation                     ("key_coupled")
-!!   namsbc_sas      StAndalone Surface module
-!!   namtra_qsr      penetrative solar radiation
-!!   namsbc_rnf      river runoffs
-!!   namsbc_apr      Atmospheric Pressure
-!!   namsbc_ssr      sea surface restoring term (for T and/or S)
-!!   namsbc_alb      albedo parameters
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namsbc        !   Surface Boundary Condition (surface module)
-!-----------------------------------------------------------------------
-   nn_fsbc     = 5         !  frequency of surface boundary condition computation
-                           !     (also = the frequency of sea-ice model call)
-   ln_ana      = .false.   !  analytical formulation                    (T => fill namsbc_ana )
-   ln_flx      = .false.   !  flux formulation                          (T => fill namsbc_flx )
-   ln_blk_clio = .false.   !  CLIO bulk formulation                     (T => fill namsbc_clio)
-   ln_blk_core = .true.    !  CORE bulk formulation                     (T => fill namsbc_core)
-   ln_blk_mfs  = .false.   !  MFS bulk formulation                      (T => fill namsbc_mfs )
-   ln_cpl      = .false.   !  Coupled formulation                       (T => fill namsbc_cpl )
-   ln_apr_dyn  = .false.   !  Patm gradient added in ocean & ice Eqs.   (T => fill namsbc_apr )
-   nn_ice      = 2         !  =0 no ice boundary condition   ,
-                           !  =1 use observed ice-cover      ,
-                           !  =2 ice-model used                         ("key_lim3" or "key_lim2)
-   nn_ice_embd = 1         !  =0 levitating ice (no mass exchange, concentration/dilution effect)
-                           !  =1 levitating ice with mass and salt exchange but no presure effect
-                           !  =2 embedded sea-ice (full salt and mass exchanges and pressure)
-   ln_dm2dc    = .false.   !  daily mean to diurnal cycle on short wave
-   ln_rnf      = .true.    !  runoffs                                   (T => fill namsbc_rnf)
-   ln_ssr      = .true.    !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
-   nn_fwb      = 2         !  FreshWater Budget: =0 unchecked
-                           !     =1 global mean of e-p-r set to zero at each time step
-                           !     =2 annual global mean of e-p-r set to zero
-   ln_wave = .false.       !  Activate coupling with wave (either Stokes Drift or Drag coefficient, or both)  (T => fill namsbc_wave)
-   ln_cdgw = .false.       !  Neutral drag coefficient read from wave model (T => fill namsbc_wave)
-   ln_sdw  = .false.       !  Computation of 3D stokes drift                (T => fill namsbc_wave)
-   cn_iceflx = 'linear'    !  redistribution of solar input into ice categories during coupling ice/atm.
-/
-!-----------------------------------------------------------------------
-&namsbc_ana    !   analytical surface boundary condition
-!-----------------------------------------------------------------------
-   nn_tau000   =   0       !  gently increase the stress over the first ntau_rst time-steps
-   rn_utau0    =   0.5     !  uniform value for the i-stress
-   rn_vtau0    =   0.e0    !  uniform value for the j-stress
-   rn_qns0     =   0.e0    !  uniform value for the total heat flux
-   rn_qsr0     =   0.e0    !  uniform value for the solar radiation
-   rn_emp0     =   0.e0    !  uniform value for the freswater budget (E-P)
-/
-!-----------------------------------------------------------------------
-&namsbc_flx    !   surface boundary condition : flux formulation
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask ! 
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_utau     = 'utau'      ,        24         , 'utau'    , .false.      , .false., 'yearly'  , ''       , ''       , ''
-   sn_vtau     = 'vtau'      ,        24         , 'vtau'    , .false.      , .false., 'yearly'  , ''       , ''       , ''
-   sn_qtot     = 'qtot'      ,        24         , 'qtot'    , .false.      , .false., 'yearly'  , ''       , ''       , ''
-   sn_qsr      = 'qsr'       ,        24         , 'qsr'     , .false.      , .false., 'yearly'  , ''       , ''       , ''
-   sn_emp      = 'emp'       ,        24         , 'emp'     , .false.      , .false., 'yearly'  , ''       , ''       , ''
-
-   cn_dir      = './'      !  root directory for the location of the flux files
-/
-!-----------------------------------------------------------------------
-&namsbc_clio   !   namsbc_clio  CLIO bulk formulae
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_utau     = 'taux_1m'   ,       -1          , 'sozotaux',   .true.     , .true. , 'yearly'  , ''       , ''       , ''
-   sn_vtau     = 'tauy_1m'   ,       -1          , 'sometauy',   .true.     , .true. , 'yearly'  , ''       , ''       , ''
-   sn_wndm     = 'flx'       ,       -1          , 'socliowi',   .true.     , .true. , 'yearly'  , ''       , ''       , ''
-   sn_tair     = 'flx'       ,       -1          , 'socliot2',   .true.     , .true. , 'yearly'  , ''       , ''       , ''
-   sn_humi     = 'flx'       ,       -1          , 'socliohu',   .true.     , .true. , 'yearly'  , ''       , ''       , ''
-   sn_ccov     = 'flx'       ,       -1          , 'socliocl',   .false.    , .true. , 'yearly'  , ''       , ''       , ''
-   sn_prec     = 'flx'       ,       -1          , 'socliopl',   .false.    , .true. , 'yearly'  , ''       , ''       , ''
-
-   cn_dir      = './'      !  root directory for the location of the bulk files are
-/
-!-----------------------------------------------------------------------
-&namsbc_core   !   namsbc_core  CORE bulk formulae
-!-----------------------------------------------------------------------
-!              !  file name                    ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights                            ! rotation ! land/sea mask !
-!              !                               !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename                           ! pairing  ! filename      !
-   sn_wndi     = 'u_10.15JUNE2009_fill'        ,         6         , 'U_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bicubic.nc'   , 'Uwnd'   , ''
-   sn_wndj     = 'v_10.15JUNE2009_fill'        ,         6         , 'V_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bicubic.nc'   , 'Vwnd'   , ''
-   sn_qsr      = 'ncar_rad.15JUNE2009_fill'    ,        24         , 'SWDN_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
-   sn_qlw      = 'ncar_rad.15JUNE2009_fill'    ,        24         , 'LWDN_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
-   sn_tair     = 't_10.15JUNE2009_fill'        ,         6         , 'T_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
-   sn_humi     = 'q_10.15JUNE2009_fill'        ,         6         , 'Q_10_MOD',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
-   sn_prec     = 'ncar_precip.15JUNE2009_fill' ,        -1         , 'PRC_MOD1',   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
-   sn_snow     = 'ncar_precip.15JUNE2009_fill' ,        -1         , 'SNOW'    ,   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
-   sn_tdif     = 'taudif_core'                 ,        24         , 'taudif'  ,   .false.    , .true. , 'yearly'  , 'weights_core2_agrif_bilinear.nc'     , ''       , ''
-
-   cn_dir      = './'      !  root directory for the location of the bulk files
-   ln_2m       = .false.   !  air temperature and humidity referenced at 2m (T) instead 10m (F)
-   ln_taudif   = .false.   !  HF tau contribution: use "mean of stress module - module of the mean stress" data
-   ln_bulk2z   = .false.   !  Air temperature/humidity and wind vectors are referenced at heights rn_zqt and rn_zu
-   rn_zqt      = 3.        !  Air temperature and humidity reference height (m) (ln_bulk2z)
-   rn_zu       = 4.        !  Wind vector reference height (m)                  (ln_bulk2z)
-   rn_pfac     = 1.        !  multiplicative factor for precipitation (total & snow)
-   rn_efac     = 1.        !  multiplicative factor for evaporation (0. or 1.)
-   rn_vfac     = 0.        !  multiplicative factor for ocean/ice velocity 
-                           !  in the calculation of the wind stress (0.=absolute winds or 1.=relative winds)
-/
-!-----------------------------------------------------------------------
-&namsbc_mfs   !   namsbc_mfs  MFS bulk formulae
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights     ! rotation ! land/sea mask !
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename    ! pairing  ! filename      !
-   sn_wndi     =   'ecmwf'   ,        6          , 'u10'     ,    .true.    , .false. , 'daily'  ,'bicubic.nc' , ''       , ''
-   sn_wndj     =   'ecmwf'   ,        6          , 'v10'     ,    .true.    , .false. , 'daily'  ,'bicubic.nc' , ''       , ''
-   sn_clc      =   'ecmwf'   ,        6          , 'clc'     ,    .true.    , .false. , 'daily'  ,'bilinear.nc', ''       , ''
-   sn_msl      =   'ecmwf'   ,        6          , 'msl'     ,    .true.    , .false. , 'daily'  ,'bicubic.nc' , ''       , ''
-   sn_tair     =   'ecmwf'   ,        6          , 't2'      ,    .true.    , .false. , 'daily'  ,'bicubic.nc' , ''       , ''
-   sn_rhm      =   'ecmwf'   ,        6          , 'rh'      ,    .true.    , .false. , 'daily'  ,'bilinear.nc', ''       , ''
-   sn_prec     =   'ecmwf'   ,        6          , 'precip'  ,    .true.    , .true.  , 'daily'  ,'bicubic.nc' , ''       , ''
-
-   cn_dir      = './ECMWF/'      !  root directory for the location of the bulk files
-/
-!-----------------------------------------------------------------------
-&namsbc_cpl    !   coupled ocean/atmosphere model                       ("key_coupled")
-!-----------------------------------------------------------------------
-!                    !     description       !  multiple  !    vector   !      vector          ! vector !
-!                    !                       ! categories !  reference  !    orientation       ! grids  !
-! send
-sn_snd_temp   =       'weighted oce and ice' ,    'no'    ,     ''      ,         ''           ,   ''
-sn_snd_alb    =       'weighted ice'         ,    'no'    ,     ''      ,         ''           ,   ''
-sn_snd_thick  =       'none'                 ,    'no'   ,     ''      ,         ''           ,   ''
-sn_snd_crt    =       'none'                 ,    'no'    , 'spherical' , 'eastward-northward' ,  'T'
-sn_snd_co2    =       'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
-! receive
-sn_rcv_w10m   =       'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_taumod =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_tau    =       'oce only'             ,    'no'    , 'cartesian' , 'eastward-northward',  'U,V'
-sn_rcv_dqnsdt =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_qsr    =       'oce and ice'          ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_qns    =       'oce and ice'          ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_emp    =       'conservative'         ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_rnf    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_cal    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_co2    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-/
-!-----------------------------------------------------------------------
-&namsbc_sas    !   analytical surface boundary condition
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_usp      = 'sas_grid_U' ,    120           , 'vozocrtx' ,  .true.    , .true. ,   'yearly'  , ''       , ''             , ''      
-   sn_vsp      = 'sas_grid_V' ,    120           , 'vomecrty' ,  .true.    , .true. ,   'yearly'  , ''       , ''             , ''
-   sn_tem      = 'sas_grid_T' ,    120           , 'sosstsst' ,  .true.    , .true. ,   'yearly'  , ''       , ''             , ''
-   sn_sal      = 'sas_grid_T' ,    120           , 'sosaline' ,  .true.    , .true. ,   'yearly'  , ''       , ''             , ''
-   sn_ssh      = 'sas_grid_T' ,    120           , 'sossheig' ,  .true.    , .true. ,   'yearly'  , ''       , ''             , ''
-
-   ln_3d_uv    = .true.    !  specify whether we are supplying a 3D u,v field
-   cn_dir      = './'      !  root directory for the location of the bulk files are
-/
-!-----------------------------------------------------------------------
-&namtra_qsr    !   penetrative solar radiation
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights          ! rotation ! land/sea mask !
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename         ! pairing  ! filename      !
-   sn_chl      ='chlorophyll',        -1         , 'CHLA'    ,   .true.     , .true. , 'yearly'  , 'weights_bilin'  , ''       , ''
-
-   cn_dir      = './'      !  root directory for the location of the runoff files
-   ln_traqsr   = .true.    !  Light penetration (T) or not (F)
-   ln_qsr_rgb  = .true.    !  RGB (Red-Green-Blue) light penetration
-   ln_qsr_2bd  = .false.   !  2 bands              light penetration
-   ln_qsr_bio  = .false.   !  bio-model light penetration
-   nn_chldta   =      1    !  RGB : Chl data (=1) or cst value (=0)
-   rn_abs      =   0.58    !  RGB & 2 bands: fraction of light (rn_si1)
-   rn_si0      =   0.35    !  RGB & 2 bands: shortess depth of extinction
-   rn_si1      =   23.0    !  2 bands: longest depth of extinction
-   ln_qsr_ice  = .true.    !  light penetration for ice-model LIM3
-/
-!-----------------------------------------------------------------------
-&namsbc_rnf    !   runoffs namelist surface boundary condition
-!-----------------------------------------------------------------------
-!              !  file name           ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !                      !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_rnf      = 'runoff_core_monthly',        -1         , 'sorunoff',   .true.     , .true. , 'yearly'  , ''       , ''       , ''
-   sn_cnf      = 'runoff_core_monthly',         0         , 'socoefr0',   .false.    , .true. , 'yearly'  , ''       , ''       , ''
-   sn_s_rnf    = 'runoffs'            ,        24         , 'rosaline',   .true.     , .true. , 'yearly'  , ''       , ''       , ''
-   sn_t_rnf    = 'runoffs'            ,        24         , 'rotemper',   .true.     , .true. , 'yearly'  , ''       , ''       , ''
-   sn_dep_rnf  = 'runoffs'            ,         0         , 'rodepth' ,   .false.    , .true. , 'yearly'  , ''       , ''       , ''
-
-   cn_dir       = './'      !  root directory for the location of the runoff files
-   ln_rnf_emp   = .false.   !  runoffs included into precipitation field (T) or into a file (F)
-   ln_rnf_mouth = .true.    !  specific treatment at rivers mouths
-   rn_hrnf      =  15.e0    !  depth over which enhanced vertical mixing is used
-   rn_avt_rnf   =   1.e-3   !  value of the additional vertical mixing coef. [m2/s]
-   rn_rfact     =   1.e0    !  multiplicative factor for runoff
-   ln_rnf_depth = .false.   !  read in depth information for runoff
-   ln_rnf_tem   = .false.   !  read in temperature information for runoff
-   ln_rnf_sal   = .false.   !  read in salinity information for runoff
-/
-!-----------------------------------------------------------------------
-&namsbc_apr    !   Atmospheric pressure used as ocean forcing or in bulk
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_apr      = 'patm'      ,         -1        ,'somslpre',    .true.     , .true. , 'yearly'  ,  ''      ,   ''     , ''
-
-   cn_dir      = './'       !  root directory for the location of the bulk files
-   rn_pref     = 101000._wp !  reference atmospheric pressure   [N/m2]/
-   ln_ref_apr  = .false.    !  ref. pressure: global mean Patm (T) or a constant (F)
-   ln_apr_obc  = .false.    !  inverse barometer added to OBC ssh data
-/
-!-----------------------------------------------------------------------
-&namsbc_ssr    !   surface boundary condition : sea surface restoring
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_sst      = 'sst_data'  ,        24         ,  'sst'    ,    .false.   , .false., 'yearly'  , ''       , ''       , ''
-   sn_sss      = 'sss_data'  ,        -1         ,  'sss'    ,    .true.    , .true. , 'yearly'  , ''       , ''       , ''
-
-   cn_dir      = './'      !  root directory for the location of the runoff files
-   nn_sstr     =     0     !  add a retroaction term in the surface heat       flux (=1) or not (=0)
-   nn_sssr     =     2     !  add a damping     term in the surface freshwater flux (=2)
-                           !  or to SSS only (=1) or no damping term (=0)
-   rn_dqdt     =   -40.    !  magnitude of the retroaction on temperature   [W/m2/K]
-   rn_deds     =  -166.67  !  magnitude of the damping on salinity   [mm/day]
-   ln_sssr_bnd =   .true.  !  flag to bound erp term (associated with nn_sssr=2)
-   rn_sssr_bnd =   4.e0    !  ABS(Max/Min) value of the damping erp term [mm/day]
-/
-!-----------------------------------------------------------------------
-&namsbc_alb    !   albedo parameters
-!-----------------------------------------------------------------------
-   rn_cloud    =    0.06   !  cloud correction to snow and ice albedo
-   rn_albice   =    0.53   !  albedo of melting ice in the arctic and antarctic
-   rn_alphd    =    0.80   !  coefficients for linear interpolation used to
-   rn_alphc    =    0.65   !  compute albedo between two extremes values
-   rn_alphdi   =    0.72   !  (Pyane, 1972)
-/
-!-----------------------------------------------------------------------
-&namberg       !   iceberg parameters
-!-----------------------------------------------------------------------
-      ln_icebergs              = .false.
-      ln_bergdia               = .true.               ! Calculate budgets
-      nn_verbose_level         = 1                    ! Turn on more verbose output if level > 0
-      nn_verbose_write         = 15                   ! Timesteps between verbose messages
-      nn_sample_rate           = 1                    ! Timesteps between sampling for trajectory storage
-                                                      ! Initial mass required for an iceberg of each class
-      rn_initial_mass          = 8.8e7, 4.1e8, 3.3e9, 1.8e10, 3.8e10, 7.5e10, 1.2e11, 2.2e11, 3.9e11, 7.4e11
-                                                      ! Proportion of calving mass to apportion to each class  
-      rn_distribution          = 0.24, 0.12, 0.15, 0.18, 0.12, 0.07, 0.03, 0.03, 0.03, 0.02
-                                                      ! Ratio between effective and real iceberg mass (non-dim)
-                                                      ! i.e. number of icebergs represented at a point         
-      rn_mass_scaling          = 2000, 200, 50, 20, 10, 5, 2, 1, 1, 1
-                                                      ! thickness of newly calved bergs (m)
-      rn_initial_thickness     = 40., 67., 133., 175., 250., 250., 250., 250., 250., 250.
-      rn_rho_bergs             = 850.                 ! Density of icebergs
-      rn_LoW_ratio             = 1.5                  ! Initial ratio L/W for newly calved icebergs
-      ln_operator_splitting    = .true.               ! Use first order operator splitting for thermodynamics
-      rn_bits_erosion_fraction = 0.                   ! Fraction of erosion melt flux to divert to bergy bits
-      rn_sicn_shift            = 0.                   ! Shift of sea-ice concn in erosion flux (0<sicn_shift<1)
-      ln_passive_mode          = .false.              ! iceberg - ocean decoupling   
-      nn_test_icebergs         =  10                  ! Create test icebergs of this class (-1 = no)
-                                                      ! Put a test iceberg at each gridpoint in box (lon1,lon2,lat1,lat2)
-      rn_test_box              = 108.0,  116.0, -66.0, -58.0
-      rn_speed_limit           = 0.                   ! CFL speed limit for a berg   
-
-!              ! file name ! frequency (hours) !   variable   ! time interp.   !  clim   ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !           !  (if <0  months)  !     name     !   (logical)    !  (T/F ) ! 'monthly' ! filename ! pairing  ! filename      !
-      sn_icb =  'calving' ,       -1           , 'calvingmask',  .true.        , .true.  , 'yearly'  , ''       , ''       , ''
-   
-      cn_dir = './' 
-/
-
-!!======================================================================
-!!               ***  Lateral boundary condition  ***
-!!======================================================================
-!!   namlbc        lateral momentum boundary condition
-!!   namcla        cross land advection
-!!   namobc        open boundaries parameters                           ("key_obc")
-!!   namagrif      agrif nested grid ( read by child model only )       ("key_agrif")
-!!   nambdy        Unstructured open boundaries                         ("key_bdy")
-!!   namtide       Tidal forcing at open boundaries                     ("key_bdy_tides")
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namlbc        !   lateral momentum boundary condition
-!-----------------------------------------------------------------------
-   rn_shlat    =    2.     !  shlat = 0  !  0 < shlat < 2  !  shlat = 2  !  2 < shlat
-                           !  free slip  !   partial slip  !   no slip   ! strong slip
-   ln_vorlat   = .false.   !  consistency of vorticity boundary condition with analytical eqs.
-/
-!-----------------------------------------------------------------------
-&namcla        !   cross land advection
-!-----------------------------------------------------------------------
-   nn_cla      =    0      !  advection between 2 ocean pts separates by land
-/
-!-----------------------------------------------------------------------
-&namobc        !   open boundaries parameters                           ("key_obc")
-!-----------------------------------------------------------------------
-   ln_obc_clim = .false.   !  climatological obc data files (T) or not (F)
-   ln_vol_cst  = .true.    !  impose the total volume conservation (T) or not (F)
-   ln_obc_fla  = .false.   !  Flather open boundary condition
-   nn_obcdta   =    1      !  = 0 the obc data are equal to the initial state
-                           !  = 1 the obc data are read in 'obc.dta' files
-   cn_obcdta   = 'annual'  !  set to annual if obc datafile hold 1 year of data
-                           !  set to monthly if obc datafile hold 1 month of data
-   rn_dpein    =    1.     !  damping time scale for inflow at east  open boundary
-   rn_dpwin    =    1.     !     -           -         -       west    -      -
-   rn_dpnin    =    1.     !     -           -         -       north   -      -
-   rn_dpsin    =    1.     !     -           -         -       south   -      -
-   rn_dpeob    = 3000.     !  time relaxation (days) for the east  open boundary
-   rn_dpwob    =   15.     !     -           -         -     west    -      -
-   rn_dpnob    = 3000.     !     -           -         -     north   -      -
-   rn_dpsob    =   15.     !     -           -         -     south   -      -
-   rn_volemp   =    1.     !  = 0 the total volume change with the surface flux (E-P-R)
-                           !  = 1 the total volume remains constant
-/
-!-----------------------------------------------------------------------
-&namagrif      !  AGRIF zoom                                            ("key_agrif")
-!-----------------------------------------------------------------------
-   nn_cln_update =    3    !  baroclinic update frequency
-   ln_spc_dyn    = .true.  !  use 0 as special value for dynamics
-   rn_sponge_tra = 2880.   !  coefficient for tracer   sponge layer [m2/s]
-   rn_sponge_dyn = 2880.   !  coefficient for dynamics sponge layer [m2/s]
-/
-!-----------------------------------------------------------------------
-&nam_tide      !   tide parameters (#ifdef key_tide)
-!-----------------------------------------------------------------------
-   ln_tide_pot   = .true.   !  use tidal potential forcing
-   ln_tide_ramp  = .false.  !
-   rdttideramp   =    0.    !
-   clname(1)     =   'M2'   !  name of constituent
-   clname(2)     =   'S2'
-   clname(3)     =   'N2'
-   clname(4)     =   'K1'
-   clname(5)     =   'O1'
-   clname(6)     =   'Q1'
-   clname(7)     =   'M4'
-   clname(8)     =   'K2'
-   clname(9)     =   'P1'
-   clname(10)    =   'Mf'
-   clname(11)    =   'Mm'
-/
-!-----------------------------------------------------------------------
-&nambdy        !  unstructured open boundaries                          ("key_bdy")
-!-----------------------------------------------------------------------
-    nb_bdy         = 0                    !  number of open boundary sets
-    ln_coords_file = .true.               !  =T : read bdy coordinates from file
-    cn_coords_file = 'coordinates.bdy.nc' !  bdy coordinates files
-    ln_mask_file   = .false.              !  =T : read mask from file
-    cn_mask_file   = ''                   !  name of mask file (if ln_mask_file=.TRUE.)
-    cn_dyn2d       = 'none'               !
-    nn_dyn2d_dta   =  0                   !  = 0, bdy data are equal to the initial state
-                                          !  = 1, bdy data are read in 'bdydata   .nc' files
-                                          !  = 2, use tidal harmonic forcing data from files
-                                          !  = 3, use external data AND tidal harmonic forcing
-    cn_dyn3d      =  'none'               !  
-    nn_dyn3d_dta  =  0                    !  = 0, bdy data are equal to the initial state
-                                          !  = 1, bdy data are read in 'bdydata   .nc' files
-    cn_tra        =  'none'               ! 
-    nn_tra_dta    =  0                    !  = 0, bdy data are equal to the initial state
-                                          !  = 1, bdy data are read in 'bdydata   .nc' files
-    ln_tra_dmp    =.false.                !  open boudaries conditions for tracers
-    ln_dyn3d_dmp  =.false.                !  open boundary condition for baroclinic velocities
-    rn_time_dmp   =  1.                   ! Damping time scale in days 
-    rn_time_dmp_out =  1.                 ! Outflow damping time scale
-    nn_rimwidth   = 10                    !  width of the relaxation zone
-    ln_vol        = .false.               !  total volume correction (see nn_volctl parameter)
-    nn_volctl     = 1                     !  = 0, the total water flux across open boundaries is zero
-/
-!-----------------------------------------------------------------------
-&nambdy_dta      !  open boundaries - external data           ("key_bdy")
-!-----------------------------------------------------------------------
-!              !  file name      ! frequency (hours) ! variable   ! time interp.   !  clim   ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !                 !  (if <0  months)  !   name     !   (logical)    !  (T/F ) ! 'monthly' ! filename ! pairing  ! filename      !
-   bn_ssh =     'amm12_bdyT_u2d' ,         24        , 'sossheig' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
-   bn_u2d =     'amm12_bdyU_u2d' ,         24        , 'vobtcrtx' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
-   bn_v2d =     'amm12_bdyV_u2d' ,         24        , 'vobtcrty' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
-   bn_u3d  =    'amm12_bdyU_u3d' ,         24        , 'vozocrtx' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
-   bn_v3d  =    'amm12_bdyV_u3d' ,         24        , 'vomecrty' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
-   bn_tem  =    'amm12_bdyT_tra' ,         24        , 'votemper' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
-   bn_sal  =    'amm12_bdyT_tra' ,         24        , 'vosaline' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
-   cn_dir  =    'bdydta/'
-   ln_full_vel = .false.
-/
-!-----------------------------------------------------------------------
-&nambdy_tide     ! tidal forcing at open boundaries
-!-----------------------------------------------------------------------
-   filtide          = 'bdydta/amm12_bdytide_'         !  file name root of tidal forcing files
-   ln_bdytide_2ddta = .false.
-   ln_bdytide_conj  = .false.
-/
-!!======================================================================
-!!                 ***  Bottom boundary condition  ***
-!!======================================================================
-!!   nambfr        bottom friction
-!!   nambbc        bottom temperature boundary condition
-!!   nambbl        bottom boundary layer scheme                         ("key_trabbl")
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&nambfr        !   bottom friction
-!-----------------------------------------------------------------------
-   nn_bfr      =    1      !  type of bottom friction :   = 0 : free slip,  = 1 : linear friction
-                           !                              = 2 : nonlinear friction
-   rn_bfri1    =    4.e-4  !  bottom drag coefficient (linear case)
-   rn_bfri2    =    1.e-3  !  bottom drag coefficient (non linear case)
-   rn_bfeb2    =    2.5e-3 !  bottom turbulent kinetic energy background  (m2/s2)
-   rn_bfrz0    =    3.e-3  ! bottom roughness for loglayer bfr coeff 
-   ln_bfr2d    = .false.   !  horizontal variation of the bottom friction coef (read a 2D mask file )
-   rn_bfrien   =    50.    !  local multiplying factor of bfr (ln_bfr2d=T)
-   ln_bfrimp   = .true.    !  implicit bottom friction (requires ln_zdfexp = .false. if true)
-/
-!-----------------------------------------------------------------------
-&nambbc        !   bottom temperature boundary condition
-!-----------------------------------------------------------------------
-   ln_trabbc   = .true.    !  Apply a geothermal heating at the ocean bottom
-   nn_geoflx   =    2      !  geothermal heat flux: = 0 no flux
-                           !     = 1 constant flux
-                           !     = 2 variable flux (read in geothermal_heating.nc in mW/m2)
-   rn_geoflx_cst = 86.4e-3 !  Constant value of geothermal heat flux [W/m2]
-/
-!-----------------------------------------------------------------------
-&nambbl        !   bottom boundary layer scheme
-!-----------------------------------------------------------------------
-   nn_bbl_ldf  =  1      !  diffusive bbl (=1)   or not (=0)
-   nn_bbl_adv  =  0      !  advective bbl (=1/2) or not (=0)
-   rn_ahtbbl   =  1000.  !  lateral mixing coefficient in the bbl  [m2/s]
-   rn_gambbl   =  10.    !  advective bbl coefficient                 [s]
-/
-
-!!======================================================================
-!!                        Tracer (T & S ) namelists
-!!======================================================================
-!!   nameos        equation of state
-!!   namtra_adv    advection scheme
-!!   namtra_ldf    lateral diffusion scheme
-!!   namtra_dmp    T & S newtonian damping
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&nameos        !   ocean physical parameters
-!-----------------------------------------------------------------------
-   nn_eos      =   0       !  type of equation of state and Brunt-Vaisala frequency
-                           !     = 0, UNESCO (formulation of Jackett and McDougall (1994) and of McDougall (1987) )
-                           !     = 1, linear: rho(T)   = rau0 * ( 1.028 - ralpha * T )
-                           !     = 2, linear: rho(T,S) = rau0 * ( rbeta * S - ralpha * T )
-   rn_alpha    =   2.0e-4  !  thermal expension coefficient (nn_eos= 1 or 2)
-   rn_beta     =   7.7e-4  !  saline  expension coefficient (nn_eos= 2)
-/
-!-----------------------------------------------------------------------
-&namtra_adv    !   advection scheme for tracer
-!-----------------------------------------------------------------------
-   ln_traadv_cen2   =  .false.  !  2nd order centered scheme
-   ln_traadv_tvd    =  .true.   !  TVD scheme
-   ln_traadv_muscl  =  .false.  !  MUSCL scheme
-   ln_traadv_muscl2 =  .false.  !  MUSCL2 scheme + cen2 at boundaries
-   ln_traadv_ubs    =  .false.  !  UBS scheme
-   ln_traadv_qck    =  .false.  !  QUICKEST scheme
-   ln_traadv_msc_ups=  .false.  !  use upstream scheme within muscl
-/
-!-----------------------------------------------------------------------
-&namtra_adv_mle !   mixed layer eddy parametrisation (Fox-Kemper param)
-!-----------------------------------------------------------------------
-   ln_mle    = .true.      ! (T) use the Mixed Layer Eddy (MLE) parameterisation
-   rn_ce     = 0.06        ! magnitude of the MLE (typical value: 0.06 to 0.08)
-   nn_mle    = 1           ! MLE type: =0 standard Fox-Kemper ; =1 new formulation
-   rn_lf     = 5.e+3       ! typical scale of mixed layer front (meters)                      (case rn_mle=0)
-   rn_time   = 172800.     ! time scale for mixing momentum across the mixed layer (seconds)  (case rn_mle=0)
-   rn_lat    = 20.         ! reference latitude (degrees) of MLE coef.                        (case rn_mle=1)
-   nn_mld_uv = 0           ! space interpolation of MLD at u- & v-pts (0=min,1=averaged,2=max)
-   nn_conv   = 0           ! =1 no MLE in case of convection ; =0 always MLE
-   rn_rho_c_mle  = 0.01    ! delta rho criterion used to calculate MLD for FK
-/
-!----------------------------------------------------------------------------------
-&namtra_ldf    !   lateral diffusion scheme for tracers
-!----------------------------------------------------------------------------------
-   !                       !  Operator type:
-   ln_traldf_lap    =  .true.   !  laplacian operator
-   ln_traldf_bilap  =  .false.  !  bilaplacian operator
-   !                       !  Direction of action:
-   ln_traldf_level  =  .false.  !  iso-level
-   ln_traldf_hor    =  .false.  !  horizontal (geopotential)   (needs "key_ldfslp" when ln_sco=T)
-   ln_traldf_iso    =  .true.   !  iso-neutral                 (needs "key_ldfslp")
-   !		       	   !  Griffies parameters              (all need "key_ldfslp")
-   ln_traldf_grif   =  .false.  !  use griffies triads
-   ln_traldf_gdia   =  .false.  !  output griffies eddy velocities
-   ln_triad_iso     =  .false.  !  pure lateral mixing in ML
-   ln_botmix_grif   =  .false.  !  lateral mixing on bottom
-   !                       !  Coefficients
-   ! Eddy-induced (GM) advection always used with Griffies; otherwise needs "key_traldf_eiv"
-   ! Value rn_aeiv_0 is ignored unless = 0 with Held-Larichev spatially varying aeiv
-   !                                  (key_traldf_c2d & key_traldf_eiv & key_orca_r2, _r1 or _r05)
-   rn_aeiv_0        =  2000.    !  eddy induced velocity coefficient [m2/s]
-   rn_aht_0         =  2000.    !  horizontal eddy diffusivity for tracers [m2/s]
-   rn_ahtb_0        =     0.    !  background eddy diffusivity for ldf_iso [m2/s]
-   !                                           (normally=0; not used with Griffies)
-   rn_slpmax        =     0.01  !  slope limit
-   rn_chsmag        =     1.    !  multiplicative factor in Smagorinsky diffusivity
-   rn_smsh          =     1.    !  Smagorinsky diffusivity: = 0 - use only sheer
-   rn_aht_m         =  2000.    !  upper limit or stability criteria for lateral eddy diffusivity (m2/s)
-/
-!-----------------------------------------------------------------------
-&namtra_dmp    !   tracer: T & S newtonian damping
-!-----------------------------------------------------------------------
-   ln_tradmp   =  .false.   !  add a damping termn (T) or not (F)
-   nn_hdmp     =   -1      !  horizontal shape =-1, damping in Med and Red Seas only
-                           !                   =XX, damping poleward of XX degrees (XX>0)
-                           !                      + F(distance-to-coast) + Red and Med Seas
-   nn_zdmp     =    0      !  vertical   shape =0    damping throughout the water column
-                           !                   =1 no damping in the mixing layer (kz  criteria)
-                           !                   =2 no damping in the mixed  layer (rho crieria)
-   rn_surf     =   50.     !  surface time scale of damping   [days]
-   rn_bot      =  360.     !  bottom  time scale of damping   [days]
-   rn_dep      =  800.     !  depth of transition between rn_surf and rn_bot [meters]
-   nn_file     =    0      !  create a damping.coeff NetCDF file (=1) or not (=0)
-/
-
-!!======================================================================
-!!                      ***  Dynamics namelists  ***
-!!======================================================================
-!!   namdyn_adv    formulation of the momentum advection
-!!   namdyn_vor    advection scheme
-!!   namdyn_hpg    hydrostatic pressure gradient
-!!   namdyn_spg    surface pressure gradient                            (CPP key only)
-!!   namdyn_ldf    lateral diffusion scheme
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namdyn_adv    !   formulation of the momentum advection
-!-----------------------------------------------------------------------
-   ln_dynadv_vec = .true.  !  vector form (T) or flux form (F)
-   ln_dynadv_cen2= .false. !  flux form - 2nd order centered scheme
-   ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
-/
-!-----------------------------------------------------------------------
-&nam_vvl    !   vertical coordinate options
-!-----------------------------------------------------------------------
-   ln_vvl_zstar  = .true.           !  zstar vertical coordinate                   
-   ln_vvl_ztilde = .false.          !  ztilde vertical coordinate: only high frequency variations
-   ln_vvl_layer  = .false.          !  full layer vertical coordinate
-   ln_vvl_ztilde_as_zstar = .false. !  ztilde vertical coordinate emulating zstar
-   rn_ahe3       = 0.0e0            !  thickness diffusion coefficient
-   rn_rst_e3t    = 30.e0            !  ztilde to zstar restoration timescale [days]
-   rn_lf_cutoff  = 5.0e0            !  cutoff frequency for low-pass filter  [days]
-   rn_zdef_max   = 0.9e0            !  maximum fractional e3t deformation
-   ln_vvl_dbg    = .true.           !  debug prints    (T/F)
-/
-!-----------------------------------------------------------------------
-&namdyn_vor    !   option of physics/algorithm (not control by CPP keys)
-!-----------------------------------------------------------------------
-   ln_dynvor_ene = .false. !  enstrophy conserving scheme
-   ln_dynvor_ens = .false. !  energy conserving scheme
-   ln_dynvor_mix = .false. !  mixed scheme
-   ln_dynvor_een = .true.  !  energy & enstrophy scheme
-/
-!-----------------------------------------------------------------------
-&namdyn_hpg    !   Hydrostatic pressure gradient option
-!-----------------------------------------------------------------------
-   ln_hpg_zco  = .false.   !  z-coordinate - full steps
-   ln_hpg_zps  = .true.    !  z-coordinate - partial steps (interpolation)
-   ln_hpg_sco  = .false.   !  s-coordinate (standard jacobian formulation)
-   ln_hpg_djc  = .false.   !  s-coordinate (Density Jacobian with Cubic polynomial)
-   ln_hpg_prj  = .false.   !  s-coordinate (Pressure Jacobian scheme)
-   ln_dynhpg_imp = .false. !  time stepping: semi-implicit time scheme  (T)
-                                 !           centered      time scheme  (F)
-/
-!-----------------------------------------------------------------------
-!namdyn_spg    !   surface pressure gradient   (CPP key only)
-!-----------------------------------------------------------------------
-!                          !  explicit free surface                     ("key_dynspg_exp")
-!                          !  filtered free surface                     ("key_dynspg_flt")
-!                          !  split-explicit free surface               ("key_dynspg_ts")
-
-!-----------------------------------------------------------------------
-&namdyn_ldf    !   lateral diffusion on momentum
-!-----------------------------------------------------------------------
-   !                       !  Type of the operator :
-   ln_dynldf_lap    =  .true.   !  laplacian operator
-   ln_dynldf_bilap  =  .false.  !  bilaplacian operator
-   !                       !  Direction of action  :
-   ln_dynldf_level  =  .false.  !  iso-level
-   ln_dynldf_hor    =  .true.   !  horizontal (geopotential)            (require "key_ldfslp" in s-coord.)
-   ln_dynldf_iso    =  .false.  !  iso-neutral                          (require "key_ldfslp")
-   !                       !  Coefficient
-   rn_ahm_0_lap     = 40000.    !  horizontal laplacian eddy viscosity   [m2/s]
-   rn_ahmb_0        =     0.    !  background eddy viscosity for ldf_iso [m2/s]
-   rn_ahm_0_blp     =     0.    !  horizontal bilaplacian eddy viscosity [m4/s]
-   rn_cmsmag_1      =     3.    !  constant in laplacian Smagorinsky viscosity
-   rn_cmsmag_2      =     3     !  constant in bilaplacian Smagorinsky viscosity
-   rn_cmsh          =     1.    !  1 or 0 , if 0 -use only shear for Smagorinsky viscosity
-   rn_ahm_m_blp     =    -1.e12 !  upper limit for bilap  abs(ahm) < min( dx^4/128rdt, rn_ahm_m_blp)
-   rn_ahm_m_lap     = 40000.    !  upper limit for lap  ahm < min(dx^2/16rdt, rn_ahm_m_lap)
-/
-
-!!======================================================================
-!!             Tracers & Dynamics vertical physics namelists
-!!======================================================================
-!!    namzdf        vertical physics
-!!    namzdf_ric    richardson number dependent vertical mixing         ("key_zdfric")
-!!    namzdf_tke    TKE dependent vertical mixing                       ("key_zdftke")
-!!    namzdf_kpp    KPP dependent vertical mixing                       ("key_zdfkpp")
-!!    namzdf_ddm    double diffusive mixing parameterization            ("key_zdfddm")
-!!    namzdf_tmx    tidal mixing parameterization                       ("key_zdftmx")
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namzdf        !   vertical physics
-!-----------------------------------------------------------------------
-   rn_avm0     =   1.2e-4  !  vertical eddy viscosity   [m2/s]          (background Kz if not "key_zdfcst")
-   rn_avt0     =   1.2e-5  !  vertical eddy diffusivity [m2/s]          (background Kz if not "key_zdfcst")
-   nn_avb      =    0      !  profile for background avt & avm (=1) or not (=0)
-   nn_havtb    =    0      !  horizontal shape for avtb (=1) or not (=0)
-   ln_zdfevd   = .true.    !  enhanced vertical diffusion (evd) (T) or not (F)
-   nn_evdm     =    0      !  evd apply on tracer (=0) or on tracer and momentum (=1)
-   rn_avevd    =  100.     !  evd mixing coefficient [m2/s]
-   ln_zdfnpc   = .false.   !  Non-Penetrative Convective algorithm (T) or not (F)
-   nn_npc      =    1            !  frequency of application of npc
-   nn_npcp     =  365            !  npc control print frequency
-   ln_zdfexp   = .false.   !  time-stepping: split-explicit (T) or implicit (F) time stepping
-   nn_zdfexp   =    3            !  number of sub-timestep for ln_zdfexp=T
-/
-!-----------------------------------------------------------------------
-&namzdf_ric    !   richardson number dependent vertical diffusion       ("key_zdfric" )
-!-----------------------------------------------------------------------
-   rn_avmri    = 100.e-4   !  maximum value of the vertical viscosity
-   rn_alp      =   5.      !  coefficient of the parameterization
-   nn_ric      =   2       !  coefficient of the parameterization
-   rn_ekmfc    =   0.7     !  Factor in the Ekman depth Equation
-   rn_mldmin   =   1.0     !  minimum allowable mixed-layer depth estimate (m)
-   rn_mldmax   =1000.0     !  maximum allowable mixed-layer depth estimate (m)
-   rn_wtmix    =  10.0     !  vertical eddy viscosity coeff [m2/s] in the mixed-layer
-   rn_wvmix    =  10.0     !  vertical eddy diffusion coeff [m2/s] in the mixed-layer
-   ln_mldw     = .true.    !  Flag to use or not the mized layer depth param.
-/
-!-----------------------------------------------------------------------
-&namzdf_tke    !   turbulent eddy kinetic dependent vertical diffusion  ("key_zdftke")
-!-----------------------------------------------------------------------
-   rn_ediff    =   0.1     !  coef. for vertical eddy coef. (avt=rn_ediff*mxl*sqrt(e) )
-   rn_ediss    =   0.7     !  coef. of the Kolmogoroff dissipation
-   rn_ebb      =  67.83    !  coef. of the surface input of tke (=67.83 suggested when ln_mxl0=T)
-   rn_emin     =   1.e-6   !  minimum value of tke [m2/s2]
-   rn_emin0    =   1.e-4   !  surface minimum value of tke [m2/s2]
-   rn_bshear   =   1.e-20  ! background shear (>0) currently a numerical threshold (do not change it)
-   nn_mxl      =   2       !  mixing length: = 0 bounded by the distance to surface and bottom
-                           !                 = 1 bounded by the local vertical scale factor
-                           !                 = 2 first vertical derivative of mixing length bounded by 1
-                           !                 = 3 as =2 with distinct disspipative an mixing length scale
-   nn_pdl      =   1       !  Prandtl number function of richarson number (=1, avt=pdl(Ri)*avm) or not (=0, avt=avm)
-   ln_mxl0     = .true.    !  surface mixing length scale = F(wind stress) (T) or not (F)
-   rn_mxl0     =   0.04    !  surface  buoyancy lenght scale minimum value
-   ln_lc       = .true.    !  Langmuir cell parameterisation (Axell 2002)
-   rn_lc       =   0.15    !  coef. associated to Langmuir cells
-   nn_etau     =   1       !  penetration of tke below the mixed layer (ML) due to internal & intertial waves
-                           !        = 0 no penetration
-                           !        = 1 add a tke source below the ML
-                           !        = 2 add a tke source just at the base of the ML
-                           !        = 3 as = 1 applied on HF part of the stress    ("key_coupled")
-   rn_efr      =   0.05    !  fraction of surface tke value which penetrates below the ML (nn_etau=1 or 2)
-   nn_htau     =   1       !  type of exponential decrease of tke penetration below the ML
-                           !        = 0  constant 10 m length scale
-                           !        = 1  0.5m at the equator to 30m poleward of 40 degrees
-/
-!------------------------------------------------------------------------
-&namzdf_kpp    !   K-Profile Parameterization dependent vertical mixing  ("key_zdfkpp", and optionally:
-!------------------------------------------------------------------------ "key_kppcustom" or "key_kpplktb")
-   ln_kpprimix = .true.    !  shear instability mixing
-   rn_difmiw   =  1.0e-04  !  constant internal wave viscosity [m2/s]
-   rn_difsiw   =  0.1e-04  !  constant internal wave diffusivity [m2/s]
-   rn_riinfty  =  0.8      !  local Richardson Number limit for shear instability
-   rn_difri    =  0.0050   !  maximum shear mixing at Rig = 0    [m2/s]
-   rn_bvsqcon  = -0.01e-07 !  Brunt-Vaisala squared for maximum convection [1/s2]
-   rn_difcon   =  1.       !  maximum mixing in interior convection [m2/s]
-   nn_avb      =  0        !  horizontal averaged (=1) or not (=0) on avt and amv
-   nn_ave      =  1        !  constant (=0) or profile (=1) background on avt
-/
-!-----------------------------------------------------------------------
-&namzdf_gls                !   GLS vertical diffusion                   ("key_zdfgls")
-!-----------------------------------------------------------------------
-   rn_emin       = 1.e-6   !  minimum value of e   [m2/s2]
-   rn_epsmin     = 1.e-12  !  minimum value of eps [m2/s3]
-   ln_length_lim = .true.  !  limit on the dissipation rate under stable stratification (Galperin et al., 1988)
-   rn_clim_galp  = 0.53    !  galperin limit
-   ln_crban      = .true.  !  Use Craig & Banner (1994) surface wave mixing parametrisation
-   ln_sigpsi     = .true.  !  Activate or not Burchard 2001 mods on psi schmidt number in the wb case
-   rn_crban      = 100.    !  Craig and Banner 1994 constant for wb tke flux
-   rn_charn      = 70000.  !  Charnock constant for wb induced roughness length
-   nn_tkebc_surf =   1     !  surface tke condition (0/1/2=Dir/Neum/Dir Mellor-Blumberg)
-   nn_tkebc_bot  =   1     !  bottom tke condition (0/1=Dir/Neum)
-   nn_psibc_surf =   1     !  surface psi condition (0/1/2=Dir/Neum/Dir Mellor-Blumberg)
-   nn_psibc_bot  =   1     !  bottom psi condition (0/1=Dir/Neum)
-   nn_stab_func  =   2     !  stability function (0=Galp, 1= KC94, 2=CanutoA, 3=CanutoB)
-   nn_clos       =   1     !  predefined closure type (0=MY82, 1=k-eps, 2=k-w, 3=Gen)
-/
-!-----------------------------------------------------------------------
-&namzdf_ddm    !   double diffusive mixing parameterization             ("key_zdfddm")
-!-----------------------------------------------------------------------
-   rn_avts     = 1.e-4     !  maximum avs (vertical mixing on salinity)
-   rn_hsbfr    = 1.6       !  heat/salt buoyancy flux ratio
-/
-!-----------------------------------------------------------------------
-&namzdf_tmx    !   tidal mixing parameterization                        ("key_zdftmx")
-!-----------------------------------------------------------------------
-   rn_htmx     = 500.      !  vertical decay scale for turbulence (meters)
-   rn_n2min    = 1.e-8     !  threshold of the Brunt-Vaisala frequency (s-1)
-   rn_tfe      = 0.333     !  tidal dissipation efficiency
-   rn_me       = 0.2       !  mixing efficiency
-   ln_tmx_itf  = .true.    !  ITF specific parameterisation
-   rn_tfe_itf  = 1.        !  ITF tidal dissipation efficiency
-/
-
-!!======================================================================
-!!                  ***  Miscellaneous namelists  ***
-!!======================================================================
-!!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi)
-!!   namctl            Control prints & Benchmark
-!!   namsol            elliptic solver / island / free surface
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namsol        !   elliptic solver / island / free surface
-!-----------------------------------------------------------------------
-   nn_solv     =      1    !  elliptic solver: =1 preconditioned conjugate gradient (pcg)
-                           !                   =2 successive-over-relaxation (sor)
-   nn_sol_arp  =      0    !  absolute/relative (0/1) precision convergence test
-   rn_eps      =  1.e-6    !  absolute precision of the solver
-   nn_nmin     =    300    !  minimum of iterations for the SOR solver
-   nn_nmax     =    800    !  maximum of iterations for the SOR solver
-   nn_nmod     =     10    !  frequency of test for the SOR solver
-   rn_resmax   =  1.e-10   !  absolute precision for the SOR solver
-   rn_sor      =  1.92     !  optimal coefficient for SOR solver (to be adjusted with the domain)
-/
-!-----------------------------------------------------------------------
-&nammpp        !   Massively Parallel Processing                        ("key_mpp_mpi)
-!-----------------------------------------------------------------------
-   cn_mpi_send =  'I'      !  mpi send/recieve type   ='S', 'B', or 'I' for standard send,
-                           !  buffer blocking send or immediate non-blocking sends, resp.
-   nn_buffer   =   0       !  size in bytes of exported buffer ('B' case), 0 no exportation
-   ln_nnogather=  .false.  !  activate code to avoid mpi_allgather use at the northfold
-   jpni        =   0       !  jpni   number of processors following i (set automatically if < 1)
-   jpnj        =   0       !  jpnj   number of processors following j (set automatically if < 1)
-   jpnij       =   0       !  jpnij  number of local domains (set automatically if < 1)
-/
-!-----------------------------------------------------------------------
-&namctl        !   Control prints & Benchmark
-!-----------------------------------------------------------------------
-   ln_ctl      = .false.   !  trends control print (expensive!)
-   nn_print    =    0      !  level of print (0 no extra print)
-   nn_ictls    =    0      !  start i indice of control sum (use to compare mono versus
-   nn_ictle    =    0      !  end   i indice of control sum        multi processor runs
-   nn_jctls    =    0      !  start j indice of control               over a subdomain)
-   nn_jctle    =    0      !  end   j indice of control
-   nn_isplt    =    1      !  number of processors in i-direction
-   nn_jsplt    =    1      !  number of processors in j-direction
-   nn_bench    =    0      !  Bench mode (1/0): CAUTION use zero except for bench
-                           !     (no physical validity of the results)
-   nn_timing   =    0      !  timing by routine activated (=1) creates timing.output file, or not (=0)
-/
-!-----------------------------------------------------------------------
-&namc1d        !   1D configuration options                             ("key_c1d")
-!-----------------------------------------------------------------------
-   rn_lat      =    50     !  Column latitude
-   rn_lon      =    -145   !  Column longitude
-/
-!-----------------------------------------------------------------------
-&namc1d_uvd    !   data: U & V currents                                 ("key_c1d")
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable  ! time interp. !  clim  ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !             !  (if <0  months)  !   name    !   (logical)  !  (T/F) ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_ucur     = 'ucurrent'  ,         -1        ,'u_current',   .false.    , .true. , 'monthly' ,  ''      ,  'Ume'   , ''
-   sn_vcur     = 'vcurrent'  ,         -1        ,'v_current',   .false.    , .true. , 'monthly' ,  ''      ,  'Vme'   , ''
-!
-   cn_dir        = './'    !  root directory for the location of the files
-   ln_uvd_init   = .false. !  Initialisation of ocean U & V with U & V input data (T) or not (F)
-   ln_uvd_dyndmp = .false. !  damping of ocean U & V toward U & V input data (T) or not (F)
-/
-!-----------------------------------------------------------------------
-&namc1d_dyndmp !   U & V newtonian damping                              ("key_c1d")
-!-----------------------------------------------------------------------
-   ln_dyndmp   =  .false.  !  add a damping term (T) or not (F)
-/
-!!======================================================================
-!!                  ***  Diagnostics namelists  ***
-!!======================================================================
-!!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
-!!   namtrd       dynamics and/or tracer trends                         ("key_trddyn","key_trdtra","key_trdmld")
-!!   namflo       float parameters                                      ("key_float")
-!!   namptr       Poleward Transport Diagnostics
-!!   namhsb       Heat and salt budgets
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namnc4        !   netcdf4 chunking and compression settings            ("key_netcdf4")
-!-----------------------------------------------------------------------
-   nn_nchunks_i=   4       !  number of chunks in i-dimension
-   nn_nchunks_j=   4       !  number of chunks in j-dimension
-   nn_nchunks_k=   31      !  number of chunks in k-dimension
-                           !  setting nn_nchunks_k = jpk will give a chunk size of 1 in the vertical which
-                           !  is optimal for postprocessing which works exclusively with horizontal slabs
-   ln_nc4zip   = .true.    !  (T) use netcdf4 chunking and compression
-                           !  (F) ignore chunking information and produce netcdf3-compatible files
-/
-!-----------------------------------------------------------------------
-&namtrd        !   diagnostics on dynamics and/or tracer trends         ("key_trddyn" and/or "key_trdtra")
-!              !       or mixed-layer trends or barotropic vorticity    ("key_trdmld" or     "key_trdvor")
-!-----------------------------------------------------------------------
-   nn_trd      = 365       !  time step frequency dynamics and tracers trends
-   nn_ctls     =   0       !  control surface type in mixed-layer trends (0,1 or n<jpk)
-   rn_ucf      =   1.      !  unit conversion factor (=1 -> /seconds ; =86400. -> /day)
-   cn_trdrst_in      = "restart_mld"   ! suffix of ocean restart name (input)
-   cn_trdrst_out     = "restart_mld"   ! suffix of ocean restart name (output)
-   ln_trdmld_restart = .false.         !  restart for ML diagnostics
-   ln_trdmld_instant = .false.         !  flag to diagnose trends of instantantaneous or mean ML T/S
-/
-!-----------------------------------------------------------------------
-&namflo       !   float parameters                                      ("key_float")
-!-----------------------------------------------------------------------
-   jpnfl         = 1          !  total number of floats during the run
-   jpnnewflo     = 0          !  number of floats for the restart
-   ln_rstflo     = .false.    !  float restart (T) or not (F)
-   nn_writefl    =      75    !  frequency of writing in float output file
-   nn_stockfl    =    5475    !  frequency of creation of the float restart file
-   ln_argo       = .false.    !  Argo type floats (stay at the surface each 10 days)
-   ln_flork4     = .false.    !  trajectories computed with a 4th order Runge-Kutta (T)
-                              !  or computed with Blanke' scheme (F)
-   ln_ariane     = .true.     !  Input with Ariane tool convention(T)
-   ln_flo_ascii  = .true.     !  Output with Ariane tool netcdf convention(F) or ascii file (T)
-/
-!-----------------------------------------------------------------------
-&namptr       !   Poleward Transport Diagnostic
-!-----------------------------------------------------------------------
-   ln_diaptr  = .false.    !  Poleward heat and salt transport (T) or not (F)
-   ln_diaznl  = .true.     !  Add zonal means and meridional stream functions
-   ln_subbas  = .true.     !  Atlantic/Pacific/Indian basins computation (T) or not
-                           !  (orca configuration only, need input basins mask file named "subbasins.nc"
-   ln_ptrcomp = .true.     !  Add decomposition : overturning
-   nn_fptr    =  1         !  Frequency of ptr computation [time step]
-   nn_fwri    =  15        !  Frequency of ptr outputs [time step]
-/
-!-----------------------------------------------------------------------
-&namhsb       !  Heat and salt budgets
-!-----------------------------------------------------------------------
-   ln_diahsb  = .false.    !  check the heat and salt budgets (T) or not (F)
-/
-!-----------------------------------------------------------------------
-&nam_diaharm   !   Harmonic analysis of tidal constituents ('key_diaharm')
-!-----------------------------------------------------------------------
-    nit000_han = 1         ! First time step used for harmonic analysis
-    nitend_han = 75        ! Last time step used for harmonic analysis
-    nstep_han  = 15        ! Time step frequency for harmonic analysis
-    tname(1)   = 'M2'      ! Name of tidal constituents
-    tname(2)   = 'K1'
-/
-!-----------------------------------------------------------------------
-&namdct        ! transports through sections
-!-----------------------------------------------------------------------
-    nn_dct      = 15       !  time step frequency for transports computing
-    nn_dctwri   = 15       !  time step frequency for transports writing
-    nn_secdebug = 112      !      0 : no section to debug
-                           !     -1 : debug all section
-                           !  0 < n : debug section number n
-/
-
-!!======================================================================
-!!            ***  Observation & Assimilation namelists ***
-!!======================================================================
-!!   namobs       observation and model comparison                      ('key_diaobs')
-!!   nam_asminc   assimilation increments                               ('key_asminc')
-!!======================================================================
-!
-!-----------------------------------------------------------------------
-&namobs       !  observation usage switch                               ('key_diaobs')
-!-----------------------------------------------------------------------
-   ln_t3d     = .false.    ! Logical switch for T profile observations
-   ln_s3d     = .false.    ! Logical switch for S profile observations
-   ln_ena     = .false.    ! Logical switch for ENACT insitu data set
-   !                       !     ln_cor                  Logical switch for Coriolis insitu data set
-   ln_profb   = .false.    ! Logical switch for feedback insitu data set
-   ln_sla     = .false.    ! Logical switch for SLA observations
-
-   ln_sladt   = .false.    ! Logical switch for AVISO SLA data
-
-   ln_slafb   = .false.    ! Logical switch for feedback SLA data
-                           !     ln_ssh                  Logical switch for SSH observations
-
-   ln_sst     = .false.     ! Logical switch for SST observations
-   ln_reysst  = .false.     !     ln_reysst               Logical switch for Reynolds observations
-   ln_ghrsst  = .false.    !     ln_ghrsst               Logical switch for GHRSST observations      
-
-   ln_sstfb   = .false.    ! Logical switch for feedback SST data
-                           !     ln_sss                  Logical switch for SSS observations
-   ln_seaice  = .false.    ! Logical switch for Sea Ice observations
-                           !     ln_vel3d                Logical switch for velocity observations
-                           !     ln_velavcur             Logical switch for velocity daily av. cur.
-                           !     ln_velhrcur             Logical switch for velocity high freq. cur.
-                           !     ln_velavadcp            Logical switch for velocity daily av. ADCP
-                           !     ln_velhradcp            Logical switch for velocity high freq. ADCP
-                           !     ln_velfb                Logical switch for feedback velocity data
-                           !     ln_grid_global          Global distribtion of observations
-                           !     ln_grid_search_lookup   Logical switch for obs grid search w/lookup table
-                           !     grid_search_file        Grid search lookup file header
-                           !     enactfiles              ENACT input observation file names
-                           !     coriofiles              Coriolis input observation file name
-   !                       ! profbfiles: Profile feedback input observation file name
-   profbfiles = 'profiles_01.nc'
-                           !     ln_profb_enatim         Enact feedback input time setting switch
-                           !     slafilesact             Active SLA input observation file name
-                           !     slafilespas             Passive SLA input observation file name
-   !                       ! slafbfiles: Feedback SLA input observation file name
-   slafbfiles = 'sla_01.nc'
-                           !     sstfiles                GHRSST input observation file name
-   !                       ! sstfbfiles: Feedback SST input observation file name
-   sstfbfiles = 'sst_01.nc'
-                           !     seaicefiles             Sea Ice input observation file name
-   seaicefiles = 'seaice_01.nc'
-                           !     velavcurfiles           Vel. cur. daily av. input file name
-                           !     velhvcurfiles           Vel. cur. high freq. input file name
-                           !     velavadcpfiles          Vel. ADCP daily av. input file name
-                           !     velhvadcpfiles          Vel. ADCP high freq. input file name
-                           !     velfbfiles              Vel. feedback input observation file name
-                           !     dobsini                 Initial date in window YYYYMMDD.HHMMSS
-                           !     dobsend                 Final date in window YYYYMMDD.HHMMSS
-                           !     n1dint                  Type of vertical interpolation method
-                           !     n2dint                  Type of horizontal interpolation method
-                           !     ln_nea                  Rejection of observations near land switch
-   nmsshc     = 0          ! MSSH correction scheme
-                           !     mdtcorr                 MDT  correction
-                           !     mdtcutoff               MDT cutoff for computed correction
-   ln_altbias = .false.    ! Logical switch for alt bias
-   ln_ignmis  = .true.     ! Logical switch for ignoring missing files
-                           !     endailyavtypes   ENACT daily average types
-   ln_grid_global = .true.
-   ln_grid_search_lookup = .false.
-/
-!-----------------------------------------------------------------------
-&nam_asminc   !   assimilation increments                               ('key_asminc')
-!-----------------------------------------------------------------------
-    ln_bkgwri = .false.    !  Logical switch for writing out background state
-    ln_trainc = .false.    !  Logical switch for applying tracer increments
-    ln_dyninc = .false.    !  Logical switch for applying velocity increments
-    ln_sshinc = .false.    !  Logical switch for applying SSH increments
-    ln_asmdin = .false.    !  Logical switch for Direct Initialization (DI)
-    ln_asmiau = .false.    !  Logical switch for Incremental Analysis Updating (IAU)
-    nitbkg    = 0          !  Timestep of background in [0,nitend-nit000-1]
-    nitdin    = 0          !  Timestep of background for DI in [0,nitend-nit000-1]
-    nitiaustr = 1          !  Timestep of start of IAU interval in [0,nitend-nit000-1]
-    nitiaufin = 15         !  Timestep of end of IAU interval in [0,nitend-nit000-1]
-    niaufn    = 0          !  Type of IAU weighting function
-    ln_salfix = .false.    !  Logical switch for ensuring that the sa > salfixmin
-    salfixmin = -9999      !  Minimum salinity after applying the increments
-    nn_divdmp = 0          !  Number of iterations of divergence damping operator
-/
-!-----------------------------------------------------------------------
-&namsbc_wave   ! External fields from wave model
-!-----------------------------------------------------------------------
-!              !  file name  ! frequency (hours) ! variable     ! time interp. !  clim   ! 'yearly'/ ! weights  ! rotation ! land/sea mask !
-!              !             !  (if <0  months)  !   name       !   (logical)  !  (T/F)  ! 'monthly' ! filename ! pairing  ! filename      !
-   sn_cdg      =  'cdg_wave' ,        1          , 'drag_coeff' ,     .true.   , .false. , 'daily'   ,  ''      , ''       , ''
-   sn_usd      =  'sdw_wave' ,        1          , 'u_sd2d'     ,     .true.   , .false. , 'daily'   ,  ''      , ''       , ''
-   sn_vsd      =  'sdw_wave' ,        1          , 'v_sd2d'     ,     .true.   , .false. , 'daily'   ,  ''      , ''       , ''
-   sn_wn       =  'sdw_wave' ,        1          , 'wave_num'   ,     .true.   , .false. , 'daily'   ,  ''      , ''       , ''
-!
-   cn_dir_cdg  = './'  !  root directory for the location of drag coefficient files
-/
-!-----------------------------------------------------------------------
-&namdyn_nept  !   Neptune effect (simplified: lateral and vertical diffusions removed)
-!-----------------------------------------------------------------------
-   ! Suggested lengthscale values are those of Eby & Holloway (1994) for a coarse model
-   ln_neptsimp       = .false.  ! yes/no use simplified neptune
-
-   ln_smooth_neptvel = .false.  ! yes/no smooth zunep, zvnep
-   rn_tslse          =  1.2e4   ! value of lengthscale L at the equator
-   rn_tslsp          =  3.0e3   ! value of lengthscale L at the pole
-   ! Specify whether to ramp down the Neptune velocity in shallow
-   ! water, and if so the depth range controlling such ramping down
-   ln_neptramp       = .true.   ! ramp down Neptune velocity in shallow water
-   rn_htrmin         =  100.0   ! min. depth of transition range
-   rn_htrmax         =  200.0   ! max. depth of transition range
-/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/README_configs_namcfg_namdom
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/README_configs_namcfg_namdom	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/README_configs_namcfg_namdom	(revision 5075)
@@ -331,7 +331,7 @@
 !-----------------------------------------------------------------------
    cp_cfg      =  "orca"               !  name of the configuration
-   jp_cfg      =    1442               !  resolution of the configuration
-   jpidta      =    1021               !  1st lateral dimension ( >= jpi )
-   jpjdta      =     511               !  2nd    "         "    ( >= jpj )
+   jp_cfg      =     025               !  resolution of the configuration
+   jpidta      =    1442               !  1st lateral dimension ( >= jpi )
+   jpjdta      =    1021               !  2nd    "         "    ( >= jpj )
    jpkdta      =      75               !  number of levels      ( >= jpk )
    jpiglo      =    1442               !  1st dimension of global domain --> i =jpidta
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/domain_def.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/domain_def.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/domain_def.xml	(revision 5075)
@@ -5,5 +5,6 @@
 	 <!--   My zoom: example of hand defined zoom   -->
          <domain id="myzoom" zoom_ibegin="10" zoom_jbegin="10" zoom_ni="5" zoom_nj="5" />
-	 <!--   Eq section   -->
+         <domain id="1point" zoom_ibegin="10" zoom_jbegin="10" zoom_ni="1" zoom_nj="1" />
+         <!--   Eq section   -->
          <domain id="EqT" zoom_ibegin="1" zoom_jbegin="0000" zoom_ni="0000" zoom_nj="1" />
          <!--   TAO   -->
@@ -170,5 +171,7 @@
       <domain_group id="scalarpoint">
          <domain id="scalarpoint" long_name="scalar"/>
+         <!--
          <domain id="1point" zoom_ibegin="1" zoom_jbegin="1" zoom_ni="1" zoom_nj="1" />
+         -->
       </domain_group>
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/field_def.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/field_def.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/field_def.xml	(revision 5075)
@@ -28,7 +28,14 @@
          <field id="mldkz5"       long_name="mixing layer depth (Turbocline)"           unit="m"                        />
          <field id="mldr10_1"     long_name="Mixed Layer Depth 0.01 ref.10m"            unit="m"                        />
-         <field id="rhop"         long_name="potential density (sigma0)"                unit="kg/m3" grid_ref="grid_T_3D"/>
-	 <field id="eken"         long_name="kinetic energy"                            unit="m2/s2" grid_ref="grid_T_3D"/>
-	 <field id="hdiv"         long_name="horizontal divergence"                     unit="s-1"   grid_ref="grid_T_3D"/>
+         <field id="heatc"        long_name="Heat content vertically integrated"        unit="J/m2"                      />
+         <field id="saltc"        long_name="Salt content vertically integrated"        unit="PSU*kg/m2"                />
+         <!-- EOS -->
+         <field id="alpha"        long_name="thermal expansion"                         unit="1/degC" grid_ref="grid_T_3D"/>
+         <field id="beta"         long_name="haline contraction"                        unit="1/psu"  grid_ref="grid_T_3D"/>
+         <field id="bn2"          long_name="squared Brunt-Vaisala frequency"           unit="1/s"    grid_ref="grid_T_3D"/>
+         <field id="rhop"         long_name="potential density (sigma0)"                unit="kg/m3"  grid_ref="grid_T_3D"/>
+         <!-- Energy - horizontal divergence -->
+         <field id="eken"         long_name="kinetic energy"                            unit="m2/s2"  grid_ref="grid_T_3D"/>
+         <field id="hdiv"         long_name="horizontal divergence"                     unit="s-1"    grid_ref="grid_T_3D"/>
          <!-- variables available with MLE -->
          <field id="Lf_NHpf"      long_name="MLE: Lf = N H / f"                         unit="m"                        />
@@ -156,7 +163,14 @@
 	 <!-- * variable relative to atmospheric pressure forcing : available with ln_apr_dyn -->
 	 <field id="ssh_ib"       long_name="Inverse barometer sea surface height"                         unit="m"        />
-	
+
+         <!-- * variable related to ice shelf forcing * -->
+         <field id="fwfisf"       long_name="Ice shelf melting"                                            unit="Kg/m2/s"  />
+         <field id="qisf"         long_name="Ice Shelf Heat Flux"                                          unit="W/m2"     />
+         <field id="isfgammat"    long_name="transfert coefficient for isf (temperature) "                 unit="m/s"      />
+         <field id="isfgammas"    long_name="transfert coefficient for isf (salinity)    "                 unit="m/s"      />
+ 	     <field id="stbl"         long_name="salinity in the Losh tbl                    "                 unit="PSU"      />
+	     <field id="ttbl"         long_name="temperature in the Losh tbl                 "                 unit="C"        />
+
          <!-- *_oce variables available with ln_blk_clio or ln_blk_core -->
-         <field id="qns_oce"      long_name="Non solar Downward Heat Flux over open ocean"                 unit="W/m2"     />
          <field id="qlw_oce"      long_name="Longwave Downward Heat Flux over open ocean"                  unit="W/m2"     />
          <field id="qsb_oce"      long_name="Sensible Downward Heat Flux over open ocean"                  unit="W/m2"     />
@@ -194,5 +208,4 @@
          <field id="ice_cover"    long_name="Ice fraction"                                                 unit="1"        />
 
-         <field id="ioceflxb"     long_name="Oceanic flux at the ice base"                                 unit="W/m2"     />
          <field id="qsr_ai_cea"   long_name="Air-Ice downward solar heat flux (cell average)"              unit="W/m2"     />
          <field id="qns_ai_cea"   long_name="Air-Ice downward non-solar heat flux (cell average)"          unit="W/m2"     />
@@ -205,4 +218,5 @@
          <field id="icethic_cea"  long_name="Ice thickness (cell average)"                                 unit="m"        />
          <field id="iceprod_cea"  long_name="Ice production (cell average)"                                unit="m/s"      />
+         <field id="iiceconc"     long_name="Ice concentration"                                            unit=""         />
          
          <field id="ice_pres"     long_name="Ice presence"                                                 unit="-"        />
@@ -219,10 +233,6 @@
          <field id="emp_x_sst"    long_name="Concentration/Dilution term on SST"                           unit="kgC/m2/s" />
          <field id="emp_x_sss"    long_name="Concentration/Dilution term on SSS"                         unit="kgPSU/m2/s" />        
-         
-         
+       
          <field id="iceconc"      long_name="ice concentration"                                            unit="%"        />
-         <field id="icebopr"      long_name="daily bottom thermo ice prod."                                unit="km3/day"   />
-         <field id="icedypr"      long_name="daily  dynamic ice prod."                                     unit="km3/day"   />
-	 <field id="ioceflxb"     long_name="Oceanic flux at the ice base"                                 unit="W/m2"     />
          <field id="uice_ipa"     long_name="Ice velocity along i-axis at I-point (ice presence average)"  unit="m/s"      />
          <field id="vice_ipa"     long_name="Ice velocity along j-axis at I-point (ice presence average)"  unit="m/s"      />
@@ -232,34 +242,81 @@
          <field id="qsr_oce"      long_name="solar heat flux at ocean surface"                             unit="W/m2"     />
          <field id="qns_oce"      long_name="non-solar heat flux at ocean surface"                         unit="W/m2"     />
-         <field id="hfbri"        long_name="heat flux due to brine release"                               unit="W/m2"     />
+         <field id="qt_ice"       long_name="total flux at ice surface"                                    unit="W/m2"     />
+         <field id="qsr_ice"      long_name="solar heat flux at ice surface"                               unit="W/m2"     />
+         <field id="qns_ice"      long_name="non-solar heat flux at ice surface"                           unit="W/m2"     />
+         <field id="qtr_ice"      long_name="solar heat flux transmitted thru the ice"                     unit="W/m2"     />
          <field id="utau_ice"     long_name="Wind stress along i-axis over the ice at i-point"             unit="N/m2"     />
          <field id="vtau_ice"     long_name="Wind stress along j-axis over the ice at i-point"             unit="N/m2"     />
-	 <field id="qsr_io"       long_name="Ice-Oce downward solar heat flux"                             unit="W/m2"     />
-	 <field id="qns_io"       long_name="Ice-Oce downward non-solar heat flux"                         unit="W/m2"     />
          <field id="micesalt"     long_name="Mean ice salinity"                                            unit="psu"      />
          <field id="miceage"      long_name="Mean ice age"                                                 unit="years"    />
-         <field id="icelapr"      long_name="daily lateral thermo ice prod."                               unit="km3/day"   />
-         <field id="icesipr"      long_name="daily snowice ice prod."                                      unit="km3/day"   />
+
+         <field id="iceage_cat"   long_name="Ice age for categories"                                       unit="days"   axis_ref="ncatice" />
+         <field id="iceconc_cat"  long_name="Ice concentration for categories"                             unit="%"      axis_ref="ncatice" />
+         <field id="icethic_cat"  long_name="Ice thickness for categories"                                 unit="m"      axis_ref="ncatice" />
+         <field id="snowthic_cat" long_name="Snow thicknessi for categories"                               unit="m"      axis_ref="ncatice" />
+         <field id="salinity_cat" long_name="Sea-Ice Bulk salinity for categories"                         unit="ppt"    axis_ref="ncatice" />
+         <field id="brinevol_cat" long_name="Brine volume for categories"                                  unit="%"      axis_ref="ncatice" />
+
          <field id="micet"        long_name="Mean ice temperature"                                         unit="degC"     />
-         <field id="icehc"        long_name="ice total heat content"                                       unit="10^9 J"   /> 
+         <field id="icehc"        long_name="ice total heat content"                                       unit="10^9J"   /> 
          <field id="isnowhc"      long_name="snow total heat content"                                      unit="10^9J"    />
          <field id="icest"        long_name="ice surface temperature"                                      unit="degC"     />
-         <field id="sfxbri"       long_name="brine salt flux"                                              unit="psu*kg/m2/day" />
-         <field id="sfxthd"       long_name="equivalent FW salt flux"                                      unit="psu*kg/m2/day" />
          <field id="ibrinv"       long_name="brine volume"                                                 unit="%"        />
          <field id="icecolf"      long_name="frazil ice collection thickness"                              unit="m"        />
          <field id="icestr"       long_name="ice strength"                                                 unit="N/m"      />
          <field id="icevel"       long_name="ice velocity"                                                 unit="m/s"      />
-         <field id="isume"        long_name="surface melt"                                                 unit="km3/day"   />
-         <field id="ibome"        long_name="bottom melt"                                                  unit="km3/day"   />
          <field id="idive"        long_name="divergence"                                                   unit="10-8s-1"  />
          <field id="ishear"       long_name="shear"                                                        unit="10-8s-1"  />
-         <field id="icerepr"      long_name="daily resultant ice prod./melting from limupdate"             unit="km3/day"   />
-         <field id="icevolu"      long_name="ice volume"                                                   unit="km3"      />
-         <field id="snowvol"      long_name="snow volume"                                                  unit="km3"      />
-         <field id="sfxmec"       long_name="salt flux from ridging rafting"                               unit="psu*kg/m2/day" />
+         <field id="icevolu"      long_name="ice volume"                                                   unit="m"      />
+         <field id="snowvol"      long_name="snow volume"                                                  unit="m"      />
+
+         <field id="icetrp"       long_name="ice volume transport"                                         unit="m/day"   />
+         <field id="snwtrp"       long_name="snw volume transport"                                         unit="m/day"   />
+         <field id="deitrp"       long_name="advected ice enhalpy"                                         unit="W/m2"   />
+         <field id="destrp"       long_name="advected snw enhalpy"                                         unit="W/m2"   />
+
+         <field id="sfxbri"       long_name="brine salt flux"                                              unit="psu*kg/m2/day" />
+         <field id="sfxdyn"       long_name="salt flux from ridging rafting"                               unit="psu*kg/m2/day" />
          <field id="sfxres"       long_name="salt flux from lipupdate (resultant)"                         unit="psu*kg/m2/day" />
-         <field id="icetrp"       long_name="ice volume transport"                                         unit="km3/day"   />
-
+         <field id="sfxbog"       long_name="salt flux from bot growth"                                    unit="psu*kg/m2/day" />
+         <field id="sfxbom"       long_name="salt flux from bot melt"                                      unit="psu*kg/m2/day" />
+         <field id="sfxsum"       long_name="salt flux from surf melt"                                     unit="psu*kg/m2/day" />
+         <field id="sfxsni"       long_name="salt flux from snow-ice formation"                            unit="psu*kg/m2/day" />
+         <field id="sfxopw"       long_name="salt flux from open water ice formation"                      unit="psu*kg/m2/day" />
+         <field id="sfx"          long_name="salt flux total"                                              unit="psu*kg/m2/day" />
+
+         <field id="vfxbog"       long_name="daily bottom thermo ice prod."                                unit="m/day"   />
+         <field id="vfxdyn"       long_name="daily  dynamic ice prod."                                     unit="m/day"   />
+         <field id="vfxopw"       long_name="daily lateral thermo ice prod."                               unit="m/day"   />
+         <field id="vfxsni"       long_name="daily snowice ice prod."                                      unit="m/day"   />
+         <field id="vfxsum"       long_name="surface melt"                                                 unit="m/day"   />
+         <field id="vfxbom"       long_name="bottom melt"                                                  unit="m/day"   />
+         <field id="vfxres"       long_name="daily resultant ice prod./melting from limupdate"             unit="m/day"   />
+         <field id="vfxice"       long_name="ice melt/growth"                                              unit="m/day"   />
+         <field id="vfxsnw"       long_name="snw melt/growth"                                              unit="m/day"   />
+         <field id="vfxsub"       long_name="snw sublimation"                                              unit="m/day"   />
+         <field id="vfxspr"       long_name="snw precipitation on ice"                                     unit="m/day"   />
+
+         <field id="hfxsum"   long_name="heat fluxes causing surface ice melt"            unit="W/m2"  />
+         <field id="hfxbom"   long_name="heat fluxes causing bottom ice melt"             unit="W/m2"  />
+         <field id="hfxbog"   long_name="heat fluxes causing bottom ice growth"           unit="W/m2"  />
+         <field id="hfxdif"   long_name="heat fluxes causing ice temperature change"      unit="W/m2"  />
+         <field id="hfxopw"   long_name="heat fluxes causing open water ice formation"    unit="W/m2"  />
+         <field id="hfxsnw"   long_name="heat fluxes causing snow melt"                   unit="W/m2"  />
+         <field id="hfxerr"   long_name="heat fluxes error after heat diffusion"          unit="W/m2"  />
+         <field id="hfxerr_rem" long_name="heat fluxes error after remapping"             unit="W/m2"  />
+         <field id="hfxout"   long_name="total heat fluxes received by the ocean"         unit="W/m2"  />
+         <field id="hfxin"    long_name="total heat fluxes at the ice/ocean surface"      unit="W/m2"  />
+
+	 <!-- heat flux associated with mass exchange -->
+         <field id="hfxthd"   long_name="heat fluxes from ice-ocean mass exchange during thermo"              unit="W/m2"  />
+         <field id="hfxdyn"   long_name="heat fluxes from ice-ocean mass exchange during dynamic"             unit="W/m2"  />
+         <field id="hfxres"   long_name="heat fluxes from ice-ocean mass exchange during resultant"           unit="W/m2"  />
+         <field id="hfxsub"   long_name="heat fluxes from ice-atm. mass exchange during sublimation"          unit="W/m2"  />
+         <field id="hfxspr"   long_name="heat fluxes from ice-atm. mass exchange during snow precip"          unit="W/m2" />
+
+	 <!-- diags -->
+         <field id="hfxdhc"    long_name="Heat content variation in snow and ice"   unit="W/m2" />
+         <field id="hfxtur"    long_name="turbulent heat flux at the ice base"      unit="W/m2"  />
 
       </field_group>
@@ -269,6 +326,6 @@
       <field_group id="grid_U"   grid_ref="grid_U_2D">
          <field id="utau"         long_name="Wind Stress along i-axis"                    unit="N/m2" />
-         <field id="suoce"        long_name="ocean surface current along i-axis"          unit="m/s"  />
          <field id="uoce"         long_name="ocean current along i-axis"                  unit="m/s"  grid_ref="grid_U_3D" />
+         <field id="ssu"          long_name="ocean surface current along i-axis"          unit="m/s"     />
          <field id="uocetr_eff"   long_name="Effective ocean transport along i-axis"      unit="m3/s" grid_ref="grid_U_3D" />
          <field id="uocet"        long_name="ocean transport along i-axis times temperature" unit="degC.m/s" grid_ref="grid_U_3D" />
@@ -280,8 +337,11 @@
          <!-- uoce_eiv: available with key_trabbl -->
          <field id="uoce_bbl"     long_name="BBL ocean current along i-axis"              unit="m/s"  grid_ref="grid_U_3D" />
-	 <field id="ahu_bbl"      long_name="BBL diffusive flux along i-axis"             unit="m3/s" />
+	     <field id="ahu_bbl"      long_name="BBL diffusive flux along i-axis"             unit="m3/s" />
+         <!-- variable for ice shelves -->
+	     <field id="utbl"         long_name="zonal current in the Losh tbl"               unit="m/s"  axis_ref="none" />
          <!-- variables available with key_diaar5 -->
          <field id="u_masstr"     long_name="ocean eulerian mass transport along i-axis"  unit="kg/s" grid_ref="grid_U_3D" />
          <field id="u_heattr"     long_name="ocean eulerian heat transport along i-axis"  unit="W"    />
+         <field id="u_salttr"     long_name="ocean eulerian salt transport along i-axis"  unit="PSU*kg/s"    />
          <field id="ueiv_heattr"  long_name="ocean bolus heat transport along i-axis"     unit="W"    />
          <field id="udiff_heattr" long_name="ocean diffusion heat transport along i-axis" unit="W"    />
@@ -292,6 +352,6 @@
       <field_group id="grid_V"   grid_ref="grid_V_2D">
          <field id="vtau"         long_name="Wind Stress along j-axis"                    unit="N/m2" />
-         <field id="svoce"        long_name="ocean surface current along j-axis"          unit="m/s"  />
          <field id="voce"         long_name="ocean current along j-axis"                  unit="m/s"  grid_ref="grid_V_3D" />
+         <field id="ssv"          long_name="ocean surface current along j-axis"          unit="m/s"  />
          <field id="vocetr_eff"   long_name="Effective ocean transport along j-axis"      unit="m3/s" grid_ref="grid_V_3D" />
          <field id="vocet"        long_name="ocean transport along j-axis times temperature" unit="degC.m/s" grid_ref="grid_V_3D" />
@@ -303,8 +363,11 @@
          <!-- voce_eiv: available with key_trabbl -->
          <field id="voce_bbl"     long_name="BBL ocean current along j-axis"              unit="m/s"  grid_ref="grid_V_3D" />
-	 <field id="ahv_bbl"      long_name="BBL diffusive flux along j-axis"             unit="m3/s"                   />
+	     <field id="ahv_bbl"      long_name="BBL diffusive flux along j-axis"             unit="m3/s"                   />
+         <!-- variable for ice shelves -->
+	     <field id="vtbl"         long_name="meridional current in the Losh tbl"        unit="m/s"  axis_ref="none" />
          <!-- variables available with key_diaar5 -->
          <field id="v_masstr"     long_name="ocean eulerian mass transport along j-axis"  unit="kg/s" grid_ref="grid_V_3D" />
          <field id="v_heattr"     long_name="ocean eulerian heat transport along j-axis"  unit="W"     />
+         <field id="v_salttr"     long_name="ocean eulerian salt transport along i-axis"  unit="PSU*kg/s"    />
          <field id="veiv_heattr"  long_name="ocean bolus heat transport along j-axis"     unit="W"     />
          <field id="vdiff_heattr" long_name="ocean diffusion heat transport along j-axis" unit="W"     />
@@ -350,20 +413,21 @@
 
    	 <!-- available with ln_diahsb -->
-	 <field id="bgtemper"     long_name="global mean temperature"                  unit="degC"   />
-	 <field id="bgsaline"     long_name="global mean salinity"                     unit="psu"    />
-	 <field id="bgheatco"     long_name="global mean heat content"                 unit="10^9J"  />
-	 <field id="bgsaltco"     long_name="global mean salt content"                 unit="psu*m3" />
-	 <field id="bgvolssh"     long_name="global mean ssh volume"                   unit="km3"     />
-	 <field id="bgvoltot"     long_name="global mean volume"                       unit="km3"     />
-	 <field id="bgsshtot"     long_name="global mean ssh"                          unit="m"      />
-	 <field id="bgfrcvol"     long_name="global mean volume from forcing"          unit="km3"     />
-	 <field id="bgfrctem"     long_name="global mean heat content from forcing"    unit="10^9J"  />
-	 <field id="bgfrcsal"     long_name="global mean salt content from forcing"    unit="psu*km3" />
-	 <field id="bgmistem"     long_name="global mean temperature error due to free surface" unit="degC" />
-	 <field id="bgmissal"     long_name="global mean salinity error due to free surface"    unit="psu"  />
+		 <field id="bgtemper"     long_name="global mean temperature"                  unit="degC"   />
+		 <field id="bgsaline"     long_name="global mean salinity"                     unit="psu"    />
+		 <field id="bgheatco"     long_name="global mean heat content"                 unit="10^9J"  />
+		 <field id="bgsaltco"     long_name="global mean salt content"                 unit="psu*m3" />
+		 <field id="bgvolssh"     long_name="global mean ssh volume"                   unit="km3"     />
+	     <field id="bgvole3t"     long_name="global mean volume variation (e3t)"           unit="km3"/>
+		 <field id="bgvoltot"     long_name="global mean volume"                       unit="km3"     />
+		 <field id="bgsshtot"     long_name="global mean ssh"                          unit="m"      />
+		 <field id="bgfrcvol"     long_name="global mean volume from forcing"          unit="km3"     />
+		 <field id="bgfrctem"     long_name="global mean heat content from forcing"    unit="10^9J"  />
+		 <field id="bgfrcsal"     long_name="global mean salt content from forcing"    unit="psu*km3" />
+		 <field id="bgmistem"     long_name="global mean temperature error due to free surface" unit="degC" />
+		 <field id="bgmissal"     long_name="global mean salinity error due to free surface"    unit="psu"  />
       </field_group>
 
       <field_group id="SBC_scalar"  domain_ref="1point" >
-         <!-- available with ln_limdiahsb -->
+         <!-- available with ln_limdiaout -->
 	 <field id="ibgvoltot"    long_name="global mean ice volume"                   unit="km3"   />
 	 <field id="sbgvoltot"    long_name="global mean snow volume"                  unit="km3"   />
@@ -371,16 +435,50 @@
 	 <field id="ibgsaline"    long_name="global mean ice salinity"                 unit="psu"   />
 	 <field id="ibgtemper"    long_name="global mean ice temperature"              unit="degC"   />
-	 <field id="ibgheatco"    long_name="global mean ice heat content"             unit="10^9J"   />
+	 <field id="ibgheatco"    long_name="global mean ice heat content"             unit="10^20J"   />
+	 <field id="sbgheatco"    long_name="global mean snow heat content"            unit="10^20J"   />
 	 <field id="ibgsaltco"    long_name="global mean ice salt content"             unit="psu*km3"   />
-	 <field id="sbgheatco"    long_name="global mean snow heat content"            unit="10^9J"   />
-	 <field id="ibgfrcsfx"    long_name="global mean salt content from sfx"        unit="psu*km3"   />
-	 <field id="ibgfrcemp"    long_name="global mean volume from emp"              unit="km3"      />
-	 <field id="ibgsfx"       long_name="global mean emps"                         unit="psu*kg/m2/day"   />
-	 <field id="ibgemp"       long_name="global mean emp"                          unit="kg/m2/day"   />
-	 <field id="ibgsfxbri"    long_name="global mean ice sfx_bri"                  unit="psu*kg/m2/day"   />
-	 <field id="ibgsfxthd"    long_name="global mean ice sfx_thd"                  unit="psu*kg/m2/day"   />
-	 <field id="ibgsfxres"    long_name="global mean ice sfx_res"                  unit="psu*kg/m2/day"   />
-	 <field id="ibgsfxmec"    long_name="global mean ice fsalt_rpo"                unit="psu*kg/m2/day"   />
-	 <field id="ibggrpme"     long_name="global mean ice growth+melt volume"       unit="km3"      />
+
+	 <field id="ibgvfx"       long_name="global mean volume flux (emp)"               unit="m/day"   />
+	 <field id="ibgvfxbog"    long_name="global mean volume flux (bottom growth)"     unit="m/day"   />
+	 <field id="ibgvfxopw"    long_name="global mean volume flux (open water growth)" unit="m/day"   />
+	 <field id="ibgvfxsni"    long_name="global mean volume flux (snow-ice growth)"   unit="m/day"   />
+	 <field id="ibgvfxdyn"    long_name="global mean volume flux (dynamic growth)"    unit="m/day"   />
+	 <field id="ibgvfxbom"    long_name="global mean volume flux (bottom melt)"       unit="m/day"   />
+	 <field id="ibgvfxsum"    long_name="global mean volume flux (surface melt)"      unit="m/day"   />
+	 <field id="ibgvfxres"    long_name="global mean volume flux (resultant)"         unit="m/day"   />
+	 <field id="ibgvfxspr"    long_name="global mean volume flux (snow precip)"       unit="m/day"   />
+	 <field id="ibgvfxsnw"    long_name="global mean volume flux (snow melt)"         unit="m/day"   />
+	 <field id="ibgvfxsub"    long_name="global mean volume flux (snow sublimation)"  unit="m/day"   />
+
+	 <field id="ibgsfx"       long_name="global mean salt flux (total)"            unit="psu*m/day"   />
+	 <field id="ibgsfxbri"    long_name="global mean salt flux (brines)"           unit="psu*m/day"   />
+	 <field id="ibgsfxdyn"    long_name="global mean salt flux (dynamic)"          unit="psu*m/day"   />
+	 <field id="ibgsfxres"    long_name="global mean salt flux (resultant)"        unit="psu*m/day"   />
+	 <field id="ibgsfxbog"    long_name="global mean salt flux (thermo)"           unit="psu*m/day"   />
+	 <field id="ibgsfxopw"    long_name="global mean salt flux (thermo)"           unit="psu*m/day"   />
+	 <field id="ibgsfxsni"    long_name="global mean salt flux (thermo)"           unit="psu*m/day"   />
+	 <field id="ibgsfxbom"    long_name="global mean salt flux (thermo)"           unit="psu*m/day"   />
+	 <field id="ibgsfxsum"    long_name="global mean salt flux (thermo)"           unit="psu*m/day"   />
+
+
+        <field id="ibghfxdhc"    long_name="Heat content variation in snow and ice"   unit="W" />
+        <field id="ibghfxspr"    long_name="Heat content of snow precip"              unit="W" />
+
+        <field id="ibghfxthd"   long_name="heat fluxes from ice-ocean exchange during thermo"              unit="W"  />
+        <field id="ibghfxsum"   long_name="heat fluxes causing surface ice melt"              unit="W"  />
+        <field id="ibghfxbom"   long_name="heat fluxes causing bottom ice melt"              unit="W"  />
+        <field id="ibghfxbog"   long_name="heat fluxes causing bottom ice growth"              unit="W"  />
+        <field id="ibghfxdif"   long_name="heat fluxes causing ice temperature change"              unit="W"  />
+        <field id="ibghfxopw"   long_name="heat fluxes causing open water ice formation"              unit="W"  />
+        <field id="ibghfxdyn"   long_name="heat fluxes from ice-ocean exchange during dynamic"             unit="W"  />
+        <field id="ibghfxres"   long_name="heat fluxes from ice-ocean exchange during resultant"           unit="W"  />
+        <field id="ibghfxsub"   long_name="heat fluxes from sublimation"                                   unit="W"  />
+        <field id="ibghfxsnw"   long_name="heat fluxes from snow-ocean exchange"                           unit="W"  />
+        <field id="ibghfxout"   long_name="non solar heat fluxes received by the ocean"                    unit="W"  />
+        <field id="ibghfxin"    long_name="total heat fluxes at the ice surface"                           unit="W"  />
+
+	 <field id="ibgfrcvol"    long_name="global mean forcing volume (emp)"         unit="km3"      />
+	 <field id="ibgfrcsfx"    long_name="global mean forcing salt   (sfx)"         unit="psu*km3"   />
+	 <field id="ibgvolgrm"    long_name="global mean ice growth+melt volume"       unit="km3"      />
       </field_group>
   
@@ -501,4 +599,8 @@
        <field id="EPSI100"     long_name="Export of Silicate at 100 m"             unit="mol/m2/s"                     />
        <field id="EPCAL100"    long_name="Export of Calcite at 100 m"              unit="mol/m2/s"                     />
+       <field id="EXPC"        long_name="Export of carbon"                        unit="molC/m2/s"  grid_ref="grid_T_3D" />
+       <field id="EXPFE"       long_name="Export of biogenic iron"                 unit="molFe/m2/s" grid_ref="grid_T_3D" />
+       <field id="EXPSI"       long_name="Export of Silicate"                      unit="molSi/m2/s" grid_ref="grid_T_3D" />
+       <field id="EXPCAL"      long_name="Export of Calcite"                       unit="molC/m2/s"  grid_ref="grid_T_3D" />
        <field id="Cflx"        long_name="DIC flux"                                unit="mol/m2/s"                     />
        <field id="Oflx"        long_name="Oxygen flux"                             unit="mol/m2/s"                     />
@@ -510,12 +612,27 @@
        <field id="Ironsed"     long_name="Iron deposition from sediment"           unit="mol/m2/s"  grid_ref="grid_T_3D"/>
 
+
        <!-- PISCES with Kriest parametisation : variables available with key_kriest -->
-       <field id="POCFlx"      long_name="Particulate organic C flux"              unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="NumFlx"      long_name="Particle number flux"                    unit="nbr/m2/s"   grid_ref="grid_T_3D" />
-       <field id="SiFlx"       long_name="Biogenic Si flux"                        unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="CaCO3Flx"    long_name="CaCO3 flux"                              unit="mol/m2/s"   grid_ref="grid_T_3D" />
-       <field id="xnum"        long_name="Number of particles in aggregats"        unit="-"          grid_ref="grid_T_3D" />
-       <field id="W1"          long_name="sinking speed of mass flux"              unit="m2/s"       grid_ref="grid_T_3D" />
-       <field id="W2"          long_name="sinking speed of number flux"            unit="m2/s"       grid_ref="grid_T_3D" />
+       <field id="EPN100"      long_name="Particulate number flux at 100 m"        unit="mol/m2/s"                     />
+       <field id="EXPN"        long_name="Particulate number flux"                 unit="mol/m2/s"   grid_ref="grid_T_3D" />
+       <field id="XNUM"        long_name="Number of particles in aggregats"        unit="-"          grid_ref="grid_T_3D" />
+       <field id="WSC"         long_name="sinking speed of mass flux"              unit="m2/s"       grid_ref="grid_T_3D" />
+       <field id="WSN"         long_name="sinking speed of number flux"            unit="m2/s"       grid_ref="grid_T_3D" />
+
+      <!-- dbio_T on T grid : variables available with key_diaar5 -->
+       <field id="TPP"         long_name="Total Primary production of phyto"                   unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPNEW"       long_name="New Primary production of phyto"                     unit="molC/m3/s"  grid_ref="grid_T_3D" />
+       <field id="TPBFE"       long_name="Total biogenic iron production"                      unit="molFe/m3/s" grid_ref="grid_T_3D" />
+       <field id="INTDIC"      long_name="DIC content"                                         unit="kg/m2"   />
+       <field id="O2MIN"       long_name="Oxygen minimum concentration"                        unit="molC/L" />
+       <field id="ZO2MIN"      long_name="Depth of oxygen minimum concentration"               unit="m"       />
+       <field id="INTNFIX"     long_name="Nitrogen fixation rate : vert. integrated"           unit="molN/m2/s"  />
+       <field id="INTPPPHY"    long_name="Vertically integrated primary production by nanophy" unit="molC/m2/s"  />
+       <field id="INTPPPHY2"   long_name="Vertically integrated primary production by diatom"  unit="molC/m2/s"  />
+       <field id="INTPP"       long_name="Vertically integrated primary production by phyto"   unit="molC/m2/s"  />
+       <field id="INTPNEW"     long_name="Vertically integrated new primary production"        unit="molC/m2/s"  />
+       <field id="INTPBFE"     long_name="Vertically integrated of biogenic iron production"   unit="molFe/m2/s" />
+       <field id="INTPBSI"     long_name="Vertically integrated of biogenic Si production"     unit="molSi/m2/s" />
+       <field id="INTPCAL"     long_name="Vertically integrated of calcite production"         unit="molC/m2/s" />
 
        <!-- PISCES light : variables available with key_pisces_reduced -->
@@ -549,4 +666,17 @@
        <field id="qintC14b"    long_name="Cumulative air-sea flux of Bomb C14"      unit="mol/m2"     />
        <field id="fdecay"      long_name="Radiactive decay of Bomb C14"             unit="mol/m3"  grid_ref="grid_T_3D"  />
+     </field_group>
+
+    <field_group id="PISCES_scalar"  domain_ref="1point" >
+       <field id="pno3tot"         long_name="global mean nitrate concentration"                  unit="mol/l"   />
+       <field id="psiltot"         long_name="global mean silicate concentration"                 unit="mol/l"   />
+       <field id="palktot"         long_name="global mean alkalinity concentration"               unit="mol/l"   />
+       <field id="pfertot"         long_name="global mean iron concentration"                     unit="mol/l"   />
+       <field id="tcflx"           long_name="total Flux of Carbon out of the ocean"              unit="molC/s" />
+       <field id="tcflxcum"        long_name="cumulative total Flux of Carbon out of the ocean"   unit="molC/s" />
+       <field id="tcexp"           long_name="total Carbon export at 100m"                        unit="molC/s" />
+       <field id="tintpp"          long_name="global total integrated primary production"         unit="molC/s" />
+       <field id="tnfix"           long_name="global total nitrogen fixation"                     unit="molN/s" />
+       <field id="tdenit"          long_name="Total denitrification"                              unit="molN/s" />
      </field_group>
 
@@ -615,5 +745,5 @@
     <field_group id="groupU" >
       <field field_ref="uoce"         name="uo"      long_name="sea_water_x_velocity"      />
-      <field field_ref="suoce"        name="uos"     long_name="sea_surface_x_velocity"    />
+      <field field_ref="ssu"          name="uos"     long_name="sea_surface_x_velocity"    />
       <field field_ref="utau"         name="tauuo"   long_name="surface_downward_x_stress" />
     </field_group>
@@ -621,5 +751,5 @@
     <field_group id="groupV" >
       <field field_ref="voce"         name="vo"      long_name="sea_water_y_velocity"      />
-      <field field_ref="svoce"        name="vos"     long_name="sea_surface_y_velocity"    />
+      <field field_ref="ssv"          name="vos"     long_name="sea_surface_y_velocity"    />
       <field field_ref="vtau"         name="tauvo"   long_name="surface_downward_y_stress" />
     </field_group>
@@ -629,3 +759,121 @@
     </field_group>
     
+    <!-- 
+============================================================================================================
+                     Trend diagnostics : temperature, KE, PE, momentum
+============================================================================================================
+    -->
+
+    <field_group id="trendT" grid_ref="grid_T_3D">
+      <!-- variables available with ln_tra_trd -->
+      <field id="ttrd_xad"      long_name="temperature-trend: i-advection"                 unit="degC/s" />
+      <field id="strd_xad"      long_name="salinity   -trend: i-advection"                 unit="psu/s"  />
+      <field id="ttrd_yad"      long_name="temperature-trend: j-advection"                 unit="degC/s" />
+      <field id="strd_yad"      long_name="salinity   -trend: j-advection"                 unit="psu/s"  />
+      <field id="ttrd_zad"      long_name="temperature-trend: k-advection"                 unit="degC/s" />
+      <field id="strd_zad"      long_name="salinity   -trend: k-advection"                 unit="psu/s"  />
+      <field id="ttrd_sad"      long_name="temperature-trend: surface adv. (no-vvl)"       unit="degC/s" grid_ref="grid_T_2D" />
+      <field id="strd_sad"      long_name="salinity   -trend: surface adv. (no-vvl)"       unit="psu/s"  grid_ref="grid_T_2D" />
+      <field id="ttrd_ldf"      long_name="temperature-trend: lateral  diffusion"          unit="degC/s" />
+      <field id="strd_ldf"      long_name="salinity   -trend: lateral  diffusion"          unit="psu/s"  />
+      <field id="ttrd_zdf"      long_name="temperature-trend: vertical diffusion"          unit="degC/s" />
+      <field id="strd_zdf"      long_name="salinity   -trend: vertical diffusion"          unit="psu/s"  />
+      <!-- ln_traldf_iso=T only (iso-neutral diffusion) -->
+      <field id="ttrd_zdfp"     long_name="temperature-trend: pure vert. diffusion"        unit="degC/s" />
+      <field id="strd_zdfp"     long_name="salinity   -trend: pure vert. diffusion"        unit="psu/s"  />
+      <!-- -->
+      <field id="ttrd_dmp"      long_name="temperature-trend: interior restoring"          unit="degC/s" />
+      <field id="strd_dmp"      long_name="salinity   -trend: interior restoring"          unit="psu/s"  />
+      <field id="ttrd_bbl"      long_name="temperature-trend: bottom boundary layer"       unit="degC/s" />
+      <field id="strd_bbl"      long_name="salinity   -trend: bottom boundary layer"       unit="psu/s"  />
+      <field id="ttrd_npc"      long_name="temperature-trend: non-penetrative conv."       unit="degC/s" />
+      <field id="strd_npc"      long_name="salinity   -trend: non-penetrative conv."       unit="psu/s"  />
+      <field id="ttrd_qns"      long_name="temperature-trend: non-solar flux + runoff"     unit="degC/s" />
+      <field id="strd_cdt"      long_name="salinity   -trend: C/D term       + runoff"     unit="degC/s" />
+      <field id="ttrd_qsr"      long_name="temperature-trend: solar penetr. heating"       unit="degC/s" />
+      <field id="ttrd_bbc"      long_name="temperature-trend: geothermal heating"          unit="degC/s" />
+      <field id="ttrd_atf"      long_name="temperature-trend: asselin time filter"         unit="degC/s" />
+      <field id="strd_atf"      long_name="salinity   -trend: asselin time filter"         unit="psu/s"  />
+      <!-- variables available with ln_KE_trd -->
+      <field id="ketrd_hpg"     long_name="ke-trend: hydrostatic pressure gradient"        unit="W/s^3"  />
+      <field id="ketrd_spg"     long_name="ke-trend: surface     pressure gradient"        unit="W/s^3"  />
+      <field id="ketrd_spgexp"  long_name="ke-trend: surface pressure gradient (explicit)" unit="W/s^3"  />
+      <field id="ketrd_spgflt"  long_name="ke-trend: surface pressure gradient (filter)"   unit="W/s^3"  />
+      <field id="ssh_flt"       long_name="filtered contribution to ssh (dynspg_flt)"      unit="m"     grid_ref="grid_T_2D"   />
+      <field id="w0"            long_name="surface vertical velocity"                      unit="m/s"   grid_ref="grid_T_2D"   />
+      <field id="pw0_exp"       long_name="surface pressure flux due to ssh"               unit="W/s^2" grid_ref="grid_T_2D"   />
+      <field id="pw0_flt"       long_name="surface pressure flux due to filtered ssh"      unit="W/s^2" grid_ref="grid_T_2D"   />
+      <field id="ketrd_keg"     long_name="ke-trend: KE gradient         or hor. adv."     unit="W/s^3"  />
+      <field id="ketrd_rvo"     long_name="ke-trend: relative  vorticity or metric term"   unit="W/s^3"  />
+      <field id="ketrd_pvo"     long_name="ke-trend: planetary vorticity"                  unit="W/s^3"  />
+      <field id="ketrd_zad"     long_name="ke-trend: vertical  advection"                  unit="W/s^3"  />
+      <field id="ketrd_udx"     long_name="ke-trend: U.dx[U]"                              unit="W/s^3"  />
+      <field id="ketrd_ldf"     long_name="ke-trend: lateral   diffusion"                  unit="W/s^3"  />
+      <field id="ketrd_zdf"     long_name="ke-trend: vertical  diffusion"                  unit="W/s^3"  />
+      <field id="ketrd_tau"     long_name="ke-trend: wind stress "                         unit="W/s^3" grid_ref="grid_T_2D"   />
+      <field id="ketrd_bfr"     long_name="ke-trend: bottom friction (explicit)"           unit="W/s^3"  />   
+      <field id="ketrd_bfri"    long_name="ke-trend: bottom friction (implicit)"           unit="W/s^3"  />   
+      <field id="ketrd_atf"     long_name="ke-trend: asselin time filter trend"            unit="W/s^3"  />  
+      <field id="ketrd_convP2K" long_name="ke-trend: conversion (potential to kinetic)"    unit="W/s^3"  />
+      <field id="KE"            long_name="kinetic energy: u(n)*u(n+1)/2"                  unit="W/s^2"  />   
+      <!-- variables available with ln_PE_trd -->
+      <field id="petrd_xad"     long_name="pe-trend: i-advection"                          unit="W/m^3"  />
+      <field id="petrd_yad"     long_name="pe-trend: j-advection"                          unit="W/m^3"  />
+      <field id="petrd_zad"     long_name="pe-trend: k-advection"                          unit="W/m^3"  />
+      <field id="petrd_sad"     long_name="pe-trend: surface adv. (no-vvl)"                unit="W/m^3"  grid_ref="grid_T_2D" />
+      <field id="petrd_ldf"     long_name="pe-trend: lateral  diffusion"                   unit="W/m^3"  />
+      <field id="petrd_zdf"     long_name="pe-trend: vertical diffusion"                   unit="W/m^3"  />
+      <field id="petrd_zdfp"    long_name="pe-trend: pure vert. diffusion"                 unit="W/m^3"  />
+      <field id="petrd_dmp"     long_name="pe-trend: interior restoring"                   unit="W/m^3"  />
+      <field id="petrd_bbl"     long_name="pe-trend: bottom boundary layer"                unit="W/m^3"  />
+      <field id="petrd_npc"     long_name="pe-trend: non-penetrative conv."                unit="W/m^3"  />
+      <field id="petrd_nsr"     long_name="pe-trend: surface forcing + runoff"             unit="W/m^3"  />
+      <field id="petrd_qsr"     long_name="pe-trend: solar penetr. heating"                unit="W/m^3"  />
+      <field id="petrd_bbc"     long_name="pe-trend: geothermal heating"                   unit="W/m^3"  />
+      <field id="petrd_atf"     long_name="pe-trend: asselin time filter"                  unit="W/m^3"  />
+      <field id="PEanom"        long_name="potential energy anomaly"                       unit="SI"     />   
+      <field id="alphaPE"       long_name="- partial deriv. of PEanom wrt T"               unit="/degC"  />   
+      <field id="betaPE"        long_name="partial deriv. of PEanom wrt S"                 unit="/psu"   />   
+    </field_group>
+
+    <field_group id="trendU" grid_ref="grid_U_3D">
+     <!-- variables available with ln_dyn_trd -->
+     <field id="utrd_hpg"       long_name="i-trend: hydrostatic pressure gradient"         unit="m/s^2"                      />
+     <field id="utrd_spg"       long_name="i-trend: surface     pressure gradient"         unit="m/s^2"                      />
+     <field id="utrd_spgexp"    long_name="i-trend: surface pressure gradient (explicit)"  unit="m/s^2"                      />
+     <field id="utrd_spgflt"    long_name="i-trend: surface pressure gradient (filtered)"  unit="m/s^2"                      />
+     <field id="utrd_keg"       long_name="i-trend: KE gradient         or hor. adv."      unit="m/s^2"                      />
+     <field id="utrd_rvo"       long_name="i-trend: relative  vorticity or metric term"    unit="m/s^2"                      />
+     <field id="utrd_pvo"       long_name="i-trend: planetary vorticity"                   unit="m/s^2"                      />
+     <field id="utrd_zad"       long_name="i-trend: vertical  advection"                   unit="m/s^2"                      />
+     <field id="utrd_udx"       long_name="i-trend: U.dx[U]"                               unit="m/s^2"                      />
+     <field id="utrd_ldf"       long_name="i-trend: lateral   diffusion"                   unit="m/s^2"                      />
+     <field id="utrd_zdf"       long_name="i-trend: vertical  diffusion"                   unit="m/s^2"                      />
+     <field id="utrd_tau"       long_name="i-trend: wind stress "                          unit="m/s^2" grid_ref="grid_U_2D" />
+     <field id="utrd_bfr"       long_name="i-trend: bottom friction (explicit)"            unit="m/s^2"                      />   
+     <field id="utrd_bfri"      long_name="i-trend: bottom friction (implicit)"            unit="m/s^2"                      />   
+     <field id="utrd_tot"       long_name="i-trend: total momentum trend before atf"       unit="m/s^2"                      />   
+     <field id="utrd_atf"       long_name="i-trend: asselin time filter trend"             unit="m/s^2"                      />   
+    </field_group>
+
+    <field_group id="trendV" grid_ref="grid_V_3D">
+     <!-- variables available with ln_dyn_trd -->
+     <field id="vtrd_hpg"       long_name="j-trend: hydrostatic pressure gradient"         unit="m/s^2"                      />
+     <field id="vtrd_spg"       long_name="j-trend: surface     pressure gradient"         unit="m/s^2"                      />
+     <field id="vtrd_spgexp"    long_name="j-trend: surface pressure gradient (explicit)"  unit="m/s^2"                      />
+     <field id="vtrd_spgflt"    long_name="j-trend: surface pressure gradient (filtered)"  unit="m/s^2"                      />
+     <field id="vtrd_keg"       long_name="j-trend: KE gradient         or hor. adv."      unit="m/s^2"                      />
+     <field id="vtrd_rvo"       long_name="j-trend: relative  vorticity or metric term"    unit="m/s^2"                      />
+     <field id="vtrd_pvo"       long_name="j-trend: planetary vorticity"                   unit="m/s^2"                      />
+     <field id="vtrd_zad"       long_name="j-trend: vertical  advection"                   unit="m/s^2"                      />
+     <field id="vtrd_vdy"       long_name="i-trend: V.dx[V]"                               unit="m/s^2"                      />
+     <field id="vtrd_ldf"       long_name="j-trend: lateral   diffusion"                   unit="m/s^2"                      />
+     <field id="vtrd_zdf"       long_name="j-trend: vertical  diffusion"                   unit="m/s^2"                      />
+     <field id="vtrd_tau"       long_name="j-trend: wind stress "                          unit="m/s^2" grid_ref="grid_V_2D" />
+     <field id="vtrd_bfr"       long_name="j-trend: bottom friction (explicit)"            unit="m/s^2"                      />   
+     <field id="vtrd_bfri"      long_name="j-trend: bottom friction (implicit)"            unit="m/s^2"                      />   
+     <field id="vtrd_tot"       long_name="j-trend: total momentum trend before atf"       unit="m/s^2"                      />   
+     <field id="vtrd_atf"       long_name="j-trend: asselin time filter trend"            unit="m/s^2"                       />   
+    </field_group>
+
     </field_definition>
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/namelist_ice_lim3_ref
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/namelist_ice_lim3_ref	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/namelist_ice_lim3_ref	(revision 5075)
@@ -15,25 +15,28 @@
 !-----------------------------------------------------------------------
    cn_icerst_in  = "restart_ice"   !  suffix of ice restart name (input)
-   cn_icerst_out = "restart_ice"      !  suffix of ice restart name (output)
-   ln_limdyn   = .true.    !  ice dynamics (T) or thermodynamics only (F)
-   amax        = 0.999      !  maximum ice concentration
-   cai         =  1.40e-3  !  atmospheric drag over sea ice
-   cao         =  1.00e-3  !  atmospheric drag over ocean
-   ln_nicep    = .false.   !  Ice points output for debug (yes or no)
-   ln_limdiahsb  = .false.    !  check the heat and salt budgets (T) or not (F)
-   ln_limdiaout  = .false.    !  output the heat and salt budgets (T) or not (F)
+   cn_icerst_out = "restart_ice"   !  suffix of ice restart name (output)
+   ln_limdyn     = .true.          !  ice dynamics (T) or thermodynamics only (F)
+   amax          = 0.999           !  maximum ice concentration
+   cai           = 1.40e-3         !  atmospheric drag over sea ice (clio)
+   cao           = 1.00e-3         !  atmospheric drag over ocean   (clio)
+   ln_nicep      = .false.         !  Ice points output for debug (yes or no)
+   ln_limdiahsb  = .false.          !  check the heat and salt budgets (T) or not (F)
+   ln_limdiaout  = .true.          !  output the heat and salt budgets (T) or not (F)
 /
 !-----------------------------------------------------------------------
 &namiceini     !   ice initialisation
 !-----------------------------------------------------------------------
-   ttest       =  2.0      !  threshold water temperature for initial sea ice
-   hninn       =  0.3      !  initial snow thickness in the north
-   hnins       =  0.1      !        "            "          south
-   hginn       =  3.50     !  initial undeformed ice thickness in the north
-   hgins       =  1.0      !        "            "              "     south
-   aginn       =  0.95     !  initial undeformed ice concentration in the north
-   agins       =  0.9      !        "            "              "         south
-   sinn        =  6.301    !  initial salinity in the north
-   sins        =  6.301    !        "            "    south
+   ln_limini   = .false.   !  activate ice initialization (T) or not (F)
+   thres_sst   =  0.0      !  threshold water temperature for initial sea ice
+   hts_ini_n   =  0.3      !  initial snow thickness in the north
+   hts_ini_s   =  0.3      !        "            "          south
+   hti_ini_n   =  1.0      !  initial ice thickness in the north
+   hti_ini_s   =  1.0      !        "            "         south
+   ati_ini_n   =  0.9      !  initial ice concentration in the north
+   ati_ini_s   =  0.9      !        "            "             south
+   smi_ini_n   =  6.301    !  initial ice salinity in the north
+   smi_ini_s   =  6.301    !        "            "    south
+   tmi_ini_n   =  270.     !  initial ice/snw temp in the north
+   tmi_ini_s   =  270.     !  initial ice/snw temp in the south
 /
 !-----------------------------------------------------------------------
@@ -41,27 +44,15 @@
 !-----------------------------------------------------------------------
    epsd        =   1.0e-20 !  tolerance parameter
-   alpha       =   0.5     !  coefficient for semi-implicit coriolis
-   dm          =   0.6e+03 !  diffusion constant for dynamics
-   nbiter      =   1       !  number of sub-time steps for relaxation
-   nbitdr      = 500       !  maximum number of iterations for relaxation
    om          =   0.5     !  relaxation constant 
-   resl        =   5.0e-05 !  maximum value for the residual of relaxation
    cw          =   5.0e-03 !  drag coefficient for oceanic stress
-   angvg       =   0.0     !  turning angle for oceanic stress
    pstar       =   2.0e+04 !  1st bulk-rheology parameter
    c_rhg       =  20.0     !  2nd bulk-rhelogy parameter
-   etamn       =   0.0e+07 !  minimun value for viscosity
    creepl      =   1.0e-12 !  creep limit
    ecc         =   2.0     !  eccentricity of the elliptical yield curve
    ahi0        = 350.e0    !  horizontal eddy diffusivity coefficient for sea-ice [m2/s]
-   nevp        = 300       !  number of iterations for subcycling in EVP, SB, 400
-   telast      =9600.0     !  timescale for elastic waves, SB, 720.0
+   nevp        = 120       !  number of iterations for subcycling in EVP
+   relast      = 0.333     !  ratio of elastic timescale over ice time step (1/3 if nevp=120 ; 1/9 if nevp=300)
    alphaevp    =   1.0     !  coefficient for the solution of internal ice stresses
    hminrhg     =   0.001   !  ice volume (a*h in m) below which ice velocity equal ocean velocity
-/
-!-----------------------------------------------------------------------
-&namicetrp     !   ice transport
-!-----------------------------------------------------------------------
-   bound       =   0.      !  boundary conditions (=0.0 no-slip, =1.0 free-slip)
 /
 !-----------------------------------------------------------------------
@@ -69,23 +60,13 @@
 !-----------------------------------------------------------------------
    hmelt       = -0.15     !  maximum melting at the bottom
-   hiccrit     = 0.1 , 0.1 !  ice thickness for lateral accretion in the Northern (Southern) Hemisphere
+   hiccrit     = 0.1       !  ice thickness for lateral accretion 
                            !         caution 1.0, 1.0 best value to be used!!! (gilles G.)  ????
-   fraz_swi    = 0.0       !  use of frazil ice collection thickness in function of wind (1.0) or not (0.0)
+   fraz_swi    = 0         !  use of frazil ice collection thickness in function of wind (1.0) or not (0.0)
    maxfrazb    = 0.0       !  maximum portion of frazil ice collecting at the ice bottom
    vfrazb      = 0.4166667 !  thresold drift speed for frazil ice collecting at the ice bottom
    Cfrazb      = 5.0       !  squeezing coefficient for frazil ice collecting at the ice bottom
-   hicmin      = 0.2       !  ice thickness corr. to max. energy stored in brine pocket
    hiclim      = 0.10      !  minimum ice thickness
-   sbeta       = 1.        !  numerical caracteritic of the scheme for diffusion in ice
-                           !        Cranck-Nicholson (=0.5), implicit (=1), explicit (=0)
-   parlat      = 0.0       !  percentage of energy used for lateral ablation
-   hakspl      = 0.25      !  slope of distr. for Hakkinen-Mellor's lateral melting
-   hibspl      = 0.5       !  slope of distribution for Hibler's lateral melting
-   exld        = 2.0       !  exponent for leads-closure rate
-   hakdif      = 1.0       !  coefficient for diffusions of ice and snow
-   thth        = 0.2       !  threshold thickness for comp. of eq. thermal conductivity
    hnzst       = 0.1       !  thickness of the surf. layer in temp. computation
    parsub      = 1.0       !  switch for snow sublimation or not
-   alphs       = 1.0       !  coefficient for snow density when snow ice formation
    betas       = 0.6       !  exponent in lead-ice fractionation of snow precipitation 0.66
                            !        betas = 1 -> equipartition, betas < 1 -> more on leads
@@ -124,11 +105,9 @@
    astar            =   0.05 !  equivalent of gstar (0.05 for TH75 and 0.03 for weaker ice)
    Hstar            = 100.0  !  parameter determining the maximum thickness of ridged ice
-   raftswi          =   1    !  rafting or not
+   raft_swi         =   1    !  rafting or not
    hparmeter        =   0.75 !  threshold thickness for rafting or not
    Craft            =   5.0  !  coefficient used in the rafting function
    ridge_por        =   0.3  !  initial porosity of the ridged ice (typically 0.30)
-   sal_max_ridge    =  15.0  !  maximum ridged ice salinity
    partfun_swi      =   1    !  participation function linear, TH75 (0) or exponential Letal07 (1)
-   transfun_swi     =   0    !  transfer function uniform of H80 (0) or exponential Letal07 (1)
    brinstren_swi    =   0    !  (1) use brine volume to diminish ice strength
 /
@@ -144,58 +123,4 @@
 !&namicehsb       !  Heat and salt budgets 
 !!-----------------------------------------------------------------------
-!
 !/
-!-----------------------------------------------------------------------
-&namiceout     !   parameters for outputs
-!-----------------------------------------------------------------------
-   noumef      =   43      !  number of fields
-   add_diag_swi=    1      !  1 -> diagnose distribution in thickness space
-                           !  0 -> only simple diagnostics
-!
-!           !         title of the field           !  name     !   units   !  save  ! multipl. ! additive !
-!           !                                      !           !           ! or not !  factor  !  factor  !
-   field_1  = 'Ice concentration                  ', 'iiceconc', '%       ',    1   ,  1.0     ,    0.0
-   field_2  = 'Ice thickness                      ', 'iicethic', 'm       ',    1   ,  1.0     ,    0.0
-   field_3  = 'Snow thickness                     ', 'isnowthi', 'm       ',    1   ,  1.0     ,    0.0
-   field_4  = 'Daily bottom thermo ice production ', 'iicebopr', 'km3/day ',    1   , 1.0e-9   ,    0.0
-   field_5  = 'Daily dynamic ice production       ', 'iicedypr', 'km3/day ',    1   , 1.0e-9   ,    0.0
-   field_6  = 'Oceanic flux at the ice base       ', 'ioceflxb', 'w/m2    ',    1   ,  1.0     ,    0.0
-   field_7  = 'Ice velocity u                     ', 'iicevelu', 'm/s     ',    1   ,  1.0     ,    0.0
-   field_8  = 'Ice velocity v                     ', 'iicevelv', 'm/s     ',    1   ,  1.0     ,    0.0
-   field_9  = 'Sea surface temperature            ', 'isstempe', 'C       ',    1   ,  1.0     , -273.15
-   field_10 = 'Sea surface salinity               ', 'isssalin', 'PSU     ',    1   ,  1.0     ,    0.0
-   field_11 = 'Total flux at ocean surface        ', 'iocetflx', 'w/m2    ',    1   ,  1.0     ,    0.0
-   field_12 = 'Solar flux at ocean surface        ', 'iocesflx', 'w/m2    ',    1   ,  1.0     ,    0.0
-   field_13 = 'Non-solar flux at ocean surface    ', 'iocwnsfl', 'w/m2    ',    1   ,  1.0     ,    0.0
-   field_14 = 'Heat flux due to brine release     ', 'iocehebr', 'w/m2    ',    1   ,  1.0     ,    0.0
-   field_15 = 'Wind stress u                      ', 'iocestru', 'Pa      ',    1   ,  1.0     ,    0.0
-   field_16 = 'Wind stress v                      ', 'iocestrv', 'Pa      ',    1   ,  1.0     ,    0.0 
-   field_17 = 'Solar flux at ice/ocean surface    ', 'iicesflx', 'w/m2    ',    1   ,  1.0     ,    0.0
-   field_18 = 'Non-solar flux at ice/ocean surface', 'iicenflx', 'w/m2    ',    1   ,  1.0     ,    0.0
-   field_19 = 'Snow precipitation                 ', 'isnowpre', 'kg/m2/d ',    1   ,  1.0     ,    0.0
-   field_20 = 'Mean ice salinity                  ', 'iicesali', 'psu     ',    1   ,  1.0     ,    0.0
-   field_21 = 'Mean ice age                       ', 'iiceages', 'years   ',    1   ,  0.002739,    0.0
-   field_22 = 'Daily lateral thermo ice prod.     ', 'iicelapr', 'km3/day ',    1   ,1.0e-9    ,    0.0
-   field_23 = 'Daily snowice ice production       ', 'iicesipr', 'km3/day ',    1   ,1.0e-9    ,    0.0
-   field_24 = 'Mean ice temperature               ', 'iicetemp', 'C       ',    1   ,  1.0     , -273.15
-   field_25 = 'Ice total heat content             ', 'iiceheco', '10^9 J  ',    1   ,  1.0     ,    0.0
-   field_26 = 'Ice surface temperature            ', 'iicesurt', 'C       ',    1   ,  1.0     , -273.15
-   field_27 = 'Snow temperature                   ', 'isnotem2', 'C       ',    1   ,  1.0     , -273.15
-   field_28 = 'Fsbri - brine salt flux            ', 'iicefsbr', 'kg/m2/d ',    1   ,  1.0     ,    0.0
-   field_29 = 'Fseqv - equivalent FW salt flux    ', 'iicefseq', 'kg/m2/d ',    1   ,  1.0     ,    0.0
-   field_30 = 'Brine volume                       ', 'ibrinvol', '%       ',    1   ,  100.0   ,    0.0
-   field_31 = 'Frazil ice collection thickness    ', 'iicecolf', 'm       ',    1   ,  1.0     ,    0.0
-   field_32 = 'Ice strength                       ', 'iicestre', 'N/m     ',    1   ,  0.001   ,    0.0
-   field_33 = 'Ice velocity                       ', 'iicevelo', 'm/s     ',    1   ,  1.0     ,    0.0
-   field_34 = 'Surface melt                       ', 'iicesume', 'km3/day ',    1   ,1.0e-9    ,    0.0
-   field_35 = 'Bottom melt                        ', 'iicebome', 'km3/day ',    1   ,1.0e-9    ,    0.0
-   field_36 = 'Divergence                         ', 'iicedive', '10-8s-1 ',    1   ,  1.0e8   ,    0.0
-   field_37 = 'Shear                              ', 'iiceshea', '10-8s-1 ',    1   ,  1.0e8   ,    0.0
-   field_38 = 'Daily resultant ice prod/melt      ', 'iicerepr', 'km3/day ',    1   ,  1.0e-9  ,    0.0
-   field_39 = 'Ice volume                         ', 'iicevolu', 'km3     ',    1   ,  1.0e-9  ,    0.0
-   field_40 = 'Snow volume                        ', 'isnowvol', 'km3     ',    1   ,  1.0e-9  ,    0.0
-   field_41 = 'Fsrpo - salt flux from ridg/raft   ', 'iicefsrp', 'kg/m2/d ',    1   ,  1.0     ,    0.0
-   field_42 = 'Fsres - salt flux from limupdate   ', 'iicefsre', 'kg/m2/d ',    1   ,  1.0     ,    0.0
-   field_43 = 'Ice volume transport               ', 'iicevtrp', 'km3/day ',    1   ,1.0e-9    ,    0.0
-/ 
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/namelist_ref
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/namelist_ref	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/SHARED/namelist_ref	(revision 5075)
@@ -1,5 +1,5 @@
 !!>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-!! NEMO/OPA  :  1 - run manager      (namrun, namcfg)
-!! namelists    2 - Domain           (namzgr, namzgr_sco, namdom, namtsd)
+!! NEMO/OPA  :  1 - run manager      (namrun)
+!! namelists    2 - Domain           (namcfg, namzgr, namzgr_sco, namdom, namtsd)
 !!              3 - Surface boundary (namsbc, namsbc_ana, namsbc_flx, namsbc_clio, namsbc_core, namsbc_sas
 !!                                    namsbc_cpl, namtra_qsr, namsbc_rnf,
@@ -18,5 +18,5 @@
 !!                   ***  Run management namelists  ***
 !!======================================================================
-!!   namrun        parameters of the run
+!!   namrun       parameters of the run
 !!======================================================================
 !
@@ -32,6 +32,6 @@
    nn_leapy    =       0   !  Leap year calendar (1) or not (0)
    ln_rstart   = .false.   !  start from rest (F) or from a restart file (T)
-   nn_euler    =       1   !  = 0 : start with forward time step if ln_rstart=.true.
-   nn_rstctl   =       0   !  restart control => activated only if ln_rstart = T
+   nn_euler    =       1   !  = 0 : start with forward time step if ln_rstart=T
+   nn_rstctl   =       0   !  restart control ==> activated only if ln_rstart=T
                            !    = 0 nn_date0 read in namelist ; nn_it000 : read in namelist
                            !    = 1 nn_date0 read in namelist ; nn_it000 : check consistancy between namelist and restart
@@ -48,9 +48,19 @@
 /
 !
-!-----------------------------------------------------------------------
-&namcfg     !   default parameters of the configuration      
+!!======================================================================
+!!                      ***  Domain namelists  ***
+!!======================================================================
+!!   namcfg       parameters of the configuration      
+!!   namzgr       vertical coordinate
+!!   namzgr_sco   s-coordinate or hybrid z-s-coordinate
+!!   namdom       space and time domain (bathymetry, mesh, timestep)
+!!   namtsd       data: temperature & salinity
+!!======================================================================
+!
+!-----------------------------------------------------------------------
+&namcfg     !   parameters of the configuration      
 !-----------------------------------------------------------------------
    cp_cfg      =  "default"            !  name of the configuration
-   cp_cfz      =         ''            !  name of the zoom of configuration
+   cp_cfz      =  "no zoom"            !  name of the zoom of configuration
    jp_cfg      =       0               !  resolution of the configuration
    jpidta      =      10               !  1st lateral dimension ( >= jpi )
@@ -58,5 +68,5 @@
    jpkdta      =      31               !  number of levels      ( >= jpk )
    jpiglo      =      10               !  1st dimension of global domain --> i =jpidta
-   jpjglo      =      12               !  2nd    -                  -    --> j  =jpjdta
+   jpjglo      =      12               !  2nd    -                  -    --> j =jpjdta
    jpizoom     =       1               !  left bottom (i,j) indices of the zoom
    jpjzoom     =       1               !  in data domain indices
@@ -68,13 +78,4 @@
                                        !  = 6 cyclic East-West AND North fold F-point pivot
 /
-!!======================================================================
-!!                      ***  Domain namelists  ***
-!!======================================================================
-!!   namzgr       vertical coordinate
-!!   namzgr_sco   s-coordinate or hybrid z-s-coordinate
-!!   namdom       space and time domain (bathymetry, mesh, timestep)
-!!   namtsd       data: temperature & salinity
-!!======================================================================
-!
 !-----------------------------------------------------------------------
 &namzgr        !   vertical coordinate
@@ -83,4 +84,5 @@
    ln_zps      = .true.    !  z-coordinate - partial steps   (T/F)
    ln_sco      = .false.   !  s- or hybrid z-s-coordinate    (T/F)
+   ln_isfcav   = .false.   !  ice shelf cavity
 /
 !-----------------------------------------------------------------------
@@ -184,4 +186,11 @@
 /
 !-----------------------------------------------------------------------
+&namc1d        !   1D configuration options                             ("key_c1d")
+!-----------------------------------------------------------------------
+   rn_lat1d    =      50   !  Column latitude (default at PAPA station)
+   rn_lon1d    =    -145   !  Column longitude (default at PAPA station)
+   ln_c1d_locpt=  .true.   ! Localization of 1D config in a grid (T) or independant point (F)
+/
+!-----------------------------------------------------------------------
 &namtsd    !   data : Temperature  & Salinity
 !-----------------------------------------------------------------------
@@ -209,4 +218,5 @@
 !!   namtra_qsr      penetrative solar radiation
 !!   namsbc_rnf      river runoffs
+!!   namsbc_isf      ice shelf melting/freezing
 !!   namsbc_apr      Atmospheric Pressure
 !!   namsbc_ssr      sea surface restoring term (for T and/or S)
@@ -224,14 +234,18 @@
    ln_blk_core = .true.    !  CORE bulk formulation                     (T => fill namsbc_core)
    ln_blk_mfs  = .false.   !  MFS bulk formulation                      (T => fill namsbc_mfs )
-   ln_cpl      = .false.   !  Coupled formulation                       (T => fill namsbc_cpl )
    ln_apr_dyn  = .false.   !  Patm gradient added in ocean & ice Eqs.   (T => fill namsbc_apr )
    nn_ice      = 2         !  =0 no ice boundary condition   ,
                            !  =1 use observed ice-cover      ,
-                           !  =2 ice-model used                         ("key_lim3" or "key_lim2)
+                           !  =2 ice-model used                         ("key_lim3" or "key_lim2")
    nn_ice_embd = 1         !  =0 levitating ice (no mass exchange, concentration/dilution effect)
                            !  =1 levitating ice with mass and salt exchange but no presure effect
                            !  =2 embedded sea-ice (full salt and mass exchanges and pressure)
    ln_dm2dc    = .false.   !  daily mean to diurnal cycle on short wave
-   ln_rnf      = .true.    !  runoffs                                   (T => fill namsbc_rnf)
+   ln_rnf      = .true.    !  runoffs                                   (T   => fill namsbc_rnf)
+   nn_isf      = 0         !  ice shelf melting/freezing                (/=0 => fill namsbc_isf)
+                           !  0 =no isf                  1 = presence of ISF 
+                           !  2 = bg03 parametrisation   3 = rnf file for isf   
+                           !  4 = ISF fwf specified
+                           !  option 1 and 4 need ln_isfcav = .true. (domzgr)
    ln_ssr      = .true.    !  Sea Surface Restoring on T and/or S       (T => fill namsbc_ssr)
    nn_fwb      = 2         !  FreshWater Budget: =0 unchecked
@@ -241,5 +255,11 @@
    ln_cdgw = .false.       !  Neutral drag coefficient read from wave model (T => fill namsbc_wave)
    ln_sdw  = .false.       !  Computation of 3D stokes drift                (T => fill namsbc_wave)
-   cn_iceflx = 'linear'    !  redistribution of solar input into ice categories during coupling ice/atm.
+   nn_lsm  = 0             !  =0 land/sea mask for input fields is not applied (keep empty land/sea mask filename field) ,
+                           !  =1:n number of iterations of land/sea mask application for input fields (fill land/sea mask filename field)
+   nn_limflx = -1          !  LIM3 Multi-category heat flux formulation (use -1 if LIM3 is not used)
+                           !  =-1  Use per-category fluxes, bypass redistributor, forced mode only, not yet implemented coupled
+                           !  = 0  Average per-category fluxes (forced and coupled mode)
+                           !  = 1  Average and redistribute per-category fluxes, forced mode only, not yet implemented coupled
+                           !  = 2  Redistribute a single flux over categories (coupled mode only)
 /
 !-----------------------------------------------------------------------
@@ -297,9 +317,7 @@
 
    cn_dir      = './'      !  root directory for the location of the bulk files
-   ln_2m       = .false.   !  air temperature and humidity referenced at 2m (T) instead 10m (F)
    ln_taudif   = .false.   !  HF tau contribution: use "mean of stress module - module of the mean stress" data
-   ln_bulk2z   = .false.   !  Air temperature/humidity and wind vectors are referenced at heights rn_zqt and rn_zu
-   rn_zqt      = 3.        !  Air temperature and humidity reference height (m) (ln_bulk2z)
-   rn_zu       = 4.        !  Wind vector reference height (m)                  (ln_bulk2z)
+   rn_zqt      = 10.        !  Air temperature and humidity reference height (m)
+   rn_zu       = 10.        !  Wind vector reference height (m)                 
    rn_pfac     = 1.        !  multiplicative factor for precipitation (total & snow)
    rn_efac     = 1.        !  multiplicative factor for evaporation (0. or 1.)
@@ -328,20 +346,24 @@
 !                    !                       ! categories !  reference  !    orientation       ! grids  !
 ! send
-sn_snd_temp   =       'weighted oce and ice' ,    'no'    ,     ''      ,         ''           ,   ''
-sn_snd_alb    =       'weighted ice'         ,    'no'    ,     ''      ,         ''           ,   ''
-sn_snd_thick  =       'none'                 ,    'no'   ,     ''      ,         ''           ,   ''
-sn_snd_crt    =       'none'                 ,    'no'    , 'spherical' , 'eastward-northward' ,  'T'
-sn_snd_co2    =       'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_temp   =       'weighted oce and ice' ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_alb    =       'weighted ice'         ,    'no'    ,     ''      ,         ''           ,   ''
+   sn_snd_thick  =       'none'                 ,    'no'   ,     ''      ,         ''           ,   ''
+   sn_snd_crt    =       'none'                 ,    'no'    , 'spherical' , 'eastward-northward' ,  'T'
+   sn_snd_co2    =       'coupled'              ,    'no'    ,     ''      ,         ''           ,   ''
 ! receive
-sn_rcv_w10m   =       'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_taumod =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_tau    =       'oce only'             ,    'no'    , 'cartesian' , 'eastward-northward',  'U,V'
-sn_rcv_dqnsdt =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_qsr    =       'oce and ice'          ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_qns    =       'oce and ice'          ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_emp    =       'conservative'         ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_rnf    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_cal    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
-sn_rcv_co2    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_w10m   =       'none'                 ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_taumod =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_tau    =       'oce only'             ,    'no'    , 'cartesian' , 'eastward-northward',  'U,V'
+   sn_rcv_dqnsdt =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_qsr    =       'oce and ice'          ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_qns    =       'oce and ice'          ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_emp    =       'conservative'         ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_rnf    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_cal    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+   sn_rcv_co2    =       'coupled'              ,    'no'    ,     ''      ,         ''          ,   ''
+!
+   nn_cplmodel   =     1     !  Maximum number of models to/from which NEMO is potentialy sending/receiving data
+   ln_usecplmask = .false.   !  use a coupling mask file to merge data received from several models
+                             !   -> file cplmask.nc with the float variable called cplmask (jpi,jpj,nn_cplmodel)
 /
 !-----------------------------------------------------------------------
@@ -397,4 +419,34 @@
    ln_rnf_tem   = .false.   !  read in temperature information for runoff
    ln_rnf_sal   = .false.   !  read in salinity information for runoff
+/
+!-----------------------------------------------------------------------
+&namsbc_isf    !  Top boundary layer (ISF) 
+!-----------------------------------------------------------------------
+!              ! file name ! frequency (hours) ! variable ! time interpol. !  clim   ! 'yearly'/ ! weights  ! rotation !
+!              !           !  (if <0  months)  !   name   !    (logical)   !  (T/F)  ! 'monthly' ! filename ! pairing  !
+! nn_isf == 4
+   sn_qisf      = 'rnfisf' ,         -12      ,'sohflisf',    .false.      , .true.  , 'yearly'  ,  ''      ,   ''
+   sn_fwfisf    = 'rnfisf' ,         -12      ,'sowflisf',    .false.      , .true.  , 'yearly'  ,  ''      ,   ''
+! nn_isf == 3
+   sn_rnfisf    = 'runoffs' ,         -12      ,'sofwfisf',    .false.      , .true.  , 'yearly'  ,  ''      ,   ''
+! nn_isf == 2 and 3
+   sn_depmax_isf = 'runoffs' ,       -12        ,'sozisfmax' ,   .false.  , .true.  , 'yearly'  ,  ''      ,   ''
+   sn_depmin_isf = 'runoffs' ,       -12        ,'sozisfmin' ,   .false.  , .true.  , 'yearly'  ,  ''      ,   ''
+! nn_isf == 2
+   sn_Leff_isf = 'rnfisf' ,       0          ,'Leff'         ,   .false.  , .true.  , 'yearly'  ,  ''      ,   ''
+! for all case
+   ln_divisf   = .true.  ! apply isf melting as a mass flux or in the salinity trend. (maybe I should remove this option as for runoff?)
+! only for nn_isf = 1 or 2
+   rn_gammat0  = 1.0e-4   ! gammat coefficient used in blk formula
+   rn_gammas0  = 1.0e-4   ! gammas coefficient used in blk formula
+! only for nn_isf = 1
+   nn_isfblk   =  1       ! 1 ISOMIP ; 2 conservative (3 equation formulation, Jenkins et al. 1991 ??)
+   rn_hisf_tbl =  30.      ! thickness of the top boundary layer           (Losh et al. 2008)
+                          ! 0 => thickness of the tbl = thickness of the first wet cell
+   ln_conserve = .true.   ! conservative case (take into account meltwater advection)
+   nn_gammablk = 1        ! 0 = cst Gammat (= gammat/s)
+                          ! 1 = velocity dependend Gamma (u* * gammat/s)  (Jenkins et al. 2010)
+                          !     if you want to keep the cd as in global config, adjust rn_gammat0 to compensate
+                          ! 2 = velocity and stability dependent Gamma    Holland et al. 1999
 /
 !-----------------------------------------------------------------------
@@ -560,4 +612,11 @@
     nn_tra_dta    =  0                    !  = 0, bdy data are equal to the initial state
                                           !  = 1, bdy data are read in 'bdydata   .nc' files
+    cn_ice_lim      =  'none'             !  
+    nn_ice_lim_dta  =  0                  !  = 0, bdy data are equal to the initial state
+                                          !  = 1, bdy data are read in 'bdydata   .nc' files
+    rn_ice_tem      = 270.                !  lim3 only: arbitrary temperature of incoming sea ice
+    rn_ice_sal      = 10.                 !  lim3 only:      --   salinity           --
+    rn_ice_age      = 30.                 !  lim3 only:      --   age                --
+
     ln_tra_dmp    =.false.                !  open boudaries conditions for tracers
     ln_dyn3d_dmp  =.false.                !  open boundary condition for baroclinic velocities
@@ -580,4 +639,12 @@
    bn_tem  =    'amm12_bdyT_tra' ,         24        , 'votemper' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
    bn_sal  =    'amm12_bdyT_tra' ,         24        , 'vosaline' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
+! for lim2
+!   bn_frld  =    'amm12_bdyT_ice' ,         24        , 'ileadfra' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
+!   bn_hicif =    'amm12_bdyT_ice' ,         24        , 'iicethic' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
+!   bn_hsnif =    'amm12_bdyT_ice' ,         24        , 'isnowthi' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
+! for lim3
+!   bn_a_i  =    'amm12_bdyT_ice' ,         24        , 'ileadfra' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
+!   bn_ht_i =    'amm12_bdyT_ice' ,         24        , 'iicethic' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
+!   bn_ht_s =    'amm12_bdyT_ice' ,         24        , 'isnowthi' ,     .true.     , .false. ,  'daily'  ,    ''    ,   ''     , ''
    cn_dir  =    'bdydta/'
    ln_full_vel = .false.
@@ -608,8 +675,16 @@
    rn_bfeb2    =    2.5e-3 !  bottom turbulent kinetic energy background  (m2/s2)
    rn_bfrz0    =    3.e-3  !  bottom roughness [m] if ln_loglayer=T 
-   ln_loglayer = .false.   !  logarithmic formulation (non linear case)
    ln_bfr2d    = .false.   !  horizontal variation of the bottom friction coef (read a 2D mask file )
    rn_bfrien   =    50.    !  local multiplying factor of bfr (ln_bfr2d=T)
+   rn_tfri1    =    4.e-4  !  top drag coefficient (linear case)
+   rn_tfri2    =    2.5e-3 !  top drag coefficient (non linear case). Minimum coeft if ln_loglayer=T
+   rn_tfri2_max =   1.e-1  !  max. top drag coefficient (non linear case and ln_loglayer=T)
+   rn_tfeb2    =    0.0    !  top turbulent kinetic energy background  (m2/s2)
+   rn_tfrz0    =    3.e-3  !  top roughness [m] if ln_loglayer=T
+   ln_tfr2d    = .false.   !  horizontal variation of the top friction coef (read a 2D mask file )
+   rn_tfrien   =    50.    !  local multiplying factor of tfr (ln_tfr2d=T)
+
    ln_bfrimp   = .true.    !  implicit bottom friction (requires ln_zdfexp = .false. if true)
+   ln_loglayer = .false.   !  logarithmic formulation (non linear case)
 /
 !-----------------------------------------------------------------------
@@ -636,4 +711,5 @@
 !!   nameos        equation of state
 !!   namtra_adv    advection scheme
+!!   namtra_adv_mle   mixed layer eddy param. (Fox-Kemper param.)
 !!   namtra_ldf    lateral diffusion scheme
 !!   namtra_dmp    T & S newtonian damping
@@ -643,21 +719,31 @@
 &nameos        !   ocean physical parameters
 !-----------------------------------------------------------------------
-   nn_eos      =   0       !  type of equation of state and Brunt-Vaisala frequency
-                           !     = 0, UNESCO (formulation of Jackett and McDougall (1994) and of McDougall (1987) )
-                           !     = 1, linear: rho(T)   = rau0 * ( 1.028 - ralpha * T )
-                           !     = 2, linear: rho(T,S) = rau0 * ( rbeta * S - ralpha * T )
-   rn_alpha    =   2.0e-4  !  thermal expension coefficient (nn_eos= 1 or 2)
-   rn_beta     =   7.7e-4  !  saline  expension coefficient (nn_eos= 2)
+   nn_eos      =  -1     !  type of equation of state and Brunt-Vaisala frequency
+                                 !  =-1, TEOS-10 
+                                 !  = 0, EOS-80 
+                                 !  = 1, S-EOS   (simplified eos)
+   ln_useCT    = .true.  ! use of Conservative Temp. ==> surface CT converted in Pot. Temp. in sbcssm
+   !                             !
+   !                     ! S-EOS coefficients :
+   !                             !  rd(T,S,Z)*rau0 = -a0*(1+.5*lambda*dT+mu*Z+nu*dS)*dT+b0*dS
+   rn_a0       =  1.6550e-1      !  thermal expension coefficient (nn_eos= 1)
+   rn_b0       =  7.6554e-1      !  saline  expension coefficient (nn_eos= 1)
+   rn_lambda1  =  5.9520e-2      !  cabbeling coeff in T^2  (=0 for linear eos)
+   rn_lambda2  =  7.4914e-4      !  cabbeling coeff in S^2  (=0 for linear eos)
+   rn_mu1      =  1.4970e-4      !  thermobaric coeff. in T (=0 for linear eos)
+   rn_mu2      =  1.1090e-5      !  thermobaric coeff. in S (=0 for linear eos)
+   rn_nu       =  2.4341e-3      !  cabbeling coeff in T*S  (=0 for linear eos)
 /
 !-----------------------------------------------------------------------
 &namtra_adv    !   advection scheme for tracer
 !-----------------------------------------------------------------------
-   ln_traadv_cen2   =  .false.  !  2nd order centered scheme
-   ln_traadv_tvd    =  .true.   !  TVD scheme
-   ln_traadv_muscl  =  .false.  !  MUSCL scheme
-   ln_traadv_muscl2 =  .false.  !  MUSCL2 scheme + cen2 at boundaries
-   ln_traadv_ubs    =  .false.  !  UBS scheme
-   ln_traadv_qck    =  .false.  !  QUICKEST scheme
-   ln_traadv_msc_ups=  .false.  !  use upstream scheme within muscl
+   ln_traadv_cen2   =  .false.   !  2nd order centered scheme
+   ln_traadv_tvd    =  .true.    !  TVD scheme
+   ln_traadv_muscl  =  .false.   !  MUSCL scheme
+   ln_traadv_muscl2 =  .false.   !  MUSCL2 scheme + cen2 at boundaries
+   ln_traadv_ubs    =  .false.   !  UBS scheme
+   ln_traadv_qck    =  .false.   !  QUICKEST scheme
+   ln_traadv_msc_ups=  .false.   !  use upstream scheme within muscl
+   ln_traadv_tvd_zts=  .false.  !  TVD scheme with sub-timestepping of vertical tracer advection
 /
 !-----------------------------------------------------------------------
@@ -734,4 +820,5 @@
    ln_dynadv_cen2= .false. !  flux form - 2nd order centered scheme
    ln_dynadv_ubs = .false. !  flux form - 3rd order UBS      scheme
+   ln_dynzad_zts = .false. !  Use (T) sub timestepping for vertical momentum advection
 /
 !-----------------------------------------------------------------------
@@ -756,4 +843,5 @@
    ln_dynvor_mix = .false. !  mixed scheme
    ln_dynvor_een = .true.  !  energy & enstrophy scheme
+   ln_dynvor_een_old = .false.  !  energy & enstrophy scheme - original formulation
 /
 !-----------------------------------------------------------------------
@@ -915,7 +1003,10 @@
 !!                  ***  Miscellaneous namelists  ***
 !!======================================================================
+!!   namsol            elliptic solver / island / free surface
 !!   nammpp            Massively Parallel Processing                    ("key_mpp_mpi)
 !!   namctl            Control prints & Benchmark
-!!   namsol            elliptic solver / island / free surface
+!!   namc1d            1D configuration options                         ("key_c1d")
+!!   namc1d_uvd        data: U & V currents                             ("key_c1d")
+!!   namc1d_dyndmp     U & V newtonian damping                          ("key_c1d")
 !!======================================================================
 !
@@ -960,10 +1051,4 @@
 /
 !-----------------------------------------------------------------------
-&namc1d        !   1D configuration options                             ("key_c1d")
-!-----------------------------------------------------------------------
-   rn_lat      =    50     !  Column latitude
-   rn_lon      =    -145   !  Column longitude
-/
-!-----------------------------------------------------------------------
 &namc1d_uvd    !   data: U & V currents                                 ("key_c1d")
 !-----------------------------------------------------------------------
@@ -982,9 +1067,10 @@
    ln_dyndmp   =  .false.  !  add a damping term (T) or not (F)
 /
+
 !!======================================================================
 !!                  ***  Diagnostics namelists  ***
 !!======================================================================
 !!   namnc4       netcdf4 chunking and compression settings             ("key_netcdf4")
-!!   namtrd       dynamics and/or tracer trends                         ("key_trddyn","key_trdtra","key_trdmld")
+!!   namtrd       dynamics and/or tracer trends
 !!   namflo       float parameters                                      ("key_float")
 !!   namptr       Poleward Transport Diagnostics
@@ -1004,15 +1090,24 @@
 /
 !-----------------------------------------------------------------------
-&namtrd        !   diagnostics on dynamics and/or tracer trends         ("key_trddyn" and/or "key_trdtra")
-!              !       or mixed-layer trends or barotropic vorticity    ("key_trdmld" or     "key_trdvor")
-!-----------------------------------------------------------------------
-   nn_trd      = 365       !  time step frequency dynamics and tracers trends
-   nn_ctls     =   0       !  control surface type in mixed-layer trends (0,1 or n<jpk)
-   rn_ucf      =   1.      !  unit conversion factor (=1 -> /seconds ; =86400. -> /day)
-   cn_trdrst_in      = "restart_mld"   ! suffix of ocean restart name (input)
-   cn_trdrst_out     = "restart_mld"   ! suffix of ocean restart name (output)
-   ln_trdmld_restart = .false.         !  restart for ML diagnostics
-   ln_trdmld_instant = .false.         !  flag to diagnose trends of instantantaneous or mean ML T/S
-/
+&namtrd        !   diagnostics on dynamics and/or tracer trends
+!              !       and/or mixed-layer trends and/or barotropic vorticity
+!-----------------------------------------------------------------------
+   ln_glo_trd  = .false.   ! (T) global domain averaged diag for T, T^2, KE, and PE
+   ln_dyn_trd  = .false.   ! (T) 3D momentum trend output
+   ln_dyn_mxl  = .FALSE.   ! (T) 2D momentum trends averaged over the mixed layer (not coded yet)
+   ln_vor_trd  = .FALSE.   ! (T) 2D barotropic vorticity trends (not coded yet)
+   ln_KE_trd   = .false.   ! (T) 3D Kinetic   Energy     trends
+   ln_PE_trd   = .false.   ! (T) 3D Potential Energy     trends
+   ln_tra_trd  = .FALSE.   ! (T) 3D tracer trend output
+   ln_tra_mxl  = .false.   ! (T) 2D tracer trends averaged over the mixed layer (not coded yet)
+   nn_trd      = 365       !  print frequency (ln_glo_trd=T) (unit=time step)
+/
+!!gm   nn_ctls     =   0       !  control surface type in mixed-layer trends (0,1 or n<jpk)
+!!gm   rn_ucf      =   1.      !  unit conversion factor (=1 -> /seconds ; =86400. -> /day)
+!!gm   cn_trdrst_in      = "restart_mld"   ! suffix of ocean restart name (input)
+!!gm   cn_trdrst_out     = "restart_mld"   ! suffix of ocean restart name (output)
+!!gm   ln_trdmld_restart = .false.         !  restart for ML diagnostics
+!!gm   ln_trdmld_instant = .false.         !  flag to diagnose trends of instantantaneous or mean ML T/S
+!!gm
 !-----------------------------------------------------------------------
 &namflo       !   float parameters                                      ("key_float")
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/cfg.txt
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/cfg.txt	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/cfg.txt	(revision 5075)
@@ -1,12 +1,13 @@
 GYRE_PISCES OPA_SRC TOP_SRC
 ORCA2_LIM_CFC_C14b OPA_SRC LIM_SRC_2 NST_SRC TOP_SRC
-GYRE OPA_SRC
 GYRE_XIOS OPA_SRC
-ORCA2_OFF_PISCES OPA_SRC OFF_SRC TOP_SRC
 ORCA2_SAS_LIM OPA_SRC SAS_SRC LIM_SRC_2 NST_SRC
 C1D_PAPA OPA_SRC
+GYRE_BFM OPA_SRC TOP_SRC
+AMM12 OPA_SRC
+ORCA2_LIM_PISCES OPA_SRC LIM_SRC_2 NST_SRC TOP_SRC
+ORCA2_OFF_PISCES OPA_SRC OFF_SRC TOP_SRC
+ISOMIP OPA_SRC
+GYRE OPA_SRC
 ORCA2_LIM3 OPA_SRC LIM_SRC_3 NST_SRC
 ORCA2_LIM OPA_SRC LIM_SRC_2 NST_SRC
-AMM12 OPA_SRC
-GYRE_BFM OPA_SRC TOP_SRC
-ORCA2_LIM_PISCES OPA_SRC LIM_SRC_2 NST_SRC TOP_SRC
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/makenemo
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/makenemo	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/makenemo	(revision 5075)
@@ -38,7 +38,8 @@
 #
 # - NEW_CONF    : configuration to be created
-# - REF_CONF    : reference configuration to build the new one
+# - REF_CONF    : reference configuration to build the new one from
 # - CMP_NAM     : compiler name
 # - NBR_PRC     : number of processes used to compile
+# - USP_CONF    : unsupported (external) configuration to build the new one from
 # - NEM_SUBDIR  : NEMO subdirectory used (specified)
 #
@@ -51,4 +52,9 @@
 # - TOOLS_DIR   :   "    "    "
 # - NEMO_DIR    :   "    "    "
+# - REMOTE_CTL  : URL link to a remote resource list for an external configuration 
+#                 which is not part of the reference suite
+# - LOCAL_REF   : Nearest reference configuration to an external configuration 
+#                 which is not part of the reference suite
+#                 (used to populate work directories if remote access is not available)
 #
 # EXAMPLES
@@ -83,4 +89,5 @@
 x_n="";
 x_r="";
+x_u="";
 x_m="";
 x_t="";
@@ -106,4 +113,6 @@
 export AGRIFUSE=10
 declare -a TAB
+declare -a REMOTE_CTL
+declare -a LOCAL_REF
 list_key=0
 chk_key=1
@@ -114,10 +123,10 @@
 #-
 #- Choice of the options ---
-while getopts :hd:n:r:m:j:e:s:v:t:k: V
+while getopts :hd:n:r:u:m:j:e:s:v:t:k: V
 do
     case $V in
 	(h) x_h=${OPTARG};
         echo "Usage	 : "${b_n} \
-	    " [-h] [-n name] [-m arch] [-d "dir1 dir2"] [-r conf] [-s Path] [-e Path] [-j No] [-v No] [-k 0/1]";
+	    " [-h] [-n name] [-m arch] [-d "dir1 dir2"] [-r conf] [-u conf] [-s Path] [-e Path] [-j No] [-v No] [-k 0/1]";
 	echo " -h	        : help";
 	echo " -h institute : specific help for consortium members";
@@ -126,4 +135,5 @@
 	echo " -d dir       : choose NEMO sub-directories";
 	echo " -r conf      : choose reference configuration";
+	echo " -u conf      : choose an unsupported (external) configuration";
         echo " -s Path      : choose alternative location for NEMO main directory";
         echo " -e Path      : choose alternative location for MY_SRC directory";
@@ -139,4 +149,6 @@
 	echo "Available configurations :"; cat ${CONFIG_DIR}/cfg.txt;
 	echo "";
+        echo "Available unsupported (external) configurations :"; cat ${CONFIG_DIR}/uspcfg.txt;
+	echo "";
 	echo "Example to remove bad configuration ";
 	echo "./makenemo -n MY_CONFIG clean_config";
@@ -161,4 +173,5 @@
 	(n)  x_n=${OPTARG};;
 	(r)  x_r=${OPTARG};;
+	(u)  x_u=${OPTARG};;
 	(m)  x_m=${OPTARG};;
 	(j)  x_j=${OPTARG};;
@@ -187,11 +200,9 @@
 	    ;;
 	add_key)
-	    list_add_key=$2
-	    export ${list_add_key}
+	    test $?2 || ( list_add_key=$2 && export ${list_add_key} )
 	    shift
 	    ;;
 	del_key)
-	    list_del_key=$2
-	    export ${list_del_key}
+	    test $?2 || ( list_del_key=$2 && export ${list_del_key} )
 	    shift
 	    ;;
@@ -220,4 +231,5 @@
 NEM_SUBDIR=${x_d}
 REF_CONF=${x_r}
+USP_CONF=${x_u}
 NEMO_TDIR=${x_t:-$NEMO_TDIR}
 export NEMO_TDIR=${NEMO_TDIR:-$CONFIG_DIR}
@@ -228,4 +240,7 @@
     echo "Available configurations :"
     cat ${CONFIG_DIR}/cfg.txt
+    echo
+    echo "Available unsupported (external) configurations :" 
+    cat ${CONFIG_DIR}/uspcfg.txt
     exit
 fi
@@ -238,6 +253,6 @@
 
 if [ ${#NEW_CONF} -eq 0 ] ; then
-    if [ ${#NEM_SUBDIR} -eq 0 -a ${#REF_CONF} -eq 0 ]; then
-	echo "You are  installing a new configuration"
+    if [ ${#NEM_SUBDIR} -eq 0 ] && [ ${#REF_CONF} -eq 0 ] && [ ${#USP_CONF} -eq 0 ] ; then
+	echo "You are installing a new default (ORCA2_LIM) configuration"
 	ind=0
 	. ${COMPIL_DIR}/Fread_dir.sh OPA_SRC	 YES
@@ -248,6 +263,6 @@
 	. ${COMPIL_DIR}/Fread_dir.sh OFF_SRC	 NO
 	REF_CONF=ORCA2_LIM
-    elif [ ${#NEM_SUBDIR} -gt 0 ] && [ ${#REF_CONF} -eq 0 ]; then
-	echo "You are  installing a new configuration"
+    elif [ ${#NEM_SUBDIR} -gt 0 ] && [ ${#REF_CONF} -eq 0 ] && [ ${#USP_CONF} -eq 0 ] ; then
+	echo "You are  installing a new configuration based on ORCA2_LIM"
 	TAB=( ${NEM_SUBDIR} )
 	REF_CONF=ORCA2_LIM
@@ -255,7 +270,19 @@
 	echo "You are  installing a new configuration based on ${REF_CONF}"
 	. ${COMPIL_DIR}/Fcopy_dir.sh ${REF_CONF}
+    elif [ ${#NEM_SUBDIR} -eq 0 ] && [ ${#USP_CONF} -gt 0 ]; then
+	echo "You are  installing a new configuration based on the unsupported (external) ${USP_CONF}"
+	. ${COMPIL_DIR}/Fcopy_extdir.sh ${USP_CONF}  
+        #echo "TTT " ${TAB}
+        #echo "RRR " ${REMOTE_CTL}
+        #echo "LLL " ${LOCAL_REF}
     fi
     NEW_CONF=${x_n}
-    . ${COMPIL_DIR}/Fmake_config.sh ${NEW_CONF} ${REF_CONF}
+
+    if [ ${#USP_CONF} -gt 0 ]; then
+      . ${COMPIL_DIR}/Fmake_extconfig.sh ${NEW_CONF} ${LOCAL_REF}
+      . ${COMPIL_DIR}/Ffetch_extdir.sh ${NEW_CONF} ${REMOTE_CTL}  
+    else
+      . ${COMPIL_DIR}/Fmake_config.sh ${NEW_CONF} ${REF_CONF}
+    fi
 else
     sed -e "/${NEW_CONF} /d"  ${CONFIG_DIR}/cfg.txt >  ${COMPIL_DIR}/cfg.tmp
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/uspcfg.txt
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/uspcfg.txt	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/CONFIG/uspcfg.txt	(revision 5075)
@@ -0,0 +1,1 @@
+ORCA1_CICE # ORCA2_LIM # OPA_SRC TOP_SRC  # http://gws-access.ceda.ac.uk/public/nemo/uspconfigs/ORCA1_CICE/v3.6.0/ORCA1_CICE_ctl.txt
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/ice_2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/ice_2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/ice_2.F90	(revision 5075)
@@ -57,4 +57,7 @@
    REAL(wp), PUBLIC ::   sangvg, cangvg        !: sin and cos of the turning angle for ocean stress
    REAL(wp), PUBLIC ::   pstarh                !: pstar / 2.0
+
+   !                                !!** switch for presence of ice or not 
+   REAL(wp), PUBLIC ::   rswitch
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ahiu , ahiv   !: hor. diffusivity coeff. at ocean U- and V-points (m2/s)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limhdf_2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limhdf_2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limhdf_2.F90	(revision 5075)
@@ -86,10 +86,8 @@
       zdiv0(:, 1 ) = 0._wp
       zdiv0(:,jpj) = 0._wp
-      IF( .NOT.lk_vopt_loop ) THEN
-         zflu (jpi,:) = 0._wp   
-         zflv (jpi,:) = 0._wp
-         zdiv0(1,  :) = 0._wp
-         zdiv0(jpi,:) = 0._wp
-      ENDIF
+      zflu (jpi,:) = 0._wp   
+      zflv (jpi,:) = 0._wp
+      zdiv0(1,  :) = 0._wp
+      zdiv0(jpi,:) = 0._wp
 
       zconv = 1._wp           !==  horizontal diffusion using a Crant-Nicholson scheme  ==!
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limistate_2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limistate_2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limistate_2.F90	(revision 5075)
@@ -14,5 +14,4 @@
    !!   'key_lim2' :                                  LIM 2.0 sea-ice model
    !!----------------------------------------------------------------------
-   !!----------------------------------------------------------------------
    !!   lim_istate_2      :  Initialisation of diagnostics ice variables
    !!   lim_istate_init_2 :  initialization of ice state and namelist read
@@ -34,6 +33,6 @@
    PUBLIC lim_istate_2      ! routine called by lim_init_2.F90
 
-   !!! **  namelist (namiceini) **
-   LOGICAL  ::   ln_limini   !: Ice initialization state
+   !                        !! **  namelist (namiceini) **
+   LOGICAL  ::   ln_limini   ! Ice initialization state
    REAL(wp) ::   ttest       ! threshold water temperature for initial sea ice
    REAL(wp) ::   hninn       ! initial snow thickness in the north
@@ -51,5 +50,4 @@
    !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
    !!----------------------------------------------------------------------
-
 CONTAINS
 
@@ -71,5 +69,5 @@
       IF( .NOT. ln_limini ) THEN  
          
-         tfu(:,:) = tfreez( tsn(:,:,1,jp_sal) ) * tmask(:,:,1)       ! freezing/melting point of sea water [Celcius]
+         tfu(:,:) = eos_fzp( tsn(:,:,1,jp_sal) ) * tmask(:,:,1)       ! freezing/melting point of sea water [Celcius]
 
          DO jj = 1, jpj
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limsbc_2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limsbc_2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limsbc_2.F90	(revision 5075)
@@ -30,5 +30,4 @@
    USE sbc_oce          ! surface boundary condition: ocean
    USE sbccpl
-   USE cpl_oasis3, ONLY : lk_cpl
    USE oce       , ONLY : sshn, sshb, snwice_mass, snwice_mass_b, snwice_fmass 
    USE albedo           ! albedo parameters
@@ -37,5 +36,4 @@
    USE wrk_nemo         ! work arrays
    USE in_out_manager   ! I/O manager
-   USE diaar5, ONLY :   lk_diaar5
    USE iom              ! I/O library
    USE prtctl           ! Print control
@@ -97,9 +95,7 @@
       !!              - emp     : freshwater budget: mass flux 
       !!              - sfx     : freshwater budget: salt flux due to Freezing/Melting
-      !!              - utau    : sea surface i-stress (ocean referential)
-      !!              - vtau    : sea surface j-stress (ocean referential)
       !!              - fr_i    : ice fraction
       !!              - tn_ice  : sea-ice surface temperature
-      !!              - alb_ice : sea-ice alberdo (lk_cpl=T)
+      !!              - alb_ice : sea-ice albedo (lk_cpl=T)
       !!
       !! References : Goosse, H. et al. 1996, Bul. Soc. Roy. Sc. Liege, 65, 87-90.
@@ -183,9 +179,9 @@
 
             !   computation the solar flux at ocean surface
-#if defined key_coupled 
-            zqsr = qsr_tot(ji,jj) + ( fstric(ji,jj) - qsr_ice(ji,jj,1) ) * ( 1.0 - pfrld(ji,jj) )
-#else
-            zqsr = pfrld(ji,jj) * qsr(ji,jj)  + ( 1.  - pfrld(ji,jj) ) * fstric(ji,jj)
-#endif            
+            IF( lk_cpl ) THEN
+               zqsr = qsr_tot(ji,jj) + ( fstric(ji,jj) - qsr_ice(ji,jj,1) ) * ( 1.0 - pfrld(ji,jj) )
+            ELSE
+               zqsr = pfrld(ji,jj) * qsr(ji,jj)  + ( 1.  - pfrld(ji,jj) ) * fstric(ji,jj)
+            ENDIF
             !  computation the non solar heat flux at ocean surface
             zqns    =  - ( 1. - thcm(ji,jj) ) * zqsr                                              &   ! part of the solar energy used in leads
@@ -206,14 +202,14 @@
             !
             ! mass flux at the ocean-atmosphere interface (open ocean fraction = leads area)
-#if defined key_coupled
             !                                                  ! coupled mode: 
-            zemp = + emp_tot(ji,jj)                            &     ! net mass flux over the grid cell (ice+ocean area)
-               &   - emp_ice(ji,jj) * ( 1. - pfrld(ji,jj) )          ! minus the mass flux intercepted by sea-ice
-#else
-            !                                                  ! forced  mode: 
-            zemp = + emp(ji,jj)     *         frld(ji,jj)      &     ! mass flux over open ocean fraction 
-               &   - tprecip(ji,jj) * ( 1. -  frld(ji,jj) )    &     ! liquid precip. over ice reaches directly the ocean
-               &   + sprecip(ji,jj) * ( 1. - pfrld(ji,jj) )          ! snow is intercepted by sea-ice (previous frld)
-#endif            
+            IF( lk_cpl ) THEN
+               zemp = + emp_tot(ji,jj)                            &     ! net mass flux over the grid cell (ice+ocean area)
+                  &   - emp_ice(ji,jj) * ( 1. - pfrld(ji,jj) )          ! minus the mass flux intercepted by sea-ice
+            ELSE
+               !                                                  ! forced  mode: 
+               zemp = + emp(ji,jj)     *         frld(ji,jj)      &     ! mass flux over open ocean fraction 
+                  &   - tprecip(ji,jj) * ( 1. -  frld(ji,jj) )    &     ! liquid precip. over ice reaches directly the ocean
+                  &   + sprecip(ji,jj) * ( 1. - pfrld(ji,jj) )          ! snow is intercepted by sea-ice (previous frld)
+            ENDIF
             !
             ! mass flux at the ocean/ice interface (sea ice fraction)
@@ -245,13 +241,11 @@
       ENDIF
 
-      CALL iom_put( 'hflx_ice_cea', - fdtcn(:,:) )      
-      CALL iom_put( 'qns_io_cea', qns(:,:) - zqnsoce(:,:) * pfrld(:,:) )      
-      CALL iom_put( 'qsr_io_cea', fstric(:,:) * (1.e0 - pfrld(:,:)) )
-
-      IF( lk_diaar5 ) THEN       ! AR5 diagnostics
-         CALL iom_put( 'isnwmlt_cea'  ,                 rdm_snw(:,:) * r1_rdtice )
-         CALL iom_put( 'fsal_virt_cea',   soce_0(:,:) * rdm_ice(:,:) * r1_rdtice )
-         CALL iom_put( 'fsal_real_cea', - sice_0(:,:) * rdm_ice(:,:) * r1_rdtice )
-      ENDIF
+      IF( iom_use('hflx_ice_cea' ) )   CALL iom_put( 'hflx_ice_cea', - fdtcn(:,:) )      
+      IF( iom_use('qns_io_cea'   ) )   CALL iom_put( 'qns_io_cea', qns(:,:) - zqnsoce(:,:) * pfrld(:,:) )      
+      IF( iom_use('qsr_io_cea'   ) )   CALL iom_put( 'qsr_io_cea', fstric(:,:) * (1.e0 - pfrld(:,:)) )
+
+      IF( iom_use('isnwmlt_cea'  ) )   CALL iom_put( 'isnwmlt_cea'  ,                 rdm_snw(:,:) * r1_rdtice )
+      IF( iom_use('fsal_virt_cea') )   CALL iom_put( 'fsal_virt_cea',   soce_0(:,:) * rdm_ice(:,:) * r1_rdtice )
+      IF( iom_use('fsal_real_cea') )   CALL iom_put( 'fsal_real_cea', - sice_0(:,:) * rdm_ice(:,:) * r1_rdtice )
 
       !-----------------------------------------------!
@@ -259,20 +253,18 @@
       !-----------------------------------------------!
 
-#if defined key_coupled
-      tn_ice(:,:,1) = sist(:,:)          ! sea-ice surface temperature       
-      ht_i(:,:,1) = hicif(:,:)
-      ht_s(:,:,1) = hsnif(:,:)
-      a_i(:,:,1) = fr_i(:,:)
-      !                                  ! Computation of snow/ice and ocean albedo
-      CALL albedo_ice( tn_ice, ht_i, ht_s, zalbp, zalb )
-      alb_ice(:,:,1) =  0.5 * ( zalbp(:,:,1) + zalb (:,:,1) )   ! Ice albedo (mean clear and overcast skys)
-      CALL iom_put( "icealb_cea", alb_ice(:,:,1) * fr_i(:,:) )  ! ice albedo
-#endif
+      IF( lk_cpl) THEN
+         tn_ice(:,:,1) = sist(:,:)          ! sea-ice surface temperature       
+         ht_i(:,:,1) = hicif(:,:)
+         ht_s(:,:,1) = hsnif(:,:)
+         a_i(:,:,1) = fr_i(:,:)
+         !                                  ! Computation of snow/ice and ocean albedo
+         CALL albedo_ice( tn_ice, ht_i, ht_s, zalbp, zalb )
+         alb_ice(:,:,1) =  0.5 * ( zalbp(:,:,1) + zalb (:,:,1) )   ! Ice albedo (mean clear and overcast skys)
+         IF( iom_use('icealb_cea' ) )   CALL iom_put( 'icealb_cea', alb_ice(:,:,1) * fr_i(:,:) )  ! ice albedo
+      ENDIF
 
       IF(ln_ctl) THEN            ! control print
          CALL prt_ctl(tab2d_1=qsr   , clinfo1=' lim_sbc: qsr    : ', tab2d_2=qns   , clinfo2=' qns     : ')
          CALL prt_ctl(tab2d_1=emp   , clinfo1=' lim_sbc: emp    : ', tab2d_2=sfx   , clinfo2=' sfx     : ')
-         CALL prt_ctl(tab2d_1=utau  , clinfo1=' lim_sbc: utau   : ', mask1=umask,   &
-            &         tab2d_2=vtau  , clinfo2=' vtau    : '        , mask2=vmask )
          CALL prt_ctl(tab2d_1=fr_i  , clinfo1=' lim_sbc: fr_i   : ', tab2d_2=tn_ice(:,:,1), clinfo2=' tn_ice  : ')
       ENDIF 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limthd_2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limthd_2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limthd_2.F90	(revision 5075)
@@ -33,6 +33,4 @@
    USE limtab_2
    USE prtctl           ! Print control
-   USE cpl_oasis3, ONLY :   lk_cpl
-   USE diaar5    , ONLY :   lk_diaar5
    USE lib_fortran      ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
    
@@ -219,15 +217,15 @@
                         
             !  partial computation of the lead energy budget (qldif)
-#if defined key_coupled 
-            qldif(ji,jj)   = tms(ji,jj) * rdt_ice                                                  &
-               &    * (   ( qsr_tot(ji,jj) - qsr_ice(ji,jj,1) * zfricp ) * ( 1.0 - thcm(ji,jj) )   &
-               &        + ( qns_tot(ji,jj) - qns_ice(ji,jj,1) * zfricp )                           &
-               &        + frld(ji,jj) * ( fdtcn(ji,jj) + ( 1.0 - zindb ) * fsbbq(ji,jj) )   )
-#else
-            qldif(ji,jj)   = tms(ji,jj) * rdt_ice * frld(ji,jj)                    &
-               &                        * (  qsr(ji,jj) * ( 1.0 - thcm(ji,jj) )    &
-               &                           + qns(ji,jj)  +  fdtcn(ji,jj)           &
-               &                           + ( 1.0 - zindb ) * fsbbq(ji,jj)      )
-#endif
+            IF( lk_cpl ) THEN 
+               qldif(ji,jj)   = tms(ji,jj) * rdt_ice                                                  &
+                  &    * (   ( qsr_tot(ji,jj) - qsr_ice(ji,jj,1) * zfricp ) * ( 1.0 - thcm(ji,jj) )   &
+                  &        + ( qns_tot(ji,jj) - qns_ice(ji,jj,1) * zfricp )                           &
+                  &        + frld(ji,jj) * ( fdtcn(ji,jj) + ( 1.0 - zindb ) * fsbbq(ji,jj) )   )
+            ELSE
+               qldif(ji,jj)   = tms(ji,jj) * rdt_ice * frld(ji,jj)                    &
+                  &                        * (  qsr(ji,jj) * ( 1.0 - thcm(ji,jj) )    &
+                  &                           + qns(ji,jj)  +  fdtcn(ji,jj)           &
+                  &                           + ( 1.0 - zindb ) * fsbbq(ji,jj)      )
+            ENDIF
             !  parlat : percentage of energy used for lateral ablation (0.0) 
             zfntlat        = 1.0 - MAX( rzero , SIGN( rone ,  - qldif(ji,jj) ) )
@@ -440,43 +438,55 @@
       !--------------------------------------------------------------------------------
       ztmp(:,:) = 1. - pfrld(:,:)                                ! fraction of ice after the dynamic, before the thermodynamic
-      CALL iom_put( 'ioceflxb', fbif )                           ! Oceanic flux at the ice base           [W/m2 ???]
-      CALL iom_put( 'ist_cea', (sist(:,:) - rt0) * ztmp(:,:) )   ! Ice surface temperature                [Celius]
-      CALL iom_put( 'qsr_ai_cea', qsr_ice(:,:,1) * ztmp(:,:) )   ! Solar flux over the ice                [W/m2]
-      CALL iom_put( 'qns_ai_cea', qns_ice(:,:,1) * ztmp(:,:) )   ! Non-solar flux over the ice            [W/m2]
-      IF( .NOT. lk_cpl )   CALL iom_put( 'qla_ai_cea', qla_ice(:,:,1) * ztmp(:,:) )     ! Latent flux over the ice  [W/m2]
+      IF( iom_use('ist_cea'    ) )   CALL iom_put( 'ist_cea', (sist(:,:) - rt0) * ztmp(:,:) )   ! Ice surface temperature   [Celius]
+      IF( iom_use('qsr_ai_cea' ) )   CALL iom_put( 'qsr_ai_cea', qsr_ice(:,:,1) * ztmp(:,:) )   ! Solar flux over the ice     [W/m2]
+      IF( iom_use('qns_ai_cea' ) )   CALL iom_put( 'qns_ai_cea', qns_ice(:,:,1) * ztmp(:,:) )   ! Non-solar flux over the ice [W/m2]
+      IF( iom_use('qla_ai_cea' ) .AND. .NOT. lk_cpl ) &
+         &                           CALL iom_put( 'qla_ai_cea', qla_ice(:,:,1) * ztmp(:,:) )   ! Latent flux over the ice [W/m2]
       !
-      CALL iom_put( 'snowthic_cea', hsnif  (:,:) * fr_i(:,:) )   ! Snow thickness             [m]
-      CALL iom_put( 'icethic_cea' , hicif  (:,:) * fr_i(:,:) )   ! Ice thickness              [m]
+      IF( iom_use('snowthic_cea'))   CALL iom_put( 'snowthic_cea', hsnif  (:,:) * fr_i(:,:) )   ! Snow thickness           [m]
+      IF( iom_use('icethic_cea' ))   CALL iom_put( 'icethic_cea' , hicif  (:,:) * fr_i(:,:) )   ! Ice thickness            [m]
       zztmp = 1.0 / rdt_ice
-      CALL iom_put( 'iceprod_cea' , hicifp (:,:) * zztmp     )   ! Ice produced               [m/s]
-      IF( lk_diaar5 ) THEN
-         CALL iom_put( 'snowmel_cea' , rdm_snw(:,:) * zztmp     )   ! Snow melt                  [kg/m2/s]
-         zztmp = rhoic / rdt_ice
-         CALL iom_put( 'sntoice_cea' , zdvonif(:,:) * zztmp     )   ! Snow to Ice transformation [kg/m2/s]
-         CALL iom_put( 'ticemel_cea' , zdvosif(:,:) * zztmp     )   ! Melt at Sea Ice top        [kg/m2/s]
-         CALL iom_put( 'bicemel_cea' , zdvomif(:,:) * zztmp     )   ! Melt at Sea Ice bottom     [kg/m2/s]
+      IF( iom_use('iceprod_cea') )   CALL iom_put( 'iceprod_cea' , hicifp (:,:) * zztmp     )   ! Ice produced             [m/s]
+      IF( iom_use('iiceconc'   ) )   CALL iom_put( 'iiceconc'    , fr_i(:,:)                )   ! Ice concentration        [-]
+      IF( iom_use('snowmel_cea') )   CALL iom_put( 'snowmel_cea' , rdm_snw(:,:) * zztmp     )   ! Snow melt                [kg/m2/s]
+      zztmp = rhoic / rdt_ice
+      IF( iom_use('sntoice_cea') )   CALL iom_put( 'sntoice_cea' , zdvonif(:,:) * zztmp     ) ! Snow to Ice transformation [kg/m2/s]
+      IF( iom_use('ticemel_cea') )   CALL iom_put( 'ticemel_cea' , zdvosif(:,:) * zztmp     )   ! Melt at Sea Ice top      [kg/m2/s]
+      IF( iom_use('bicemel_cea') )   CALL iom_put( 'bicemel_cea' , zdvomif(:,:) * zztmp     )   ! Melt at Sea Ice bottom   [kg/m2/s]
+      IF( iom_use('licepro_cea') ) THEN
          zlicegr(:,:) = MAX( 0.e0, rdm_ice(:,:)-zlicegr(:,:) )
-         CALL iom_put( 'licepro_cea' , zlicegr(:,:) * zztmp     )   ! Lateral sea ice growth     [kg/m2/s]
+                                     CALL iom_put( 'licepro_cea' , zlicegr(:,:) * zztmp     )   ! Lateral sea ice growth   [kg/m2/s]
       ENDIF
       !
       ! Compute the Eastward & Northward sea-ice transport
-      zztmp = 0.25 * rhoic
-      DO jj = 1, jpjm1 
-         DO ji = 1, jpim1   ! NO vector opt.
-            ! Ice velocities, volume & transport at U & V-points
-            zuice_m = u_ice(ji+1,jj+1) + u_ice(ji+1,jj )
-            zvice_m = v_ice(ji+1,jj+1) + v_ice(ji ,jj+1)
-            zhice_u = hicif(ji,jj)*e2t(ji,jj)*fr_i(ji,jj) + hicif(ji+1,jj  )*e2t(ji+1,jj  )*fr_i(ji+1,jj  )
-            zhice_v = hicif(ji,jj)*e1t(ji,jj)*fr_i(ji,jj) + hicif(ji  ,jj+1)*e1t(ji  ,jj+1)*fr_i(ji  ,jj+1)
-            zu_imasstr(ji,jj) = zztmp * zhice_u * zuice_m 
-            zv_imasstr(ji,jj) = zztmp * zhice_v * zvice_m 
-         END DO
-      END DO
-      CALL lbc_lnk( zu_imasstr, 'U', -1. )   ;   CALL lbc_lnk( zv_imasstr, 'V', -1. )
-      CALL iom_put( 'u_imasstr',  zu_imasstr(:,:) )   ! Ice transport along i-axis at U-point [kg/s] 
-      CALL iom_put( 'v_imasstr',  zv_imasstr(:,:) )   ! Ice transport along j-axis at V-point [kg/s] 
+      IF( iom_use('u_imasstr') ) THEN
+         zztmp = 0.25 * rhoic
+         DO jj = 1, jpjm1 
+            DO ji = 1, jpim1   ! NO vector opt.
+               ! Ice velocities, volume & transport at U-points
+               zuice_m = u_ice(ji+1,jj+1) + u_ice(ji+1,jj )
+               zhice_u = hicif(ji,jj)*e2t(ji,jj)*fr_i(ji,jj) + hicif(ji+1,jj  )*e2t(ji+1,jj  )*fr_i(ji+1,jj  )
+               zu_imasstr(ji,jj) = zztmp * zhice_u * zuice_m 
+            END DO
+         END DO
+         CALL lbc_lnk( zu_imasstr, 'U', -1. )
+         CALL iom_put( 'u_imasstr',  zu_imasstr(:,:) )   ! Ice transport along i-axis at U-point [kg/s] 
+      ENDIF
+      IF( iom_use('v_imasstr') ) THEN
+         zztmp = 0.25 * rhoic
+         DO jj = 1, jpjm1 
+            DO ji = 1, jpim1   ! NO vector opt.
+               ! Ice velocities, volume & transport at V-points
+               zvice_m = v_ice(ji+1,jj+1) + v_ice(ji ,jj+1)
+               zhice_v = hicif(ji,jj)*e1t(ji,jj)*fr_i(ji,jj) + hicif(ji  ,jj+1)*e1t(ji  ,jj+1)*fr_i(ji  ,jj+1)
+               zv_imasstr(ji,jj) = zztmp * zhice_v * zvice_m 
+            END DO
+         END DO
+         CALL lbc_lnk( zv_imasstr, 'V', -1. )
+         CALL iom_put( 'v_imasstr',  zv_imasstr(:,:) )   ! Ice transport along j-axis at V-point [kg/s]
+      ENDIF
 
       !! Fram Strait sea-ice transport (sea-ice + snow)  (in ORCA2 = 5 points)
-      IF( cp_cfg == "orca" .AND. jp_cfg == 2 ) THEN    ! ORCA R2 configuration
+      IF( iom_use('fram_trans') .and. cp_cfg == "orca" .AND. jp_cfg == 2 ) THEN    ! ORCA R2 configuration
          DO jj = mj0(137), mj1(137) ! B grid
             IF( mj0(jj-1) >= nldj ) THEN
@@ -492,17 +502,19 @@
       ENDIF
 
+      IF( iom_use('ice_pres') .OR. iom_use('ist_ipa') .OR. iom_use('uice_ipa') .OR. iom_use('vice_ipa') ) THEN
 !! ce     ztmp(:,:) = 1. - AINT( frld(:,:), wp )                        ! return 1 as soon as there is ice
 !! ce     A big warning because the model crashes on IDRIS/IBM SP6 with xlf 13.1.0.3, see ticket #761
-!! ce     We Unroll the loop and everything works fine 
-      DO jj = 1, jpj
-         DO ji = 1, jpi
-            ztmp(ji,jj) = 1. - AINT( frld(ji,jj), wp )                ! return 1 as soon as there is ice
-         END DO
-      END DO
-      !
-      CALL iom_put( 'ice_pres'  , ztmp                            )   ! Ice presence                          [-]
-      CALL iom_put( 'ist_ipa'   , ( sist(:,:) - rt0 ) * ztmp(:,:) )   ! Ice surface temperature               [Celius]
-      CALL iom_put( 'uice_ipa'  ,  u_ice(:,:)         * ztmp(:,:) )   ! Ice velocity along i-axis at I-point  [m/s] 
-      CALL iom_put( 'vice_ipa'  ,  v_ice(:,:)         * ztmp(:,:) )   ! Ice velocity along j-axis at I-point  [m/s]
+!! ce     We Unroll the loop and everything works fine      
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ztmp(ji,jj) = 1. - AINT( frld(ji,jj), wp )                ! return 1 as soon as there is ice
+            END DO
+         END DO
+         !
+         IF( iom_use('ice_pres') ) CALL iom_put( 'ice_pres', ztmp                            )   ! Ice presence                 [-]
+         IF( iom_use('ist_ipa' ) ) CALL iom_put( 'ist_ipa' , ( sist(:,:) - rt0 ) * ztmp(:,:) )   ! Ice surface temperature [Celius]
+         IF( iom_use('uice_ipa') ) CALL iom_put( 'uice_ipa', u_ice(:,:) * ztmp(:,:) ) ! Ice velocity along i-axis at I-point  [m/s] 
+         IF( iom_use('vice_ipa') ) CALL iom_put( 'vice_ipa', v_ice(:,:) * ztmp(:,:) ) ! Ice velocity along j-axis at I-point  [m/s]
+      ENDIF
 
       IF(ln_ctl) THEN
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limthd_zdf_2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limthd_zdf_2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limthd_zdf_2.F90	(revision 5075)
@@ -18,5 +18,5 @@
    USE ice_2
    USE limistate_2
-   USE cpl_oasis3, ONLY : lk_cpl
+   USE sbc_oce, ONLY : lk_cpl
    USE in_out_manager
    USE lib_mpp          ! MPP library
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limwri_2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limwri_2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_2/limwri_2.F90	(revision 5075)
@@ -333,5 +333,4 @@
       CALL histdef( kid, "ileadfra", "Ice concentration"       , "-"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
       CALL histdef( kid, "iicetemp", "Ice temperature"         , "K"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "ioceflxb", "flux at ice base"        , "w/m2"   , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
       CALL histdef( kid, "iicevelu", "i-Ice speed (I-point)"   , "m/s"    , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
       CALL histdef( kid, "iicevelv", "j-Ice speed (I-point)"   , "m/s"    , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
@@ -351,5 +350,4 @@
       CALL histwrite( kid, "ileadfra", kt, 1. - frld(:,:) , jpi*jpj, (/1/) )
       CALL histwrite( kid, "iicetemp", kt, sist(:,:) - rt0, jpi*jpj, (/1/) )
-      CALL histwrite( kid, "ioceflxb", kt, fbif           , jpi*jpj, (/1/) )
       CALL histwrite( kid, "iicevelu", kt, u_ice          , jpi*jpj, (/1/) )
       CALL histwrite( kid, "iicevelv", kt, v_ice          , jpi*jpj, (/1/) )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/ice.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/ice.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/ice.F90	(revision 5075)
@@ -105,5 +105,5 @@
    !! ** Global variables                                                 |
    !!-------------|-------------|---------------------------------|-------|
-   !! a_i         | a_i_b       |    Ice concentration            |       |
+   !! a_i         | a_i_1d      |    Ice concentration            |       |
    !! v_i         |      -      |    Ice volume per unit area     | m     |
    !! v_s         |      -      |    Snow volume per unit area    | m     |
@@ -111,7 +111,7 @@
    !! oa_i        !      -      !    Sea ice areal age content    | day   |
    !! e_i         !      -      !    Ice enthalpy                 | 10^9 J| 
-   !!      -      ! q_i_b       !    Ice enthalpy per unit vol.   | J/m3  | 
+   !!      -      ! q_i_1d      !    Ice enthalpy per unit vol.   | J/m3  | 
    !! e_s         !      -      !    Snow enthalpy                | 10^9 J| 
-   !!      -      ! q_s_b       !    Snow enthalpy per unit vol.  | J/m3  | 
+   !!      -      ! q_s_1d      !    Snow enthalpy per unit vol.  | J/m3  | 
    !!                                                                     |
    !!-------------|-------------|---------------------------------|-------|
@@ -120,12 +120,12 @@
    !!-------------|-------------|---------------------------------|-------|
    !!                                                                     |
-   !! ht_i        | ht_i_b      |    Ice thickness                | m     |
-   !! ht_s        ! ht_s_b      |    Snow depth                   | m     |
-   !! sm_i        ! sm_i_b      |    Sea ice bulk salinity        ! ppt   |
-   !! s_i         ! s_i_b       |    Sea ice salinity profile     ! ppt   |
+   !! ht_i        | ht_i_1d     |    Ice thickness                | m     |
+   !! ht_s        ! ht_s_1d     |    Snow depth                   | m     |
+   !! sm_i        ! sm_i_1d     |    Sea ice bulk salinity        ! ppt   |
+   !! s_i         ! s_i_1d      |    Sea ice salinity profile     ! ppt   |
    !! o_i         !      -      |    Sea ice Age                  ! days  |
-   !! t_i         ! t_i_b       |    Sea ice temperature          ! K     |
-   !! t_s         ! t_s_b       |    Snow temperature             ! K     |
-   !! t_su        ! t_su_b      |    Sea ice surface temperature  ! K     |
+   !! t_i         ! t_i_1d      |    Sea ice temperature          ! K     |
+   !! t_s         ! t_s_1d      |    Snow temperature             ! K     |
+   !! t_su        ! t_su_1d     |    Sea ice surface temperature  ! K     |
    !!                                                                     |
    !! notes: the ice model only sees a bulk (i.e., vertically averaged)   |
@@ -142,5 +142,5 @@
    !! ***         Category-summed state variables (diagnostic)        *** |
    !! ******************************************************************* |
-   !! at_i        | at_i_b      |    Total ice concentration      |       |
+   !! at_i        | at_i_1d     |    Total ice concentration      |       |
    !! vt_i        |      -      |    Total ice vol. per unit area | m     |
    !! vt_s        |      -      |    Total snow vol. per unit ar. | m     |
@@ -166,27 +166,17 @@
 
    !                                     !!** ice-dynamic namelist (namicedyn) **
-   INTEGER , PUBLIC ::   nbiter           !: number of sub-time steps for relaxation
-   INTEGER , PUBLIC ::   nbitdr           !: maximum number of iterations for relaxation
    INTEGER , PUBLIC ::   nevp             !: number of iterations for subcycling
-   INTEGER , PUBLIC ::   nlay_i = 5            !: number of layers in the ice
-
-   !                                     !!** ice-dynamic namelist (namicedyn) **
    REAL(wp), PUBLIC ::   epsd             !: tolerance parameter for dynamic
-   REAL(wp), PUBLIC ::   alpha            !: coefficient for semi-implicit coriolis
-   REAL(wp), PUBLIC ::   dm               !: diffusion constant for dynamics
    REAL(wp), PUBLIC ::   om               !: relaxation constant
-   REAL(wp), PUBLIC ::   resl             !: maximum value for the residual of relaxation
    REAL(wp), PUBLIC ::   cw               !: drag coefficient for oceanic stress
-   REAL(wp), PUBLIC ::   angvg            !: turning angle for oceanic stress
    REAL(wp), PUBLIC ::   pstar            !: determines ice strength (N/M), Hibler JPO79
    REAL(wp), PUBLIC ::   c_rhg            !: determines changes in ice strength
-   REAL(wp), PUBLIC ::   etamn            !: minimun value for viscosity : has to be 0
    REAL(wp), PUBLIC ::   creepl           !: creep limit : has to be under 1.0e-9
    REAL(wp), PUBLIC ::   ecc              !: eccentricity of the elliptical yield curve
    REAL(wp), PUBLIC ::   ahi0             !: sea-ice hor. eddy diffusivity coeff. (m2/s)
-   REAL(wp), PUBLIC ::   telast           !: timescale for elastic waves (s) !SB
-   REAL(wp), PUBLIC ::   alphaevp         !: coeficient of the internal stresses !SB
-   REAL(wp), PUBLIC ::   unit_fac = 1.e+09_wp  !: conversion factor for ice / snow enthalpy
-   REAL(wp), PUBLIC ::   hminrhg = 0.001_wp    !: clem : ice volume (a*h, in m) below which ice velocity is set to ocean velocity
+   REAL(wp), PUBLIC ::   telast           !: timescale for elastic waves (s)
+   REAL(wp), PUBLIC ::   relast           !: ratio => telast/rdt_ice (1/3 or 1/9 depending on nb of subcycling nevp) 
+   REAL(wp), PUBLIC ::   alphaevp         !: coeficient of the internal stresses 
+   REAL(wp), PUBLIC ::   hminrhg          !: ice volume (a*h, in m) below which ice velocity is set to ocean velocity
 
    !                                     !!** ice-salinity namelist (namicesal) **
@@ -202,10 +192,9 @@
 
    !                                     !!** ice-salinity namelist (namicesal) **
-   INTEGER , PUBLIC ::   num_sal          !: salinity configuration used in the model
+   INTEGER , PUBLIC ::   num_sal             !: salinity configuration used in the model
    !                                         ! 1 - constant salinity in both space and time
    !                                         ! 2 - prognostic salinity (s(z,t))
    !                                         ! 3 - salinity profile, constant in time
-   INTEGER , PUBLIC ::   sal_prof    = 1           !: salinity profile or not 
-   INTEGER , PUBLIC ::   thcon_i_swi          !: thermal conductivity: =1 Untersteiner (1964) ; =2 Pringle et al (2007)
+   INTEGER , PUBLIC ::   thcon_i_swi         !: thermal conductivity: =0 Untersteiner (1964) ; =1 Pringle et al (2007)
 
    !                                     !!** ice-mechanical redistribution namelist (namiceitdme)
@@ -220,5 +209,4 @@
    REAL(wp), PUBLIC ::   Craft            !: coefficient for smoothness of the hyperbolic tangent in rafting
    REAL(wp), PUBLIC ::   ridge_por        !: initial porosity of ridges (0.3 regular value)
-   REAL(wp), PUBLIC ::   sal_max_ridge    !: maximum ridged ice salinity (ppt)
    REAL(wp), PUBLIC ::   betas            !: coef. for partitioning of snowfall between leads and sea ice
    REAL(wp), PUBLIC ::   kappa_i          !: coef. for the extinction of radiation Grenfell et al. (2006) [1/m]
@@ -228,13 +216,19 @@
    !                                     !!** ice-mechanical redistribution namelist (namiceitdme)
    INTEGER , PUBLIC ::   ridge_scheme_swi !: scheme used for ice ridging
-   INTEGER , PUBLIC ::   raftswi          !: rafting of ice or not                        
+   INTEGER , PUBLIC ::   raft_swi         !: rafting of ice or not                        
    INTEGER , PUBLIC ::   partfun_swi      !: participation function: =0 Thorndike et al. (1975), =1 Lipscomb et al. (2007)
-   INTEGER , PUBLIC ::   transfun_swi     !: transfer function: =0 Hibler 1980, =1 Lipscomb et al. 2007
    INTEGER , PUBLIC ::   brinstren_swi    !: use brine volume to diminish ice strength
 
    REAL(wp), PUBLIC ::   usecc2           !:  = 1.0 / ( ecc * ecc )
    REAL(wp), PUBLIC ::   rhoco            !: = rau0 * cw
-   REAL(wp), PUBLIC ::   sangvg, cangvg   !: sin and cos of the turning angle for ocean stress
-   REAL(wp), PUBLIC ::   pstarh           !: pstar / 2.0
+
+   !                                     !!** switch for presence of ice or not 
+   REAL(wp), PUBLIC ::   rswitch
+
+   !                                     !!** define some parameters 
+   REAL(wp), PUBLIC, PARAMETER ::   unit_fac = 1.e+09_wp  !: conversion factor for ice / snow enthalpy
+   REAL(wp), PUBLIC, PARAMETER ::   epsi06   = 1.e-06_wp  !: small number 
+   REAL(wp), PUBLIC, PARAMETER ::   epsi10   = 1.e-10_wp  !: small number 
+   REAL(wp), PUBLIC, PARAMETER ::   epsi20   = 1.e-20_wp  !: small number 
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   u_oce, v_oce   !: surface ocean velocity used in ice dynamics
@@ -249,46 +243,60 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   shear_i        !: Shear of the velocity field [s-1]
    !
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   firic       !: IR flux over the ice (diag only)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fcsic       !: Sensible heat flux over the ice (diag only)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fleic       !: Latent heat flux over the ice (diag only)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qlatic      !: latent flux
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rdvosif     !: Variation of volume at surface (diag only)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rdvobif     !: Variation of ice volume at the bottom ice (diag only)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fdvolif     !: Total variation of ice volume (diag only)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rdvonif     !: Lateral Variation of ice volume (diag only)
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sist        !: Average Sea-Ice Surface Temperature [Kelvin]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   icethi      !: total ice thickness (for all categories) (diag only)
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   t_bo        !: Sea-Ice bottom temperature [Kelvin]     
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hicifp      !: Ice production/melting==>!obsolete... can be removed
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   frld        !: Leads fraction = 1 - ice fraction
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   pfrld       !: Leads fraction at previous time  
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   phicif      !: Old ice thickness
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fbif        !: Heat flux at the ice base
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rdm_snw     !: Variation of snow mass over 1 time step     [Kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rdq_snw     !: Heat content associated with rdm_snw        [J/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rdm_ice     !: Variation of ice mass over 1 time step      [Kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   rdq_ice     !: Heat content associated with rdm_ice        [J/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qldif       !: heat balance of the lead (or of the open ocean)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qcmif       !: Energy needed to bring the ocean to freezing 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fdtcn       !: net downward heat flux from the ice to the ocean
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qdtcn       !: energy from the ice to the ocean
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fstric      !: transmitted solar radiation under ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fscmbq      !: associated with lead chipotage with solar flux
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ffltbif     !: related to max heat contained in brine pockets (?)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fsbbq       !: Also linked with the solar flux below the ice (?)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qfvbq       !: store energy in case of total lateral ablation (?)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   dmgwi       !: Variation of the mass of snow ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_thd     !: salt flux due to ice growth/melt                      [PSU/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qlead       !: heat balance of the lead (or of the open ocean)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fhtur       !: net downward heat flux from the ice to the ocean
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fhld        !: heat flux from the lead used for bottom melting
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_snw    !: snow-ocean mass exchange over 1 time step [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_spr    !: snow precipitation on ice over 1 time step [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sub    !: snow sublimation over 1 time step [kg/m2]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_ice    !: ice-ocean mass exchange over 1 time step [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sni    !: snow ice growth component of wfx_ice [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_opw    !: lateral ice growth component of wfx_ice [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_bog    !: bottom ice growth component of wfx_ice [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_dyn    !: dynamical ice growth component of wfx_ice [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_bom    !: bottom melt component of wfx_ice [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_sum    !: surface melt component of wfx_ice [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   wfx_res    !: residual component of wfx_ice [kg/m2]
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_bog     !: salt flux due to ice growth/melt                      [PSU/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_bom     !: salt flux due to ice growth/melt                      [PSU/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_sum     !: salt flux due to ice growth/melt                      [PSU/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_sni     !: salt flux due to ice growth/melt                      [PSU/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_opw     !: salt flux due to ice growth/melt                      [PSU/m2/s]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_bri     !: salt flux due to brine rejection                      [PSU/m2/s]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_mec     !: salt flux due to porous ridged ice formation          [PSU/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_dyn     !: salt flux due to porous ridged ice formation          [PSU/m2/s]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sfx_res     !: residual salt flux due to correction of ice thickness [PSU/m2/s]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fhbri       !: heat flux due to brine rejection
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fheat_mec   !: heat flux associated with porous ridged ice formation [???]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fheat_res   !: residual heat flux due to correction of ice thickness
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fmmec       !: mass flux due to snow loss during compression         [Kg/m2/s]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fhmec       !: heat flux due to snow loss during compression
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_bog     !: total heat flux causing bottom ice growth 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_bom     !: total heat flux causing bottom ice melt 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_sum     !: total heat flux causing surface ice melt 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_opw     !: total heat flux causing open water ice formation
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_dif     !: total heat flux causing Temp change in the ice 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_snw     !: heat flux for snow melt 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_err     !: heat flux error after heat diffusion 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_err_rem !: heat flux error after heat remapping 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_in      !: heat flux available for thermo transformations 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_out     !: heat flux remaining at the end of thermo transformations 
+
+   ! heat flux associated with ice-atmosphere mass exchange
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_sub     !: heat flux for sublimation 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_spr     !: heat flux of the snow precipitation 
+
+   ! heat flux associated with ice-ocean mass exchange
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_thd     !: ice-ocean heat flux from thermo processes (limthd_dh) 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_dyn     !: ice-ocean heat flux from mecanical processes (limitd_me) 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hfx_res     !: residual heat flux due to correction of ice thickness
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ftr_ice   !: transmitted solar radiation under ice
 
    ! temporary arrays for dummy version of the code
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   dh_i_surf2D, dh_i_bott2D, fstbif, fsup2D, focea2D, q_s
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   dh_i_surf2D, dh_i_bott2D, q_s
 
    !!--------------------------------------------------------------------------
@@ -321,11 +329,6 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   smt_i          !: mean sea ice salinity averaged over all categories [PSU]
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   at_i_typ     !: total area   contained in each ice type [m^2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   vt_i_typ     !: total volume contained in each ice type [m^3]
-
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   t_s        !: Snow temperatures [K]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   e_s        !: Snow ...      
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   e_i_cat    !: ! go to trash
       
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   t_i        !: ice temperatures          [K]
@@ -348,9 +351,9 @@
    !! * Old values of global variables
    !!--------------------------------------------------------------------------
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   old_v_s, old_v_i               !: snow and ice volumes
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   old_a_i, old_smv_i, old_oa_i   !: ???
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   old_e_s                        !: snow heat content
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   old_e_i                        !: ice temperatures
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   old_u_ice, old_v_ice           !: ice velocity (gv6 and gv7)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   v_s_b, v_i_b               !: snow and ice volumes
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   a_i_b, smv_i_b, oa_i_b     !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   e_s_b                      !: snow heat content
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   e_i_b                      !: ice temperatures
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)     ::   u_ice_b, v_ice_b           !: ice velocity
       
 
@@ -366,5 +369,5 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   d_sm_i_fl  , d_sm_i_gd                 !:
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   d_sm_i_se  , d_sm_i_si  , d_sm_i_la    !:
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   d_oa_i_thd , d_oa_i_trp , s_i_newice   !:
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   d_oa_i_thd , d_oa_i_trp                !:
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   d_e_s_thd  , d_e_s_trp     !:
@@ -375,14 +378,6 @@
    !! * Ice thickness distribution variables
    !!--------------------------------------------------------------------------
-   ! REMOVE
-   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)   ::   ice_types      !: Vector connecting types and categories
-   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ice_cat_bounds !: Matrix containing the integer upper and 
-   !                                                                       !  lower boundaries of ice thickness categories
-   ! REMOVE
-   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)   ::   ice_ncat_types !: nb of thickness categories in each ice type
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)   ::   hi_max         !: Boundary of ice thickness categories in thickness space
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)   ::   hi_mean        !: Mean ice thickness in catgories 
-   ! REMOVE
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hi_max_typ     !: Boundary of ice thickness categories in thickness space
 
    !!--------------------------------------------------------------------------
@@ -404,15 +399,12 @@
    LOGICAL , PUBLIC                                      ::   ln_limdiahsb  !: flag for ice diag (T) or not (F)
    LOGICAL , PUBLIC                                      ::   ln_limdiaout  !: flag for ice diag (T) or not (F)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   v_newice   !: volume of ice formed in the leads
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dv_dt_thd  !: thermodynamic growth rates 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   izero, fstroc, fhbricat
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_sni_gr   ! snow ice growth 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_lat_gr   ! lateral ice growth 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_bot_gr   ! bottom ice growth 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_dyn_gr   ! dynamical ice growth 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_bot_me   ! vertical bottom melt 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_sur_me   ! vertical surface melt
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_res_pr   ! production (growth+melt) due to limupdate
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_trp_vi   ! transport of ice volume
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dv_dt_thd     !: thermodynamic growth rates 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_trp_vi   !: transport of ice volume
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_trp_vs   !: transport of snw volume
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_trp_ei   !: transport of ice enthalpy (W/m2)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_trp_es   !: transport of snw enthalpy (W/m2)
+   !
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   diag_heat_dhc !: snw/ice heat content variation   [W/m2] 
+   !
    INTEGER , PUBLIC ::   jiindx, jjindx        !: indexes of the debugging point
 
@@ -430,5 +422,5 @@
       INTEGER :: ice_alloc
       !
-      INTEGER :: ierr(20), ii
+      INTEGER :: ierr(19), ii
       !!-----------------------------------------------------------------
 
@@ -447,19 +439,16 @@
 
       ii = ii + 1
-      ALLOCATE( firic    (jpi,jpj) , fcsic  (jpi,jpj) , fleic  (jpi,jpj) , qlatic   (jpi,jpj) ,     &
-         &      rdvosif  (jpi,jpj) , rdvobif(jpi,jpj) , fdvolif(jpi,jpj) , rdvonif  (jpi,jpj) ,     &
-         &      sist     (jpi,jpj) , icethi (jpi,jpj) , t_bo   (jpi,jpj) , hicifp   (jpi,jpj) ,     &
-         &      frld     (jpi,jpj) , pfrld  (jpi,jpj) , phicif (jpi,jpj) , fbif     (jpi,jpj) ,     &
-         &      rdm_snw  (jpi,jpj) , rdq_snw(jpi,jpj) , rdm_ice(jpi,jpj) , rdq_ice  (jpi,jpj) ,     &
-         &                                              qldif  (jpi,jpj) , qcmif    (jpi,jpj) ,     &
-         &      fdtcn    (jpi,jpj) , qdtcn  (jpi,jpj) , fstric (jpi,jpj) , fscmbq   (jpi,jpj) ,     &
-         &      ffltbif  (jpi,jpj) , fsbbq  (jpi,jpj) , qfvbq  (jpi,jpj) , dmgwi    (jpi,jpj) ,     &
-         &      sfx_res  (jpi,jpj) , sfx_bri(jpi,jpj) , sfx_mec(jpi,jpj) , fheat_mec(jpi,jpj) ,     &
-         &      fhbri    (jpi,jpj) , fmmec  (jpi,jpj) , sfx_thd(jpi,jpj) , fhmec    (jpi,jpj) ,     &
-         &      fheat_res(jpi,jpj)                                                            , STAT=ierr(ii) )
-
-      ii = ii + 1
-      ALLOCATE( dh_i_surf2D(jpi,jpj) , dh_i_bott2D(jpi,jpj) , fstbif(jpi,jpj) ,     &
-         &      fsup2D     (jpi,jpj) , focea2D    (jpi,jpj) , q_s   (jpi,jpj) , STAT=ierr(ii) )
+      ALLOCATE( sist   (jpi,jpj) , icethi (jpi,jpj) , t_bo   (jpi,jpj) ,      &
+         &      frld   (jpi,jpj) , pfrld  (jpi,jpj) , phicif (jpi,jpj) ,      &
+         &      wfx_snw(jpi,jpj) , wfx_ice(jpi,jpj) , wfx_sub(jpi,jpj) ,    &
+         &      wfx_bog(jpi,jpj) , wfx_dyn(jpi,jpj) , wfx_bom(jpi,jpj) , wfx_sum(jpi,jpj) ,     &
+         &      wfx_res(jpi,jpj) , wfx_sni(jpi,jpj) , wfx_opw(jpi,jpj) , wfx_spr(jpi,jpj) ,  qlead  (jpi,jpj) ,     &
+         &      fhtur  (jpi,jpj) , ftr_ice(jpi,jpj,jpl) ,      &
+         &      sfx_res(jpi,jpj) , sfx_bri(jpi,jpj) , sfx_dyn(jpi,jpj) ,      &
+         &      sfx_bog(jpi,jpj) , sfx_bom(jpi,jpj) , sfx_sum(jpi,jpj) , sfx_sni(jpi,jpj) , sfx_opw(jpi,jpj) ,   &
+         &      hfx_res(jpi,jpj) , hfx_snw(jpi,jpj) , hfx_sub(jpi,jpj) , hfx_err(jpi,jpj) , hfx_err_rem(jpi,jpj), &
+         &      hfx_in (jpi,jpj) , hfx_out(jpi,jpj) , fhld(jpi,jpj) ,  &
+         &      hfx_sum(jpi,jpj) , hfx_bom(jpi,jpj) , hfx_bog(jpi,jpj) , hfx_dif(jpi,jpj) , hfx_opw(jpi,jpj) , &
+         &      hfx_thd(jpi,jpj) , hfx_dyn(jpi,jpj) , hfx_spr(jpi,jpj) ,  STAT=ierr(ii) )
 
       ! * Ice global state variables
@@ -475,8 +464,8 @@
          &      bv_i (jpi,jpj) , smt_i(jpi,jpj)                                   , STAT=ierr(ii) )
       ii = ii + 1
-      ALLOCATE( t_s(jpi,jpj,nlay_s,jpl) , at_i_typ(jpi,jpj,jpm) ,                            &
-         &      e_s(jpi,jpj,nlay_s,jpl) , vt_i_typ(jpi,jpj,jpm) , e_i_cat(jpi,jpj,jpl) , STAT=ierr(ii) )
-      ii = ii + 1
-      ALLOCATE( t_i(jpi,jpj,jkmax,jpl) , e_i(jpi,jpj,jkmax,jpl) , s_i(jpi,jpj,jkmax,jpl) , STAT=ierr(ii) )
+      ALLOCATE( t_s(jpi,jpj,nlay_s,jpl) ,                            &
+         &      e_s(jpi,jpj,nlay_s,jpl) , STAT=ierr(ii) )
+      ii = ii + 1
+      ALLOCATE( t_i(jpi,jpj,nlay_i+1,jpl) , e_i(jpi,jpj,nlay_i+1,jpl) , s_i(jpi,jpj,nlay_i+1,jpl) , STAT=ierr(ii) )
 
       ! * Moments for advection
@@ -494,13 +483,13 @@
          &      STAT=ierr(ii) )
       ii = ii + 1
-      ALLOCATE( sxe (jpi,jpj,jkmax,jpl) , sye (jpi,jpj,jkmax,jpl) , sxxe(jpi,jpj,jkmax,jpl) ,     &
-         &      syye(jpi,jpj,jkmax,jpl) , sxye(jpi,jpj,jkmax,jpl)                           , STAT=ierr(ii) )
+      ALLOCATE( sxe (jpi,jpj,nlay_i+1,jpl) , sye (jpi,jpj,nlay_i+1,jpl) , sxxe(jpi,jpj,nlay_i+1,jpl) ,     &
+         &      syye(jpi,jpj,nlay_i+1,jpl) , sxye(jpi,jpj,nlay_i+1,jpl)                           , STAT=ierr(ii) )
 
       ! * Old values of global variables
       ii = ii + 1
-      ALLOCATE( old_v_s  (jpi,jpj,jpl) , old_v_i  (jpi,jpj,jpl) , old_e_s(jpi,jpj,nlay_s,jpl) ,     &
-         &      old_a_i  (jpi,jpj,jpl) , old_smv_i(jpi,jpj,jpl) , old_e_i(jpi,jpj,jkmax ,jpl) ,     &
-         &      old_oa_i (jpi,jpj,jpl)                                                        ,     &
-         &      old_u_ice(jpi,jpj)     , old_v_ice(jpi,jpj)                                   , STAT=ierr(ii) )
+      ALLOCATE( v_s_b  (jpi,jpj,jpl) , v_i_b  (jpi,jpj,jpl) , e_s_b(jpi,jpj,nlay_s,jpl) ,     &
+         &      a_i_b  (jpi,jpj,jpl) , smv_i_b(jpi,jpj,jpl) , e_i_b(jpi,jpj,nlay_i+1 ,jpl) ,     &
+         &      oa_i_b (jpi,jpj,jpl)                                                        ,     &
+         &      u_ice_b(jpi,jpj)     , v_ice_b(jpi,jpj)                                   , STAT=ierr(ii) )
 
       ! * Increment of global variables
@@ -509,21 +498,19 @@
          &      d_v_i_thd(jpi,jpj,jpl) , d_v_i_trp (jpi,jpj,jpl) , d_smv_i_thd(jpi,jpj,jpl) , d_smv_i_trp(jpi,jpj,jpl) ,   &     
          &      d_sm_i_fl(jpi,jpj,jpl) , d_sm_i_gd (jpi,jpj,jpl) , d_sm_i_se  (jpi,jpj,jpl) , d_sm_i_si  (jpi,jpj,jpl) ,   &
-         &      d_sm_i_la(jpi,jpj,jpl) , d_oa_i_thd(jpi,jpj,jpl) , d_oa_i_trp (jpi,jpj,jpl) , s_i_newice (jpi,jpj,jpl) ,   &
+         &      d_sm_i_la(jpi,jpj,jpl) , d_oa_i_thd(jpi,jpj,jpl) , d_oa_i_trp (jpi,jpj,jpl) ,   &
          &     STAT=ierr(ii) )
       ii = ii + 1
-      ALLOCATE( d_e_s_thd(jpi,jpj,nlay_s,jpl) , d_e_i_thd(jpi,jpj,jkmax,jpl) , d_u_ice_dyn(jpi,jpj) ,     &
-         &      d_e_s_trp(jpi,jpj,nlay_s,jpl) , d_e_i_trp(jpi,jpj,jkmax,jpl) , d_v_ice_dyn(jpi,jpj) , STAT=ierr(ii) )
+      ALLOCATE( d_e_s_thd(jpi,jpj,nlay_s,jpl) , d_e_i_thd(jpi,jpj,nlay_i,jpl) , d_u_ice_dyn(jpi,jpj) ,     &
+         &      d_e_s_trp(jpi,jpj,nlay_s,jpl) , d_e_i_trp(jpi,jpj,nlay_i,jpl) , d_v_ice_dyn(jpi,jpj) , STAT=ierr(ii) )
       
       ! * Ice thickness distribution variables
       ii = ii + 1
-      ALLOCATE( ice_types(jpl) , ice_cat_bounds(jpm,2) , ice_ncat_types  (jpm) ,     &
-         &      hi_max (0:jpl) , hi_mean(jpl)          , hi_max_typ(0:jpl,jpm) , STAT=ierr(ii) )
+      ALLOCATE( hi_max(0:jpl), hi_mean(jpl),  STAT=ierr(ii) )
 
       ! * Ice diagnostics
       ii = ii + 1
-      ALLOCATE( dv_dt_thd(jpi,jpj,jpl) , diag_sni_gr(jpi,jpj) , diag_lat_gr(jpi,jpj) ,     &
-         &      izero    (jpi,jpj,jpl) , diag_bot_gr(jpi,jpj) , diag_dyn_gr(jpi,jpj) ,     &
-         &      fstroc   (jpi,jpj,jpl) , diag_bot_me(jpi,jpj) , diag_sur_me(jpi,jpj) ,     &
-         &      fhbricat (jpi,jpj,jpl) , diag_res_pr(jpi,jpj) , diag_trp_vi(jpi,jpj) , v_newice(jpi,jpj) , STAT=ierr(ii) )
+      ALLOCATE( dv_dt_thd(jpi,jpj,jpl),    &
+         &      diag_trp_vi(jpi,jpj), diag_trp_vs  (jpi,jpj), diag_trp_ei(jpi,jpj),   & 
+         &      diag_trp_es(jpi,jpj), diag_heat_dhc(jpi,jpj),  STAT=ierr(ii) )
 
       ice_alloc = MAXVAL( ierr(:) )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/iceini.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/iceini.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/iceini.F90	(revision 5075)
@@ -66,6 +66,6 @@
       !
       !                                ! adequation jpk versus ice/snow layers/categories
-      IF( jpl   > jpk  .OR.  jpm    > jpk .OR.                                    &
-          jkmax > jpk  .OR.  nlay_s > jpk      )   CALL ctl_stop( 'STOP',         &
+      IF( jpl > jpk .OR. (nlay_i+1) > jpk .OR. nlay_s > jpk )   &
+         &      CALL ctl_stop( 'STOP',                     &
          &     'ice_init: the 3rd dimension of workspace arrays is too small.',   &
          &     'use more ocean levels or less ice/snow layers/categories.' )
@@ -89,4 +89,5 @@
       CALL lim_itd_ini                 ! ice thickness distribution initialization
       !
+      CALL lim_itd_me_init             ! ice thickness distribution initialization
       !                                ! Initial sea-ice state
       IF( .NOT. ln_rstart ) THEN              ! start from rest
@@ -173,5 +174,5 @@
       !!              limistate (only) and is changed to 99 m in ice_init
       !!------------------------------------------------------------------
-      INTEGER  ::   jl, jm               ! dummy loop index
+      INTEGER  ::   jl                   ! dummy loop index
       REAL(wp) ::   zc1, zc2, zc3, zx1   ! local scalars
       !!------------------------------------------------------------------
@@ -184,33 +185,6 @@
       ! 1) Ice thickness distribution parameters initialization    
       !------------------------------------------------------------------------------!
-
-      !- Types boundaries (integer)
-      !----------------------------
-      ice_cat_bounds(1,1) = 1
-      ice_cat_bounds(1,2) = jpl
-
-      !- Number of ice thickness categories in each ice type
-      DO jm = 1, jpm
-         ice_ncat_types(jm) = ice_cat_bounds(jm,2) - ice_cat_bounds(jm,1) + 1 
-      END DO
-
-      !- Make the correspondence between thickness categories and ice types
-      !---------------------------------------------------------------------
-      DO jm = 1, jpm       !over types
-         DO jl = ice_cat_bounds(jm,1), ice_cat_bounds(jm,2) !over thickness categories
-            ice_types(jl) = jm
-         END DO
-      END DO
-
       IF(lwp) THEN  
-         WRITE(numout,*) ' Number of ice types jpm =      ', jpm
          WRITE(numout,*) ' Number of ice categories jpl = ', jpl
-         DO jm = 1, jpm
-            WRITE(numout,*) ' Ice type ', jm
-            WRITE(numout,*) ' Number of thickness categories ', ice_ncat_types(jm)
-            WRITE(numout,*) ' Thickness category boundaries  ', ice_cat_bounds(jm,1:2)
-         END DO
-         WRITE(numout,*) 'Ice type vector', ice_types(1:jpl)
-         WRITE(numout,*)
       ENDIF
 
@@ -218,33 +192,17 @@
       !----------------------------------
       hi_max(:) = 0._wp
-      hi_max_typ(:,:) = 0._wp
-
-      !- Type 1 - undeformed ice
-      zc1 =  3._wp / REAL( ice_cat_bounds(1,2) - ice_cat_bounds(1,1) + 1 , wp )
+
+      zc1 =  3._wp / REAL( jpl, wp )
       zc2 = 10._wp * zc1
       zc3 =  3._wp
 
-      DO jl = ice_cat_bounds(1,1), ice_cat_bounds(1,2)
-         zx1 = REAL( jl-1 , wp ) / REAL( ice_cat_bounds(1,2) - ice_cat_bounds(1,1) + 1 , wp )
+      DO jl = 1, jpl
+         zx1 = REAL( jl-1, wp ) / REAL( jpl, wp )
          hi_max(jl) = hi_max(jl-1) + zc1 + zc2 * (1._wp + TANH( zc3 * (zx1 - 1._wp ) ) )
       END DO
 
-      !- Fill in the hi_max_typ vector, useful in other circumstances
-      ! Tricky trick: hi_max_typ is actually not used in the code and will be removed in a
-      ! next flyspray at this time, the tricky trick will also be removed (Martin, march 08)
-      DO jl = ice_cat_bounds(1,1), ice_cat_bounds(1,2)
-         hi_max_typ(jl,1) = hi_max(jl)
-      END DO
-
-      IF(lwp) WRITE(numout,*) ' Thickness category boundaries independently of ice type '
+      IF(lwp) WRITE(numout,*) ' Thickness category boundaries '
       IF(lwp) WRITE(numout,*) ' hi_max ', hi_max(0:jpl)
 
-      IF(lwp) WRITE(numout,*) ' Thickness category boundaries inside ice types '
-      IF(lwp) THEN 
-         DO jm = 1, jpm
-            WRITE(numout,*) ' Type number ', jm
-            WRITE(numout,*) ' hi_max_typ : ', hi_max_typ(0:ice_ncat_types(jm),jm)
-         END DO
-      ENDIF
       !
       DO jl = 1, jpl
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limadv.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limadv.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limadv.F90	(revision 5075)
@@ -30,8 +30,4 @@
    PUBLIC   lim_adv_x   ! called by lim_trp
    PUBLIC   lim_adv_y   ! called by lim_trp
-
-   REAL(wp)  ::   epsi20 = 1.e-20_wp   ! constant values
-   REAL(wp)  ::   rzero  = 0._wp       !    -       -
-   REAL(wp)  ::   rone   = 1._wp       !    -       -
 
    !! * Substitutions
@@ -84,10 +80,10 @@
       DO jj = 1, jpj
          DO ji = 1, jpi
-            zslpmax = MAX( rzero, ps0(ji,jj) )
+            zslpmax = MAX( 0._wp, ps0(ji,jj) )
             zs1max  = 1.5 * zslpmax
             zs1new  = MIN( zs1max, MAX( -zs1max, psx(ji,jj) ) )
             zs2new  = MIN(  2.0 * zslpmax - 0.3334 * ABS( zs1new ),      &
                &            MAX( ABS( zs1new ) - zslpmax, psxx(ji,jj) )  )
-            zin0    = ( 1.0 - MAX( rzero, SIGN( rone, -zslpmax) ) ) * tms(ji,jj)   ! Case of empty boxes & Apply mask
+            zin0    = ( 1.0 - MAX( 0._wp, SIGN( 1._wp, -zslpmax) ) ) * tms(ji,jj)   ! Case of empty boxes & Apply mask
 
             ps0 (ji,jj) = zslpmax  
@@ -106,6 +102,6 @@
       DO jj = 1, jpj                      !  Flux from i to i+1 WHEN u GT 0 
          DO ji = 1, jpi
-            zbet(ji,jj)  =  MAX( rzero, SIGN( rone, put(ji,jj) ) )
-            zalf         =  MAX( rzero, put(ji,jj) ) * zrdt * e2u(ji,jj) / psm(ji,jj)
+            zbet(ji,jj)  =  MAX( 0._wp, SIGN( 1._wp, put(ji,jj) ) )
+            zalf         =  MAX( 0._wp, put(ji,jj) ) * zrdt * e2u(ji,jj) / psm(ji,jj)
             zalfq        =  zalf * zalf
             zalf1        =  1.0 - zalf
@@ -133,5 +129,5 @@
       DO jj = 1, jpjm1                      !  Flux from i+1 to i when u LT 0.
          DO ji = 1, fs_jpim1
-            zalf          = MAX( rzero, -put(ji,jj) ) * zrdt * e2u(ji,jj) / psm(ji+1,jj) 
+            zalf          = MAX( 0._wp, -put(ji,jj) ) * zrdt * e2u(ji,jj) / psm(ji+1,jj) 
             zalg  (ji,jj) = zalf
             zalfq         = zalf * zalf
@@ -269,10 +265,10 @@
       DO jj = 1, jpj
          DO ji = 1, jpi
-            zslpmax = MAX( rzero, ps0(ji,jj) )
+            zslpmax = MAX( 0._wp, ps0(ji,jj) )
             zs1max  = 1.5 * zslpmax
             zs1new  = MIN( zs1max, MAX( -zs1max, psy(ji,jj) ) )
             zs2new  = MIN(  ( 2.0 * zslpmax - 0.3334 * ABS( zs1new ) ),   &
                &             MAX( ABS( zs1new )-zslpmax, psyy(ji,jj) )  )
-            zin0    = ( 1.0 - MAX( rzero, SIGN( rone, -zslpmax) ) ) * tms(ji,jj)   ! Case of empty boxes & Apply mask
+            zin0    = ( 1.0 - MAX( 0._wp, SIGN( 1._wp, -zslpmax) ) ) * tms(ji,jj)   ! Case of empty boxes & Apply mask
             !
             ps0 (ji,jj) = zslpmax  
@@ -291,6 +287,6 @@
       DO jj = 1, jpj                     !  Flux from j to j+1 WHEN v GT 0   
          DO ji = 1, jpi
-            zbet(ji,jj)  =  MAX( rzero, SIGN( rone, pvt(ji,jj) ) )
-            zalf         =  MAX( rzero, pvt(ji,jj) ) * zrdt * e1v(ji,jj) / psm(ji,jj)
+            zbet(ji,jj)  =  MAX( 0._wp, SIGN( 1._wp, pvt(ji,jj) ) )
+            zalf         =  MAX( 0._wp, pvt(ji,jj) ) * zrdt * e1v(ji,jj) / psm(ji,jj)
             zalfq        =  zalf * zalf
             zalf1        =  1.0 - zalf
@@ -318,5 +314,5 @@
       DO jj = 1, jpjm1                   !  Flux from j+1 to j when v LT 0.
          DO ji = 1, jpi
-            zalf          = ( MAX(rzero, -pvt(ji,jj) ) * zrdt * e1v(ji,jj) ) / psm(ji,jj+1) 
+            zalf          = ( MAX(0._wp, -pvt(ji,jj) ) * zrdt * e1v(ji,jj) ) / psm(ji,jj+1) 
             zalg  (ji,jj) = zalf
             zalfq         = zalf * zalf
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limcons.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limcons.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limcons.F90	(revision 5075)
@@ -7,4 +7,5 @@
    !!            3.0  ! 2004-06  (M. Vancoppenolle)   Energy Conservation 
    !!            4.0  ! 2011-02  (G. Madec)  add mpp considerations
+   !!             -   ! 2014-05  (C. Rousset) add lim_cons_hsm
    !!----------------------------------------------------------------------
 #if defined key_lim3
@@ -14,4 +15,5 @@
    !!    lim_cons     :   checks whether energy, mass and salt are conserved 
    !!----------------------------------------------------------------------
+   USE phycst         ! physical constants
    USE par_ice        ! LIM-3 parameter
    USE ice            ! LIM-3 variables
@@ -28,4 +30,5 @@
    PUBLIC   lim_column_sum_energy
    PUBLIC   lim_cons_check
+   PUBLIC   lim_cons_hsm
 
    !!----------------------------------------------------------------------
@@ -70,8 +73,8 @@
       !! ** Method  : Arithmetics
       !!---------------------------------------------------------------------
-      INTEGER                               , INTENT(in   ) ::   ksum   !: number of categories
-      INTEGER                               , INTENT(in   ) ::   klay   !: number of vertical layers
-      REAL(wp), DIMENSION(jpi,jpj,jkmax,jpl), INTENT(in   ) ::   pin   !: input field
-      REAL(wp), DIMENSION(jpi,jpj)          , INTENT(  out) ::   pout   !: output field
+      INTEGER                                  , INTENT(in   ) ::   ksum   !: number of categories
+      INTEGER                                  , INTENT(in   ) ::   klay   !: number of vertical layers
+      REAL(wp), DIMENSION(jpi,jpj,nlay_i+1,jpl), INTENT(in   ) ::   pin   !: input field
+      REAL(wp), DIMENSION(jpi,jpj)             , INTENT(  out) ::   pout   !: output field
       !
       INTEGER ::   jk, jl   ! dummy loop indices
@@ -151,4 +154,69 @@
    END SUBROUTINE lim_cons_check
 
+
+   SUBROUTINE lim_cons_hsm( icount, cd_routine, zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b )
+      !!-------------------------------------------------------------------
+      !!               ***  ROUTINE lim_cons_hsm ***
+      !!
+      !! ** Purpose : Test the conservation of heat, salt and mass for each routine
+      !!
+      !! ** Method  :
+      !!---------------------------------------------------------------------
+      INTEGER         , INTENT(in)    :: icount      ! determine wether this is the beggining of the routine (0) or the end (1)
+      CHARACTER(len=*), INTENT(in)    :: cd_routine  ! name of the routine
+      REAL(wp)        , INTENT(inout) :: zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b 
+      REAL(wp)                        :: zvi,   zsmv,   zei,   zfs,   zfw,   zft
+      REAL(wp)                        :: zvmin, zamin, zamax 
+
+      IF( icount == 0 ) THEN
+
+         zvi_b  = glob_sum( SUM(   v_i(:,:,:)*rhoic + v_s(:,:,:)*rhosn, dim=3 ) * area(:,:) * tms(:,:) )
+         zsmv_b = glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
+         zei_b  = glob_sum( SUM(   e_i(:,:,1:nlay_i,:), dim=3 ) + SUM( e_s(:,:,1:nlay_s,:), dim=3 ) )
+         zfw_b  = glob_sum( - ( wfx_bog(:,:) + wfx_bom(:,:) + wfx_sum(:,:) + wfx_sni(:,:) + wfx_opw(:,:) +  &
+            &                   wfx_res(:,:) + wfx_dyn(:,:) + wfx_snw(:,:) + wfx_sub(:,:) + wfx_spr(:,:)    &
+            &             ) * area(:,:) * tms(:,:) )
+         zfs_b  = glob_sum(   ( sfx_bri(:,:) + sfx_bog(:,:) + sfx_bom(:,:) + sfx_sum(:,:) + sfx_sni(:,:) +  &
+            &                   sfx_opw(:,:) + sfx_res(:,:) + sfx_dyn(:,:)                                  &
+            &                 ) * area(:,:) * tms(:,:) )
+         zft_b  = glob_sum(   ( hfx_sum(:,:) + hfx_bom(:,:) + hfx_bog(:,:) + hfx_dif(:,:) + hfx_opw(:,:) + hfx_snw(:,:)  & 
+            &                 - hfx_thd(:,:) - hfx_dyn(:,:) - hfx_res(:,:) - hfx_sub(:,:) - hfx_spr(:,:)   &
+            &                  ) * area(:,:) / unit_fac * tms(:,:) )
+
+      ELSEIF( icount == 1 ) THEN
+
+         zfs  = glob_sum(   ( sfx_bri(:,:) + sfx_bog(:,:) + sfx_bom(:,:) + sfx_sum(:,:) + sfx_sni(:,:) +  &
+            &                 sfx_opw(:,:) + sfx_res(:,:) + sfx_dyn(:,:)                                  & 
+            &                ) * area(:,:) * tms(:,:) ) - zfs_b
+         zfw  = glob_sum( - ( wfx_bog(:,:) + wfx_bom(:,:) + wfx_sum(:,:) + wfx_sni(:,:) + wfx_opw(:,:) +  &
+            &                 wfx_res(:,:) + wfx_dyn(:,:) + wfx_snw(:,:) + wfx_sub(:,:) + wfx_spr(:,:)    &
+            &                ) * area(:,:) * tms(:,:) ) - zfw_b
+         zft  = glob_sum(   ( hfx_sum(:,:) + hfx_bom(:,:) + hfx_bog(:,:) + hfx_dif(:,:) + hfx_opw(:,:) + hfx_snw(:,:)  & 
+            &               - hfx_thd(:,:) - hfx_dyn(:,:) - hfx_res(:,:) - hfx_sub(:,:) - hfx_spr(:,:)   &
+            &                ) * area(:,:) / unit_fac * tms(:,:) ) - zft_b
+ 
+         zvi  = ( glob_sum( SUM(   v_i(:,:,:)*rhoic + v_s(:,:,:)*rhosn, dim=3 ) * area(:,:) * tms(:,:) ) - zvi_b ) * r1_rdtice - zfw 
+         zsmv = ( glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zsmv_b ) * r1_rdtice + ( zfs / rhoic )
+         zei  =   glob_sum( SUM( e_i(:,:,1:nlay_i,:), dim=3 ) + SUM( e_s(:,:,1:nlay_s,:), dim=3 ) ) * r1_rdtice - zei_b * r1_rdtice + zft
+
+         zvmin = glob_min(v_i)
+         zamax = glob_max(SUM(a_i,dim=3))
+         zamin = glob_min(a_i)
+       
+         IF(lwp) THEN
+            IF ( ABS( zvi    ) >  1.e-4 ) WRITE(numout,*) 'violation volume [kg/day]     (',cd_routine,') = ',(zvi * rday)
+            IF ( ABS( zsmv   ) >  1.e-4 ) WRITE(numout,*) 'violation saline [psu*m3/day] (',cd_routine,') = ',(zsmv * rday)
+            IF ( ABS( zei    ) >  1.    ) WRITE(numout,*) 'violation enthalpy [1e9 J]    (',cd_routine,') = ',(zei)
+            IF ( zvmin <  0.            ) WRITE(numout,*) 'violation v_i<0  [m]          (',cd_routine,') = ',(zvmin)
+            IF( cd_routine /= 'limtrp' .AND. cd_routine /= 'limitd_me' .AND. zamax > amax+1.e-10 ) THEN
+                                          WRITE(numout,*) 'violation a_i>amax            (',cd_routine,') = ',zamax
+            ENDIF
+            IF ( zamin <  0.            ) WRITE(numout,*) 'violation a_i<0               (',cd_routine,') = ',zamin
+         ENDIF
+
+      ENDIF
+
+   END SUBROUTINE lim_cons_hsm
+
 #else
    !!----------------------------------------------------------------------
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limdiahsb.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limdiahsb.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limdiahsb.F90	(revision 5075)
@@ -18,4 +18,5 @@
    USE dom_oce         ! ocean domain
    USE sbc_oce         ! surface boundary condition: ocean fields
+   USE sbc_ice         ! Surface boundary condition: sea-ice fields
    USE daymod          ! model calendar
    USE phycst          ! physical constant
@@ -34,9 +35,6 @@
    !!PUBLIC   lim_diahsb_rst   ! routine called by ice_init.F90
 
-   REAL(dp) ::   frc_sal, frc_vol   ! global forcing trends
-   REAL(dp) ::   bg_grme            ! global ice growth+melt trends
-   REAL(wp) ::   epsi06 = 1.e-6_wp  ! small number
-   REAL(wp) ::   epsi03 = 1.e-3_wp  ! small number
-
+   real(wp) ::   frc_sal, frc_vol   ! global forcing trends
+   real(wp) ::   bg_grme            ! global ice growth+melt trends
 
    !! * Substitutions
@@ -59,10 +57,15 @@
       !!---------------------------------------------------------------------------
       !!
-      REAL(dp)   ::   zbg_ivo, zbg_svo, zbg_are, zbg_sal ,zbg_tem ,zbg_ihc ,zbg_shc
-      REAL(dp)   ::   zbg_sfx, zbg_sfx_bri, zbg_sfx_thd, zbg_sfx_res, zbg_sfx_mec 
-      REAL(dp)   ::   zbg_emp, zbg_emp_bog, zbg_emp_lag, zbg_emp_sig, zbg_emp_dyg, zbg_emp_bom, zbg_emp_sum, zbg_emp_res 
-      REAL(dp)   ::   z_frc_vol, z_frc_sal, z_bg_grme 
-      REAL(dp)   ::   z1_area                     !    -     -
-      REAL(dp)   ::   zinda, zindb
+      real(wp)   ::   zbg_ivo, zbg_svo, zbg_are, zbg_sal ,zbg_tem ,zbg_ihc ,zbg_shc
+      real(wp)   ::   zbg_sfx, zbg_sfx_bri, zbg_sfx_bog, zbg_sfx_bom, zbg_sfx_sum, zbg_sfx_sni,   &
+      &               zbg_sfx_opw, zbg_sfx_res, zbg_sfx_dyn 
+      real(wp)   ::   zbg_vfx, zbg_vfx_bog, zbg_vfx_opw, zbg_vfx_sni, zbg_vfx_dyn
+      real(wp)   ::   zbg_vfx_bom, zbg_vfx_sum, zbg_vfx_res, zbg_vfx_spr, zbg_vfx_snw, zbg_vfx_sub  
+      real(wp)   ::   zbg_hfx_dhc, zbg_hfx_spr
+      real(wp)   ::   zbg_hfx_res, zbg_hfx_sub, zbg_hfx_dyn, zbg_hfx_thd, zbg_hfx_snw, zbg_hfx_out, zbg_hfx_in   
+      real(wp)   ::   zbg_hfx_sum, zbg_hfx_bom, zbg_hfx_bog, zbg_hfx_dif, zbg_hfx_opw
+      real(wp)   ::   z_frc_vol, z_frc_sal, z_bg_grme 
+      real(wp)   ::   z1_area                     !    -     -
+      REAL(wp)   ::   ztmp
       !!---------------------------------------------------------------------------
       IF( nn_timing == 1 )   CALL timing_start('lim_diahsb')
@@ -71,7 +74,7 @@
 
       ! 1/area
-      z1_area = 1.d0 / MAX( glob_sum( area(:,:) * tms(:,:) ), epsi06 )
-
-      zinda = MAX( 0.d0 , SIGN( 1.d0 , glob_sum( area(:,:) * tms(:,:) ) - epsi06 ) )
+      z1_area = 1._wp / MAX( glob_sum( area(:,:) * tms(:,:) ), epsi06 )
+
+      rswitch = MAX( 0._wp , SIGN( 1._wp , glob_sum( area(:,:) * tms(:,:) ) - epsi06 ) )
       ! ----------------------- !
       ! 1 -  Content variations !
@@ -86,22 +89,49 @@
       !zbg_shc = glob_sum( et_s(:,:) * area(:,:) * tms(:,:) ) / MAX( zbg_svo,epsi06 ) ! snow heat content
 
-      zbg_ihc = glob_sum( et_i(:,:) * 1.e-11 ) ! ice heat content  [10^9*1.e-11 J]
-      zbg_shc = glob_sum( et_s(:,:) * 1.e-11 ) ! snow heat content [10^9*1.e-11 J]
-
-      zbg_emp     = zinda * glob_sum(         emp(:,:) * area(:,:) * tms(:,:) ) * z1_area         * r1_rau0 * rday
-      zbg_emp_bog = zinda * glob_sum( diag_bot_gr(:,:) * area(:,:) * tms(:,:) ) * z1_area * rhoic * r1_rau0 * rday
-      zbg_emp_lag = zinda * glob_sum( diag_lat_gr(:,:) * area(:,:) * tms(:,:) ) * z1_area * rhoic * r1_rau0 * rday
-      zbg_emp_sig = zinda * glob_sum( diag_sni_gr(:,:) * area(:,:) * tms(:,:) ) * z1_area * rhoic * r1_rau0 * rday
-      zbg_emp_dyg = zinda * glob_sum( diag_dyn_gr(:,:) * area(:,:) * tms(:,:) ) * z1_area * rhoic * r1_rau0 * rday
-      zbg_emp_bom = zinda * glob_sum( diag_bot_me(:,:) * area(:,:) * tms(:,:) ) * z1_area * rhoic * r1_rau0 * rday
-      zbg_emp_sum = zinda * glob_sum( diag_sur_me(:,:) * area(:,:) * tms(:,:) ) * z1_area * rhoic * r1_rau0 * rday
-      zbg_emp_res = zinda * glob_sum( diag_res_pr(:,:) * area(:,:) * tms(:,:) ) * z1_area * rhoic * r1_rau0 * rday
-
-      zbg_sfx     = zinda * glob_sum(     sfx(:,:) * area(:,:) * tms(:,:) ) * z1_area * r1_rau0 * rday
-      zbg_sfx_bri = zinda * glob_sum( sfx_bri(:,:) * area(:,:) * tms(:,:) ) * z1_area * r1_rau0 * rday
-      zbg_sfx_thd = zinda * glob_sum( sfx_thd(:,:) * area(:,:) * tms(:,:) ) * z1_area * r1_rau0 * rday
-      zbg_sfx_res = zinda * glob_sum( sfx_res(:,:) * area(:,:) * tms(:,:) ) * z1_area * r1_rau0 * rday
-      zbg_sfx_mec = zinda * glob_sum( sfx_mec(:,:) * area(:,:) * tms(:,:) ) * z1_area * r1_rau0 * rday
-      
+      ! Volume
+      ztmp = rswitch * z1_area * r1_rau0 * rday
+      zbg_vfx     = ztmp * glob_sum(     emp(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_bog = ztmp * glob_sum( wfx_bog(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_opw = ztmp * glob_sum( wfx_opw(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_sni = ztmp * glob_sum( wfx_sni(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_dyn = ztmp * glob_sum( wfx_dyn(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_bom = ztmp * glob_sum( wfx_bom(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_sum = ztmp * glob_sum( wfx_sum(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_res = ztmp * glob_sum( wfx_res(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_spr = ztmp * glob_sum( wfx_spr(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_snw = ztmp * glob_sum( wfx_snw(:,:) * area(:,:) * tms(:,:) )
+      zbg_vfx_sub = ztmp * glob_sum( wfx_sub(:,:) * area(:,:) * tms(:,:) )
+
+      ! Salt
+      zbg_sfx     = ztmp * glob_sum(     sfx(:,:) * area(:,:) * tms(:,:) )
+      zbg_sfx_bri = ztmp * glob_sum( sfx_bri(:,:) * area(:,:) * tms(:,:) )
+      zbg_sfx_res = ztmp * glob_sum( sfx_res(:,:) * area(:,:) * tms(:,:) )
+      zbg_sfx_dyn = ztmp * glob_sum( sfx_dyn(:,:) * area(:,:) * tms(:,:) )
+
+      zbg_sfx_bog = ztmp * glob_sum( sfx_bog(:,:) * area(:,:) * tms(:,:) )
+      zbg_sfx_opw = ztmp * glob_sum( sfx_opw(:,:) * area(:,:) * tms(:,:) )
+      zbg_sfx_sni = ztmp * glob_sum( sfx_sni(:,:) * area(:,:) * tms(:,:) )
+      zbg_sfx_bom = ztmp * glob_sum( sfx_bom(:,:) * area(:,:) * tms(:,:) )
+      zbg_sfx_sum = ztmp * glob_sum( sfx_sum(:,:) * area(:,:) * tms(:,:) )
+
+      ! Heat budget
+      zbg_ihc      = glob_sum( et_i(:,:) * 1.e-20 ) ! ice heat content  [1.e-20 J]
+      zbg_shc      = glob_sum( et_s(:,:) * 1.e-20 ) ! snow heat content [1.e-20 J]
+      zbg_hfx_dhc  = glob_sum( diag_heat_dhc(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_spr  = glob_sum( hfx_spr(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+
+      zbg_hfx_thd  = glob_sum( hfx_thd(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_dyn  = glob_sum( hfx_dyn(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_res  = glob_sum( hfx_res(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_sub  = glob_sum( hfx_sub(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_snw  = glob_sum( hfx_snw(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_sum  = glob_sum( hfx_sum(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_bom  = glob_sum( hfx_bom(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_bog  = glob_sum( hfx_bog(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_dif  = glob_sum( hfx_dif(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_opw  = glob_sum( hfx_opw(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_out  = glob_sum( hfx_out(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+      zbg_hfx_in   = glob_sum(  hfx_in(:,:) * area(:,:) * tms(:,:) ) ! [in W]
+    
       ! --------------------------------------------- !
       ! 2 - Trends due to forcing and ice growth/melt !
@@ -109,6 +139,6 @@
       z_frc_vol = r1_rau0 * glob_sum( - emp(:,:) * area(:,:) * tms(:,:) ) ! volume fluxes
       z_frc_sal = r1_rau0 * glob_sum(   sfx(:,:) * area(:,:) * tms(:,:) ) ! salt fluxes
-      z_bg_grme = glob_sum( ( diag_bot_gr(:,:) + diag_lat_gr(:,:) + diag_sni_gr(:,:) + diag_dyn_gr(:,:) + &
-                          &    diag_bot_me(:,:) + diag_sur_me(:,:) + diag_res_pr(:,:) ) * area(:,:) * tms(:,:) ) ! volume fluxes
+      z_bg_grme = glob_sum( - ( wfx_bog(:,:) + wfx_opw(:,:) + wfx_sni(:,:) + wfx_dyn(:,:) + &
+                          &     wfx_bom(:,:) + wfx_sum(:,:) + wfx_res(:,:) + wfx_snw(:,:) + wfx_sub(:,:) ) * area(:,:) * tms(:,:) ) ! volume fluxes
       !
       frc_vol  = frc_vol  + z_frc_vol  * rdt_ice
@@ -123,33 +153,64 @@
       ! 3 - Diagnostics writing !
       ! ----------------------- !
-      zindb = MAX( 0.d0 , SIGN( 1.d0 , zbg_ivo - epsi06 ) )
-      !
+      rswitch = MAX( 0._wp , SIGN( 1._wp , zbg_ivo - epsi06 ) )
+      !
+      IF( iom_use('ibgvoltot') )   &
       CALL iom_put( 'ibgvoltot' , zbg_ivo * rhoic * r1_rau0 * 1.e-9        )   ! ice volume (km3 equivalent liquid)         
+      IF( iom_use('sbgvoltot') )   &
       CALL iom_put( 'sbgvoltot' , zbg_svo * rhosn * r1_rau0 * 1.e-9        )   ! snw volume (km3 equivalent liquid)       
+      IF( iom_use('ibgarea') )   &
       CALL iom_put( 'ibgarea'   , zbg_are * 1.e-6                          )   ! ice area   (km2)
-      CALL iom_put( 'ibgsaline' , zindb * zbg_sal / MAX( zbg_ivo, epsi06 ) )   ! ice saline (psu)
-      CALL iom_put( 'ibgtemper' , zindb * zbg_tem / MAX( zbg_ivo, epsi06 ) )   ! ice temper (C)
+      IF( iom_use('ibgsaline') )   &
+      CALL iom_put( 'ibgsaline' , rswitch * zbg_sal / MAX( zbg_ivo, epsi06 ) )   ! ice saline (psu)
+      IF( iom_use('ibgtemper') )   &
+      CALL iom_put( 'ibgtemper' , rswitch * zbg_tem / MAX( zbg_ivo, epsi06 ) )   ! ice temper (C)
       CALL iom_put( 'ibgheatco' , zbg_ihc                                  )   ! ice heat content (1.e20 J)        
       CALL iom_put( 'sbgheatco' , zbg_shc                                  )   ! snw heat content (1.e20 J)
+      IF( iom_use('ibgsaltco') )   &
       CALL iom_put( 'ibgsaltco' , zbg_sal * rhoic * r1_rau0 * 1.e-9        )   ! ice salt content (psu*km3 equivalent liquid)        
 
-      CALL iom_put( 'ibgemp'    , zbg_emp                                  )   ! volume flux emp (m/day liquid)
-      CALL iom_put( 'ibgempbog' , zbg_emp_bog                              )   ! volume flux bottom growth     -(m/day equivalent liquid)
-      CALL iom_put( 'ibgemplag' , zbg_emp_lag                              )   ! volume flux open water growth -
-      CALL iom_put( 'ibgempsig' , zbg_emp_sig                              )   ! volume flux snow ice growth   -
-      CALL iom_put( 'ibgempdyg' , zbg_emp_dyg                              )   ! volume flux dynamic growth    -
-      CALL iom_put( 'ibgempbom' , zbg_emp_bom                              )   ! volume flux bottom melt       -
-      CALL iom_put( 'ibgempsum' , zbg_emp_sum                              )   ! volume flux surface melt      -
-      CALL iom_put( 'ibgempres' , zbg_emp_res                              )   ! volume flux resultant         -
+      CALL iom_put( 'ibgvfx'    , zbg_vfx                                  )   ! volume flux emp (m/day liquid)
+      CALL iom_put( 'ibgvfxbog' , zbg_vfx_bog                              )   ! volume flux bottom growth     -(m/day equivalent liquid)
+      CALL iom_put( 'ibgvfxopw' , zbg_vfx_opw                              )   ! volume flux open water growth -
+      CALL iom_put( 'ibgvfxsni' , zbg_vfx_sni                              )   ! volume flux snow ice growth   -
+      CALL iom_put( 'ibgvfxdyn' , zbg_vfx_dyn                              )   ! volume flux dynamic growth    -
+      CALL iom_put( 'ibgvfxbom' , zbg_vfx_bom                              )   ! volume flux bottom melt       -
+      CALL iom_put( 'ibgvfxsum' , zbg_vfx_sum                              )   ! volume flux surface melt      -
+      CALL iom_put( 'ibgvfxres' , zbg_vfx_res                              )   ! volume flux resultant         -
+      CALL iom_put( 'ibgvfxspr' , zbg_vfx_spr                              )   ! volume flux from snow precip         -
+      CALL iom_put( 'ibgvfxsnw' , zbg_vfx_snw                              )   ! volume flux from snow melt         -
+      CALL iom_put( 'ibgvfxsub' , zbg_vfx_sub                              )   ! volume flux from sublimation         -
           
       CALL iom_put( 'ibgsfx'    , zbg_sfx                                  )   ! salt flux         -(psu*m/day equivalent liquid)       
       CALL iom_put( 'ibgsfxbri' , zbg_sfx_bri                              )   ! salt flux brines  -      
-      CALL iom_put( 'ibgsfxthd' , zbg_sfx_thd                              )   ! salt flux thermo  -    
-      CALL iom_put( 'ibgsfxmec' , zbg_sfx_mec                              )   ! salt flux dynamic -    
+      CALL iom_put( 'ibgsfxdyn' , zbg_sfx_dyn                              )   ! salt flux dynamic -    
       CALL iom_put( 'ibgsfxres' , zbg_sfx_res                              )   ! salt flux result  -    
+      CALL iom_put( 'ibgsfxbog' , zbg_sfx_bog                              )   ! salt flux bottom growth   
+      CALL iom_put( 'ibgsfxopw' , zbg_sfx_opw                              )   ! salt flux open water growth -
+      CALL iom_put( 'ibgsfxsni' , zbg_sfx_sni                              )   ! salt flux snow ice growth   -
+      CALL iom_put( 'ibgsfxbom' , zbg_sfx_bom                              )   ! salt flux bottom melt       -
+      CALL iom_put( 'ibgsfxsum' , zbg_sfx_sum                              )   ! salt flux surface melt      -
+
+      CALL iom_put( 'ibghfxdhc' , zbg_hfx_dhc                              )   ! Heat content variation in snow and ice [W]
+      CALL iom_put( 'ibghfxspr' , zbg_hfx_spr                              )   ! Heat content of snow precip [W]
+
+      CALL iom_put( 'ibghfxres' , zbg_hfx_res                              )   ! 
+      CALL iom_put( 'ibghfxsub' , zbg_hfx_sub                              )   ! 
+      CALL iom_put( 'ibghfxdyn' , zbg_hfx_dyn                              )   ! 
+      CALL iom_put( 'ibghfxthd' , zbg_hfx_thd                              )   ! 
+      CALL iom_put( 'ibghfxsnw' , zbg_hfx_snw                              )   ! 
+      CALL iom_put( 'ibghfxsum' , zbg_hfx_sum                              )   ! 
+      CALL iom_put( 'ibghfxbom' , zbg_hfx_bom                              )   ! 
+      CALL iom_put( 'ibghfxbog' , zbg_hfx_bog                              )   ! 
+      CALL iom_put( 'ibghfxdif' , zbg_hfx_dif                              )   ! 
+      CALL iom_put( 'ibghfxopw' , zbg_hfx_opw                              )   ! 
+      CALL iom_put( 'ibghfxout' , zbg_hfx_out                              )   ! 
+      CALL iom_put( 'ibghfxin'  , zbg_hfx_in                               )   ! 
 
       CALL iom_put( 'ibgfrcvol' , frc_vol * 1.e-9                          )   ! vol - forcing     (km3 equivalent liquid) 
       CALL iom_put( 'ibgfrcsfx' , frc_sal * 1.e-9                          )   ! sal - forcing     (psu*km3 equivalent liquid)   
-      CALL iom_put( 'ibggrme'   , bg_grme * rhoic * r1_rau0 * 1.e-9        )   ! vol growth + melt (km3 equivalent liquid)         
+      IF( iom_use('ibgvolgrm') )   &
+      CALL iom_put( 'ibgvolgrm' , bg_grme * r1_rau0 * 1.e-9                )   ! vol growth + melt (km3 equivalent liquid)         
+
       !
       IF( lrst_ice )   CALL lim_diahsb_rst( numit, 'WRITE' )
@@ -190,7 +251,7 @@
       ! 2 - initial conservation variables !
       ! ---------------------------------- !
-      !frc_vol = 0.d0                                           ! volume       trend due to forcing
-      !frc_sal = 0.d0                                           ! salt content   -    -   -    -         
-      !bg_grme = 0.d0                                           ! ice growth + melt volume trend
+      !frc_vol = 0._wp                                          ! volume       trend due to forcing
+      !frc_sal = 0._wp                                          ! salt content   -    -   -    -         
+      !bg_grme = 0._wp                                          ! ice growth + melt volume trend
       !
       CALL lim_diahsb_rst( nstart, 'READ' )  !* read or initialize all required files
@@ -226,8 +287,8 @@
            IF(lwp) WRITE(numout,*) ' lim_diahsb at initial state '
            IF(lwp) WRITE(numout,*) '~~~~~~~'
-           frc_vol  = 0.d0                                           
-           frc_sal  = 0.d0                                                  
-           bg_grme  = 0.d0                                        
-       ENDIF	
+           frc_vol  = 0._wp                                          
+           frc_sal  = 0._wp                                                 
+           bg_grme  = 0._wp                                       
+       ENDIF
 
      ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN   ! Create restart file
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limdyn.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limdyn.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limdyn.F90	(revision 5075)
@@ -30,4 +30,5 @@
    USE lib_fortran      ! glob_sum
    USE timing          ! Timing
+   USE limcons        ! conservation tests
 
    IMPLICIT NONE
@@ -63,9 +64,9 @@
       INTEGER  ::   i_j1, i_jpj       ! Starting/ending j-indices for rheology
       REAL(wp) ::   zcoef             ! local scalar
-      REAL(wp), POINTER, DIMENSION(:)   ::   zind           ! i-averaged indicator of sea-ice
+      REAL(wp), POINTER, DIMENSION(:)   ::   zswitch        ! i-averaged indicator of sea-ice
       REAL(wp), POINTER, DIMENSION(:)   ::   zmsk           ! i-averaged of tmask
       REAL(wp), POINTER, DIMENSION(:,:) ::   zu_io, zv_io   ! ice-ocean velocity
-      REAL(wp) :: zchk_v_i, zchk_smv, zchk_fs, zchk_fw, zchk_v_i_b, zchk_smv_b, zchk_fs_b, zchk_fw_b ! Check conservation (C Rousset)
-      REAL(wp) :: zchk_vmin, zchk_amin, zchk_amax ! Check errors (C Rousset)
+      !
+      REAL(wp) :: zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b 
      !!---------------------------------------------------------------------
 
@@ -73,16 +74,5 @@
 
       CALL wrk_alloc( jpi, jpj, zu_io, zv_io )
-      CALL wrk_alloc( jpj, zind, zmsk )
-
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_v_i_b = glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_smv_b = glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_fw_b  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) )
-         zchk_fs_b  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) )
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      CALL wrk_alloc( jpj, zswitch, zmsk )
 
       IF( kt == nit000 )   CALL lim_dyn_init   ! Initialization (first time-step only)
@@ -90,6 +80,9 @@
       IF( ln_limdyn ) THEN
          !
-         old_u_ice(:,:) = u_ice(:,:) * tmu(:,:)
-         old_v_ice(:,:) = v_ice(:,:) * tmv(:,:)
+         ! conservation test
+         IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limdyn', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
+
+         u_ice_b(:,:) = u_ice(:,:) * tmu(:,:)
+         v_ice_b(:,:) = v_ice(:,:) * tmv(:,:)
 
          ! Rheology (ice dynamics)
@@ -107,5 +100,5 @@
             !
             DO jj = 1, jpj
-               zind(jj) = SUM( 1.0 - at_i(:,jj) )   ! = REAL(jpj) if ocean everywhere on a j-line
+               zswitch(jj) = SUM( 1.0 - at_i(:,jj) )   ! = REAL(jpj) if ocean everywhere on a j-line
                zmsk(jj) = SUM( tmask(:,jj,1)    )   ! = 0         if land  everywhere on a j-line
             END DO
@@ -117,5 +110,5 @@
                i_j1  = njeq
                i_jpj = jpj
-               DO WHILE ( i_j1 <= jpj .AND. zind(i_j1) == FLOAT(jpi) .AND. zmsk(i_j1) /=0 )
+               DO WHILE ( i_j1 <= jpj .AND. zswitch(i_j1) == FLOAT(jpi) .AND. zmsk(i_j1) /=0 )
                   i_j1 = i_j1 + 1
                END DO
@@ -127,5 +120,5 @@
                i_j1  =  1
                i_jpj = njeq
-               DO WHILE ( i_jpj >= 1 .AND. zind(i_jpj) == FLOAT(jpi) .AND. zmsk(i_jpj) /=0 )
+               DO WHILE ( i_jpj >= 1 .AND. zswitch(i_jpj) == FLOAT(jpi) .AND. zmsk(i_jpj) /=0 )
                   i_jpj = i_jpj - 1
                END DO
@@ -139,5 +132,5 @@
                !                                 ! latitude strip
                i_j1  = 1
-               DO WHILE ( i_j1 <= jpj .AND. zind(i_j1) == FLOAT(jpi) .AND. zmsk(i_j1) /=0 )
+               DO WHILE ( i_j1 <= jpj .AND. zswitch(i_j1) == FLOAT(jpi) .AND. zmsk(i_j1) /=0 )
                   i_j1 = i_j1 + 1
                END DO
@@ -145,5 +138,5 @@
 
                i_jpj  = jpj
-               DO WHILE ( i_jpj >= 1  .AND. zind(i_jpj) == FLOAT(jpi) .AND. zmsk(i_jpj) /=0 )
+               DO WHILE ( i_jpj >= 1  .AND. zswitch(i_jpj) == FLOAT(jpi) .AND. zmsk(i_jpj) /=0 )
                   i_jpj = i_jpj - 1
                END DO
@@ -171,4 +164,7 @@
             END DO
          END DO
+         !
+         ! conservation test
+         IF( ln_limdiahsb ) CALL lim_cons_hsm(1, 'limdyn', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
          !
       ELSE      ! no ice dynamics : transmit directly the atmospheric stress to the ocean
@@ -224,30 +220,6 @@
       ENDIF
       !
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_fs  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) ) - zchk_fs_b
-         zchk_fw  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) ) - zchk_fw_b
- 
-         zchk_v_i = ( glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_v_i_b - ( zchk_fw / rhoic ) ) / rdt_ice
-         zchk_smv = ( glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_smv_b ) / rdt_ice + ( zchk_fs / rhoic )
-
-         zchk_vmin = glob_min(v_i)
-         zchk_amax = glob_max(SUM(a_i,dim=3))
-         zchk_amin = glob_min(a_i)
-
-         IF(lwp) THEN
-            IF ( ABS( zchk_v_i   ) >  1.e-5 ) WRITE(numout,*) 'violation volume [m3/day]     (limdyn) = ',(zchk_v_i * rday)
-            IF ( ABS( zchk_smv   ) >  1.e-4 ) WRITE(numout,*) 'violation saline [psu*m3/day] (limdyn) = ',(zchk_smv * rday)
-            IF ( zchk_vmin <  0.            ) WRITE(numout,*) 'violation v_i<0  [mm]         (limdyn) = ',(zchk_vmin * 1.e-3)
-            !IF ( zchk_amax >  amax+1.e-10   ) WRITE(numout,*) 'violation a_i>amax            (limdyn) = ',zchk_amax
-            IF ( zchk_amin <  0.            ) WRITE(numout,*) 'violation a_i<0               (limdyn) = ',zchk_amin
-         ENDIF
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
-
       CALL wrk_dealloc( jpi, jpj, zu_io, zv_io )
-      CALL wrk_dealloc( jpj, zind, zmsk )
+      CALL wrk_dealloc( jpj, zswitch, zmsk )
       !
       IF( nn_timing == 1 )  CALL timing_stop('limdyn')
@@ -269,8 +241,7 @@
       !!-------------------------------------------------------------------
       INTEGER  ::   ios                 ! Local integer output status for namelist read
-      NAMELIST/namicedyn/ epsd, alpha,     &
-         &                dm, nbiter, nbitdr, om, resl, cw, angvg, pstar,   &
-         &                c_rhg, etamn, creepl, ecc, ahi0, &
-         &                nevp, telast, alphaevp, hminrhg
+      NAMELIST/namicedyn/ epsd, om, cw, pstar,   &
+         &                c_rhg, creepl, ecc, ahi0,     &
+         &                nevp, relast, alphaevp, hminrhg
       !!-------------------------------------------------------------------
 
@@ -289,36 +260,22 @@
          WRITE(numout,*) '~~~~~~~~~~~~'
          WRITE(numout,*) '   tolerance parameter                              epsd   = ', epsd
-         WRITE(numout,*) '   coefficient for semi-implicit coriolis           alpha  = ', alpha
-         WRITE(numout,*) '   diffusion constant for dynamics                  dm     = ', dm
-         WRITE(numout,*) '   number of sub-time steps for relaxation          nbiter = ', nbiter
-         WRITE(numout,*) '   maximum number of iterations for relaxation      nbitdr = ', nbitdr
          WRITE(numout,*) '   relaxation constant                              om     = ', om
-         WRITE(numout,*) '   maximum value for the residual of relaxation     resl   = ', resl
          WRITE(numout,*) '   drag coefficient for oceanic stress              cw     = ', cw
-         WRITE(numout,*) '   turning angle for oceanic stress                 angvg  = ', angvg
          WRITE(numout,*) '   first bulk-rheology parameter                    pstar  = ', pstar
          WRITE(numout,*) '   second bulk-rhelogy parameter                    c_rhg  = ', c_rhg
-         WRITE(numout,*) '   minimun value for viscosity                      etamn  = ', etamn
          WRITE(numout,*) '   creep limit                                      creepl = ', creepl
          WRITE(numout,*) '   eccentricity of the elliptical yield curve       ecc    = ', ecc
          WRITE(numout,*) '   horizontal diffusivity coeff. for sea-ice        ahi0   = ', ahi0
          WRITE(numout,*) '   number of iterations for subcycling              nevp   = ', nevp
-         WRITE(numout,*) '   timescale for elastic waves                      telast = ', telast
+         WRITE(numout,*) '   ratio of elastic timescale over ice time step    relast = ', relast
          WRITE(numout,*) '   coefficient for the solution of int. stresses  alphaevp = ', alphaevp
          WRITE(numout,*) '   min ice thickness for rheology calculations     hminrhg = ', hminrhg
       ENDIF
       !
-      IF( angvg /= 0._wp ) THEN
-         CALL ctl_warn( 'lim_dyn_init: turning angle for oceanic stress not properly coded for EVP ',   &
-            &           '(see limsbc module). We force  angvg = 0._wp'  )
-         angvg = 0._wp
-      ENDIF
-      
       usecc2 = 1._wp / ( ecc * ecc )
       rhoco  = rau0  * cw
-      angvg  = angvg * rad
-      sangvg = SIN( angvg )
-      cangvg = COS( angvg )
-      pstarh = pstar * 0.5_wp
+
+      ! elastic damping
+      telast = relast * rdt_ice
 
       !  Diffusion coefficients.
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limhdf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limhdf.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limhdf.F90	(revision 5075)
@@ -83,10 +83,8 @@
       zdiv0(:, 1 ) = 0._wp
       zdiv0(:,jpj) = 0._wp
-      IF( .NOT.lk_vopt_loop ) THEN
-         zflu (jpi,:) = 0._wp   
-         zflv (jpi,:) = 0._wp
-         zdiv0(1,  :) = 0._wp
-         zdiv0(jpi,:) = 0._wp
-      ENDIF
+      zflu (jpi,:) = 0._wp   
+      zflv (jpi,:) = 0._wp
+      zdiv0(1,  :) = 0._wp
+      zdiv0(jpi,:) = 0._wp
 
       zconv = 1._wp           !==  horizontal diffusion using a Crant-Nicholson scheme  ==!
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limistate.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limistate.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limistate.F90	(revision 5075)
@@ -6,5 +6,5 @@
    !! History :  2.0  ! 2004-01 (C. Ethe, G. Madec)  Original code
    !!            4.0  ! 2011-02 (G. Madec) dynamical allocation
-   !!             -   ! 2012    (C. Rousset) add par_oce (for jp_sal)...bug?
+   !!             -   ! 2014    (C. Rousset) add N/S initializations
    !!----------------------------------------------------------------------
 #if defined key_lim3
@@ -26,5 +26,4 @@
    USE dom_ice          ! sea-ice domain
    USE in_out_manager   ! I/O manager
-   USE lbclnk           ! lateral boundary condition - MPP exchanges
    USE lib_mpp          ! MPP library
    USE lib_fortran      ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
@@ -36,16 +35,18 @@
    PUBLIC   lim_istate      ! routine called by lim_init.F90
 
-   !! * Module variables
    !                          !!** init namelist (namiceini) **
-   REAL(wp) ::   ttest   ! threshold water temperature for initial sea ice
-   REAL(wp) ::   hninn   ! initial snow thickness in the north
-   REAL(wp) ::   hnins   ! initial snow thickness in the south
-   REAL(wp) ::   hginn   ! initial ice thickness in the north
-   REAL(wp) ::   hgins   ! initial ice thickness in the south
-   REAL(wp) ::   aginn   ! initial leads area in the north
-   REAL(wp) ::   agins   ! initial leads area in the south
-   REAL(wp) ::   sinn    ! initial salinity 
-   REAL(wp) ::   sins  
-
+   REAL(wp) ::   thres_sst   ! threshold water temperature for initial sea ice
+   REAL(wp) ::   hts_ini_n   ! initial snow thickness in the north
+   REAL(wp) ::   hts_ini_s   ! initial snow thickness in the south
+   REAL(wp) ::   hti_ini_n   ! initial ice thickness in the north
+   REAL(wp) ::   hti_ini_s   ! initial ice thickness in the south
+   REAL(wp) ::   ati_ini_n   ! initial leads area in the north
+   REAL(wp) ::   ati_ini_s   ! initial leads area in the south
+   REAL(wp) ::   smi_ini_n   ! initial salinity 
+   REAL(wp) ::   smi_ini_s   ! initial salinity
+   REAL(wp) ::   tmi_ini_n   ! initial temperature
+   REAL(wp) ::   tmi_ini_s   ! initial temperature
+
+   LOGICAL  ::  ln_limini    ! initialization or not
    !!----------------------------------------------------------------------
    !!   LIM 3.0,  UCL-LOCEAN-IPSL (2008)
@@ -53,5 +54,4 @@
    !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
    !!----------------------------------------------------------------------
-
 CONTAINS
 
@@ -77,5 +77,5 @@
       !!
       !! ** Notes   : o_i, t_su, t_s, t_i, s_i must be filled everywhere, even
-      !!              where there is no ice (clem: I do not know why but it is mandatory) 
+      !!              where there is no ice (clem: I do not know why, is it mandatory?) 
       !!
       !! History :
@@ -90,16 +90,17 @@
       INTEGER    :: i_hemis, i_fill, jl0  
       REAL(wp)   :: ztest_1, ztest_2, ztest_3, ztest_4, ztests, zsigma, zarg, zA, zV, zA_cons, zV_cons, zconv
-      REAL(wp), POINTER, DIMENSION(:)     :: zhm_i_ini, zat_i_ini, zvt_i_ini, zhm_s_ini, zsm_i_ini
-      REAL(wp), POINTER, DIMENSION(:,:)   :: zht_i_ini, za_i_ini, zv_i_ini
-      REAL(wp), POINTER, DIMENSION(:,:)   :: zidto    ! ice indicator
+      REAL(wp), POINTER, DIMENSION(:)     :: zht_i_ini, zat_i_ini, zvt_i_ini, zht_s_ini, zsm_i_ini, ztm_i_ini
+      REAL(wp), POINTER, DIMENSION(:,:)   :: zh_i_ini, za_i_ini, zv_i_ini
+      REAL(wp), POINTER, DIMENSION(:,:)   :: zswitch    ! ice indicator
       INTEGER,  POINTER, DIMENSION(:,:)   :: zhemis   ! hemispheric index
       !--------------------------------------------------------------------
 
-      CALL wrk_alloc( jpi, jpj, zidto )
+      CALL wrk_alloc( jpi, jpj, zswitch )
       CALL wrk_alloc( jpi, jpj, zhemis )
-      CALL wrk_alloc( jpl,   2, zht_i_ini,  za_i_ini,  zv_i_ini )
-      CALL wrk_alloc(   2,      zhm_i_ini, zat_i_ini, zvt_i_ini, zhm_s_ini, zsm_i_ini )
-
-      epsi20   = 1.0e-20
+      CALL wrk_alloc( jpl,   2, zh_i_ini,  za_i_ini,  zv_i_ini )
+      CALL wrk_alloc(   2,      zht_i_ini, zat_i_ini, zvt_i_ini, zht_s_ini, zsm_i_ini, ztm_i_ini )
+
+      epsi20   = 1.e-20_wp
+
       IF(lwp) WRITE(numout,*)
       IF(lwp) WRITE(numout,*) 'lim_istate : Ice initialization '
@@ -112,27 +113,31 @@
       CALL lim_istate_init     !  reading the initials parameters of the ice
 
-!!gm  in lim2  the initialisation if only done if required in the namelist :
-!!gm      IF( .NOT. ln_limini ) THEN
-!!gm  this should be added in lim3 namelist...
+      ! surface temperature
+      DO jl = 1, jpl ! loop over categories
+         t_su  (:,:,jl) = rtt * tms(:,:)
+         tn_ice(:,:,jl) = rtt * tms(:,:)
+      END DO
+
+      ! basal temperature (considered at freezing point)
+      t_bo(:,:) = ( eos_fzp( tsn(:,:,1,jp_sal) ) + rt0 ) * tms(:,:) 
+
+      IF( ln_limini ) THEN
 
       !--------------------------------------------------------------------
       ! 2) Basal temperature, ice mask and hemispheric index
       !--------------------------------------------------------------------
-
-      ! Basal temperature is set to the freezing point of seawater in Celsius
-      t_bo(:,:) = tfreez( tsn(:,:,1,jp_sal) ) * tmask(:,:,1)       ! freezing/melting point of sea water [Celcius]
 
       DO jj = 1, jpj                                       ! ice if sst <= t-freez + ttest
          DO ji = 1, jpi
-            IF( tsn(ji,jj,1,jp_tem)  - t_bo(ji,jj) >= ttest ) THEN   ;   zidto(ji,jj) = 0._wp      ! no ice
-            ELSE                                                     ;   zidto(ji,jj) = 1._wp      !    ice
+            IF( ( tsn(ji,jj,1,jp_tem)  - ( t_bo(ji,jj) - rt0 ) ) * tms(ji,jj) >= thres_sst ) THEN 
+               zswitch(ji,jj) = 0._wp * tms(ji,jj)    ! no ice
+            ELSE                                                                                   
+               zswitch(ji,jj) = 1._wp * tms(ji,jj)    !    ice
             ENDIF
          END DO
       END DO
 
-      t_bo(:,:) = t_bo(:,:) + rt0                          ! conversion to Kelvin
 
       ! Hemispheric index
-      ! MV 2011 new initialization
       DO jj = 1, jpj
          DO ji = 1, jpi
@@ -144,5 +149,4 @@
          END DO
       END DO
-      ! END MV 2011 new initialization
 
       !--------------------------------------------------------------------
@@ -153,11 +157,12 @@
       ! 3.1) Hemisphere-dependent arrays
       !-----------------------------
-      ! assign initial thickness, concentration, snow depth and salinity to
-      ! an hemisphere-dependent array
-      zhm_i_ini(1) = hginn ; zhm_i_ini(2) = hgins  ! ice thickness
-      zat_i_ini(1) = aginn ; zat_i_ini(2) = agins  ! ice concentration
-      zvt_i_ini(:) = zhm_i_ini(:) * zat_i_ini(:)   ! ice volume
-      zhm_s_ini(1) = hninn ; zhm_s_ini(2) = hnins  ! snow depth
-      zsm_i_ini(1) = sinn  ; zsm_i_ini(2) = sins   ! bulk ice salinity
+      ! assign initial thickness, concentration, snow depth and salinity to an hemisphere-dependent array
+      zht_i_ini(1) = hti_ini_n ; zht_i_ini(2) = hti_ini_s  ! ice thickness
+      zht_s_ini(1) = hts_ini_n ; zht_s_ini(2) = hts_ini_s  ! snow depth
+      zat_i_ini(1) = ati_ini_n ; zat_i_ini(2) = ati_ini_s  ! ice concentration
+      zsm_i_ini(1) = smi_ini_n ; zsm_i_ini(2) = smi_ini_s  ! bulk ice salinity
+      ztm_i_ini(1) = tmi_ini_n ; ztm_i_ini(2) = tmi_ini_s  ! temperature (ice and snow)
+
+      zvt_i_ini(:) = zht_i_ini(:) * zat_i_ini(:)   ! ice volume
 
       !---------------------------------------------------------------------
@@ -183,35 +188,35 @@
             ! *** 1 category to fill
             IF ( i_fill .EQ. 1 ) THEN
-               zht_i_ini(1,i_hemis)       = zhm_i_ini(i_hemis)
-               za_i_ini(1,i_hemis)        = zat_i_ini(i_hemis)
-               zht_i_ini(2:jpl,i_hemis)   = 0._wp
-               za_i_ini(2:jpl,i_hemis)    = 0._wp
+               zh_i_ini(1,i_hemis)       = zht_i_ini(i_hemis)
+               za_i_ini(1,i_hemis)       = zat_i_ini(i_hemis)
+               zh_i_ini(2:jpl,i_hemis)   = 0._wp
+               za_i_ini(2:jpl,i_hemis)   = 0._wp
             ELSE
 
-            ! *** >1 categores to fill
-            !--- Ice thicknesses in the i_fill - 1 first categories
+               ! *** >1 categores to fill
+               !--- Ice thicknesses in the i_fill - 1 first categories
                DO jl = 1, i_fill - 1
-                  zht_i_ini(jl,i_hemis)    = 0.5 * ( hi_max(jl) + hi_max(jl-1) )
+                  zh_i_ini(jl,i_hemis)    = 0.5 * ( hi_max(jl) + hi_max(jl-1) )
                END DO
-
-            !--- jl0: most likely index where cc will be maximum
+               
+               !--- jl0: most likely index where cc will be maximum
                DO jl = 1, jpl
-                  IF ( ( zhm_i_ini(i_hemis) .GT. hi_max(jl-1) ) .AND. &
-                       ( zhm_i_ini(i_hemis) .LE. hi_max(jl)   ) ) THEN
+                  IF ( ( zht_i_ini(i_hemis) .GT. hi_max(jl-1) ) .AND. &
+                     ( zht_i_ini(i_hemis) .LE. hi_max(jl)   ) ) THEN
                      jl0 = jl
                   ENDIF
                END DO
                jl0 = MIN(jl0, i_fill)
-
-            !--- Concentrations
+               
+               !--- Concentrations
                za_i_ini(jl0,i_hemis)      = zat_i_ini(i_hemis) / SQRT(REAL(jpl))
                DO jl = 1, i_fill - 1
                   IF ( jl .NE. jl0 ) THEN
-                     zsigma               = 0.5 * zhm_i_ini(i_hemis)
-                     zarg                 = ( zht_i_ini(jl,i_hemis) - zhm_i_ini(i_hemis) ) / zsigma
+                     zsigma               = 0.5 * zht_i_ini(i_hemis)
+                     zarg                 = ( zh_i_ini(jl,i_hemis) - zht_i_ini(i_hemis) ) / zsigma
                      za_i_ini(jl,i_hemis) = za_i_ini(jl0,i_hemis) * EXP(-zarg**2)
                   ENDIF
-               END DO 
-
+               END DO
+               
                zA = 0. ! sum of the areas in the jpl categories 
                DO jl = 1, i_fill - 1
@@ -221,14 +226,14 @@
                IF ( i_fill .LT. jpl ) za_i_ini(i_fill+1:jpl, i_hemis) = 0._wp
          
-            !--- Ice thickness in the last category
+               !--- Ice thickness in the last category
                zV = 0. ! sum of the volumes of the N-1 categories
                DO jl = 1, i_fill - 1
-                  zV = zV + za_i_ini(jl,i_hemis)*zht_i_ini(jl,i_hemis)
+                  zV = zV + za_i_ini(jl,i_hemis)*zh_i_ini(jl,i_hemis)
                END DO
-               zht_i_ini(i_fill,i_hemis) = ( zvt_i_ini(i_hemis) - zV ) / za_i_ini(i_fill,i_hemis) 
-               IF ( i_fill .LT. jpl ) zht_i_ini(i_fill+1:jpl, i_hemis) = 0._wp
-
-            !--- volumes
-               zv_i_ini(:,i_hemis) = za_i_ini(:,i_hemis) * zht_i_ini(:,i_hemis)
+               zh_i_ini(i_fill,i_hemis) = ( zvt_i_ini(i_hemis) - zV ) / za_i_ini(i_fill,i_hemis) 
+               IF ( i_fill .LT. jpl ) zh_i_ini(i_fill+1:jpl, i_hemis) = 0._wp
+
+               !--- volumes
+               zv_i_ini(:,i_hemis) = za_i_ini(:,i_hemis) * zh_i_ini(:,i_hemis)
                IF ( i_fill .LT. jpl ) zv_i_ini(i_fill+1:jpl, i_hemis) = 0._wp
 
@@ -262,10 +267,10 @@
 
             ! Test 3: thickness of the last category is in-bounds ?
-            IF ( zht_i_ini(i_fill, i_hemis) .GT. hi_max(i_fill-1) ) THEN
+            IF ( zh_i_ini(i_fill, i_hemis) .GT. hi_max(i_fill-1) ) THEN
                ztest_3 = 1
             ELSE
                ! this write is useful
-               IF(lwp) WRITE(numout,*) ' * TEST 3 THICKNESS OF THE LAST CATEGORY OUT OF BOUNDS *** zht_i_ini(i_fill,i_hemis) = ', &
-               zht_i_ini(i_fill,i_hemis), ' hi_max(jpl-1) = ', hi_max(i_fill-1)
+               IF(lwp) WRITE(numout,*) ' * TEST 3 THICKNESS OF THE LAST CATEGORY OUT OF BOUNDS *** zh_i_ini(i_fill,i_hemis) = ', &
+               zh_i_ini(i_fill,i_hemis), ' hi_max(jpl-1) = ', hi_max(i_fill-1)
                ztest_3 = 0
             ENDIF
@@ -288,17 +293,14 @@
 
       IF(lwp) THEN 
-         WRITE(numout,*), ' ztests : ', ztests
+         WRITE(numout,*) ' ztests : ', ztests
          IF ( ztests .NE. 4 ) THEN
             WRITE(numout,*)
-            WRITE(numout,*), ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! '
-            WRITE(numout,*), ' !!!! RED ALERT                  !!! '
-            WRITE(numout,*), ' !!!! BIIIIP BIIIP BIIIIP BIIIIP !!!'
-            WRITE(numout,*), ' !!!! Something is wrong in the LIM3 initialization procedure '
-            WRITE(numout,*), ' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! '
+            WRITE(numout,*) ' !!!! ALERT                  !!! '
+            WRITE(numout,*) ' !!!! Something is wrong in the LIM3 initialization procedure '
             WRITE(numout,*)
-            WRITE(numout,*), ' *** ztests is not equal to 4 '
-            WRITE(numout,*), ' *** ztest_i (i=1,4) = ', ztest_1, ztest_2, ztest_3, ztest_4
-            WRITE(numout,*), ' zat_i_ini : ', zat_i_ini(i_hemis)
-            WRITE(numout,*), ' zhm_i_ini : ', zhm_i_ini(i_hemis)
+            WRITE(numout,*) ' *** ztests is not equal to 4 '
+            WRITE(numout,*) ' *** ztest_i (i=1,4) = ', ztest_1, ztest_2, ztest_3, ztest_4
+            WRITE(numout,*) ' zat_i_ini : ', zat_i_ini(i_hemis)
+            WRITE(numout,*) ' zht_i_ini : ', zht_i_ini(i_hemis)
          ENDIF ! ztests .NE. 4
       ENDIF
@@ -314,10 +316,10 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               a_i(ji,jj,jl)   = zidto(ji,jj) * za_i_ini (jl,zhemis(ji,jj))  ! concentration
-               ht_i(ji,jj,jl)  = zidto(ji,jj) * zht_i_ini(jl,zhemis(ji,jj))  ! ice thickness
-               ht_s(ji,jj,jl)  = ht_i(ji,jj,jl) * ( zhm_s_ini( zhemis(ji,jj) ) / zhm_i_ini( zhemis(ji,jj) ) )  ! snow depth
-               sm_i(ji,jj,jl)  = zidto(ji,jj) * zsm_i_ini(zhemis(ji,jj)) + ( 1._wp - zidto(ji,jj) ) * s_i_min ! salinity
-               o_i(ji,jj,jl)   = zidto(ji,jj) * 1._wp + ( 1._wp - zidto(ji,jj) ) ! age
-               t_su(ji,jj,jl)  = zidto(ji,jj) * 270.0 + ( 1._wp - zidto(ji,jj) ) * 270.0 ! surf temp
+               a_i(ji,jj,jl)   = zswitch(ji,jj) * za_i_ini (jl,zhemis(ji,jj))  ! concentration
+               ht_i(ji,jj,jl)  = zswitch(ji,jj) * zh_i_ini(jl,zhemis(ji,jj))  ! ice thickness
+               ht_s(ji,jj,jl)  = ht_i(ji,jj,jl) * ( zht_s_ini( zhemis(ji,jj) ) / zht_i_ini( zhemis(ji,jj) ) )  ! snow depth
+               sm_i(ji,jj,jl)  = zswitch(ji,jj) * zsm_i_ini(zhemis(ji,jj)) !+ ( 1._wp - zswitch(ji,jj) ) * s_i_min ! salinity
+               o_i(ji,jj,jl)   = zswitch(ji,jj) * 1._wp + ( 1._wp - zswitch(ji,jj) ) ! age
+               t_su(ji,jj,jl)  = zswitch(ji,jj) * ztm_i_ini(zhemis(ji,jj)) + ( 1._wp - zswitch(ji,jj) ) * rtt ! surf temp
 
                ! This case below should not be used if (ht_s/ht_i) is ok in namelist
@@ -343,10 +345,10 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                   t_s(ji,jj,jk,jl) = zidto(ji,jj) * 270.0 + ( 1._wp - zidto(ji,jj) ) * rtt
+                   t_s(ji,jj,jk,jl) = zswitch(ji,jj) * ztm_i_ini(zhemis(ji,jj)) + ( 1._wp - zswitch(ji,jj) ) * rtt
                    ! Snow energy of melting
-                   e_s(ji,jj,jk,jl) = zidto(ji,jj) * rhosn * ( cpic * ( rtt - t_s(ji,jj,jk,jl) ) + lfus )
+                   e_s(ji,jj,jk,jl) = zswitch(ji,jj) * rhosn * ( cpic * ( rtt - t_s(ji,jj,jk,jl) ) + lfus )
                    ! Change dimensions
                    e_s(ji,jj,jk,jl) = e_s(ji,jj,jk,jl) / unit_fac
-                   ! Multiply by volume, so that heat content in 10^9 Joules
+                   ! Multiply by volume, so that heat content in Joules
                    e_s(ji,jj,jk,jl) = e_s(ji,jj,jk,jl) * area(ji,jj) * v_s(ji,jj,jl) / nlay_s
                END DO ! ji
@@ -360,10 +362,10 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                   t_i(ji,jj,jk,jl) = zidto(ji,jj) * 270.00 + ( 1._wp - zidto(ji,jj) ) * rtt 
-                   s_i(ji,jj,jk,jl) = zidto(ji,jj) * zsm_i_ini(zhemis(ji,jj)) + ( 1._wp - zidto(ji,jj) ) * s_i_min
+                   t_i(ji,jj,jk,jl) = zswitch(ji,jj) * ztm_i_ini(zhemis(ji,jj)) + ( 1._wp - zswitch(ji,jj) ) * rtt 
+                   s_i(ji,jj,jk,jl) = zswitch(ji,jj) * zsm_i_ini(zhemis(ji,jj)) !+ ( 1._wp - zswitch(ji,jj) ) * s_i_min
                    ztmelts          = - tmut * s_i(ji,jj,jk,jl) + rtt !Melting temperature in K
 
                    ! heat content per unit volume
-                   e_i(ji,jj,jk,jl) = zidto(ji,jj) * rhoic * (   cpic    * ( ztmelts - t_i(ji,jj,jk,jl) ) &
+                   e_i(ji,jj,jk,jl) = zswitch(ji,jj) * rhoic * (   cpic    * ( ztmelts - t_i(ji,jj,jk,jl) ) &
                       +   lfus    * ( 1._wp - (ztmelts-rtt) / MIN((t_i(ji,jj,jk,jl)-rtt),-epsi20) ) &
                       -   rcp     * ( ztmelts - rtt ) )
@@ -372,6 +374,5 @@
                    e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) / unit_fac 
 
-                   ! Mutliply by ice volume, and divide by number of layers 
-                   ! to get heat content in 10^9 J
+                   ! Mutliply by ice volume, and divide by number of layers to get heat content in J
                    e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * area(ji,jj) * v_i(ji,jj,jl) / nlay_i
                END DO ! ji
@@ -380,8 +381,40 @@
       END DO ! jk
 
+      tn_ice (:,:,:) = t_su (:,:,:)
+
+      ELSE 
+         ! if ln_limini=false
+         a_i  (:,:,:) = 0._wp
+         v_i  (:,:,:) = 0._wp
+         v_s  (:,:,:) = 0._wp
+         smv_i(:,:,:) = 0._wp
+         oa_i (:,:,:) = 0._wp
+         ht_i (:,:,:) = 0._wp
+         ht_s (:,:,:) = 0._wp
+         sm_i (:,:,:) = 0._wp
+         o_i  (:,:,:) = 0._wp
+
+         e_i(:,:,:,:) = 0._wp
+         e_s(:,:,:,:) = 0._wp
+
+         DO jl = 1, jpl
+            DO jk = 1, nlay_i
+               t_i(:,:,jk,jl) = rtt * tms(:,:)
+            END DO
+            DO jk = 1, nlay_s
+               t_s(:,:,jk,jl) = rtt * tms(:,:)
+            END DO
+         END DO
+      
+      ENDIF ! ln_limini
+      
+      at_i (:,:) = 0.0_wp
+      DO jl = 1, jpl
+         at_i (:,:) = at_i (:,:) + a_i (:,:,jl)
+      END DO
+      !
       !--------------------------------------------------------------------
       ! 4) Global ice variables for output diagnostics                    | 
       !--------------------------------------------------------------------
-      fsbbq (:,:)     = 0._wp
       u_ice (:,:)     = 0._wp
       v_ice (:,:)     = 0._wp
@@ -390,8 +423,4 @@
       stress12_i(:,:) = 0._wp
 
-# if defined key_coupled
-      albege(:,:)   = 0.8 * tms(:,:)
-# endif
-
       !--------------------------------------------------------------------
       ! 5) Moments for advection
@@ -428,52 +457,9 @@
       sxyage (:,:,:)  = 0._wp
 
-      !--------------------------------------------------------------------
-      ! 6) Lateral boundary conditions                                    | 
-      !--------------------------------------------------------------------
-
-      DO jl = 1, jpl
-
-         CALL lbc_lnk( a_i(:,:,jl)  , 'T', 1. )
-         CALL lbc_lnk( v_i(:,:,jl)  , 'T', 1. )
-         CALL lbc_lnk( v_s(:,:,jl)  , 'T', 1. )
-         CALL lbc_lnk( smv_i(:,:,jl), 'T', 1. )
-         CALL lbc_lnk( oa_i(:,:,jl) , 'T', 1. )
-
-         CALL lbc_lnk( ht_i(:,:,jl) , 'T', 1. )
-         CALL lbc_lnk( ht_s(:,:,jl) , 'T', 1. )
-         CALL lbc_lnk( sm_i(:,:,jl) , 'T', 1. )
-         CALL lbc_lnk( o_i(:,:,jl)  , 'T', 1. )
-         CALL lbc_lnk( t_su(:,:,jl) , 'T', 1. )
-         DO jk = 1, nlay_s
-            CALL lbc_lnk(t_s(:,:,jk,jl), 'T', 1. )
-            CALL lbc_lnk(e_s(:,:,jk,jl), 'T', 1. )
-         END DO
-         DO jk = 1, nlay_i
-            CALL lbc_lnk(t_i(:,:,jk,jl), 'T', 1. )
-            CALL lbc_lnk(e_i(:,:,jk,jl), 'T', 1. )
-         END DO
-         !
-         a_i(:,:,jl) = tms(:,:) * a_i(:,:,jl)
-      END DO
-      
-      at_i (:,:) = 0.0_wp
-      DO jl = 1, jpl
-         at_i (:,:) = at_i (:,:) + a_i (:,:,jl)
-      END DO
-
-      CALL lbc_lnk( at_i , 'T', 1. )
-      at_i(:,:) = tms(:,:) * at_i(:,:)                       ! put 0 over land
-      !
-      CALL lbc_lnk( fsbbq  , 'T', 1. )
-      !
-      !--------------------------------------------------------------------
-      ! 6) ????                                                           | 
-      !--------------------------------------------------------------------
-      tn_ice (:,:,:) = t_su (:,:,:)
-
-      CALL wrk_dealloc( jpi, jpj, zidto )
+
+      CALL wrk_dealloc( jpi, jpj, zswitch )
       CALL wrk_dealloc( jpi, jpj, zhemis )
-      CALL wrk_dealloc( jpl,   2, zht_i_ini,  za_i_ini,  zv_i_ini )
-      CALL wrk_dealloc(   2,      zhm_i_ini, zat_i_ini, zvt_i_ini, zhm_s_ini, zsm_i_ini )
+      CALL wrk_dealloc( jpl,   2, zh_i_ini,  za_i_ini,  zv_i_ini )
+      CALL wrk_dealloc(   2,      zht_i_ini, zat_i_ini, zvt_i_ini, zht_s_ini, zsm_i_ini, ztm_i_ini )
 
    END SUBROUTINE lim_istate
@@ -495,6 +481,6 @@
       !!  8.5  ! 07-11 (M. Vancoppenolle) rewritten initialization
       !!-----------------------------------------------------------------------------
-      NAMELIST/namiceini/ ttest, hninn, hnins, hginn, hgins, aginn, agins, sinn, sins
-      !
+      NAMELIST/namiceini/ ln_limini, thres_sst, hts_ini_n, hts_ini_s, hti_ini_n, hti_ini_s,  &
+         &                                      ati_ini_n, ati_ini_s, smi_ini_n, smi_ini_s, tmi_ini_n, tmi_ini_s
       INTEGER :: ios                 ! Local integer output status for namelist read
       !!-----------------------------------------------------------------------------
@@ -516,13 +502,16 @@
          WRITE(numout,*) 'lim_istate_init : ice parameters inititialisation '
          WRITE(numout,*) '~~~~~~~~~~~~~~~'
-         WRITE(numout,*) '   threshold water temp. for initial sea-ice    ttest      = ', ttest
-         WRITE(numout,*) '   initial snow thickness in the north          hninn      = ', hninn
-         WRITE(numout,*) '   initial snow thickness in the south          hnins      = ', hnins 
-         WRITE(numout,*) '   initial ice thickness  in the north          hginn      = ', hginn
-         WRITE(numout,*) '   initial ice thickness  in the south          hgins      = ', hgins
-         WRITE(numout,*) '   initial ice concentr.  in the north          aginn      = ', aginn
-         WRITE(numout,*) '   initial ice concentr.  in the north          agins      = ', agins
-         WRITE(numout,*) '   initial  ice salinity  in the north          sinn       = ', sinn
-         WRITE(numout,*) '   initial  ice salinity  in the south          sins       = ', sins
+         WRITE(numout,*) '   initialization with ice (T) or not (F)       ln_limini   = ', ln_limini
+         WRITE(numout,*) '   threshold water temp. for initial sea-ice    thres_sst  = ', thres_sst
+         WRITE(numout,*) '   initial snow thickness in the north          hts_ini_n  = ', hts_ini_n
+         WRITE(numout,*) '   initial snow thickness in the south          hts_ini_s  = ', hts_ini_s 
+         WRITE(numout,*) '   initial ice thickness  in the north          hti_ini_n  = ', hti_ini_n
+         WRITE(numout,*) '   initial ice thickness  in the south          hti_ini_s  = ', hti_ini_s
+         WRITE(numout,*) '   initial ice concentr.  in the north          ati_ini_n  = ', ati_ini_n
+         WRITE(numout,*) '   initial ice concentr.  in the north          ati_ini_s  = ', ati_ini_s
+         WRITE(numout,*) '   initial  ice salinity  in the north          smi_ini_n  = ', smi_ini_n
+         WRITE(numout,*) '   initial  ice salinity  in the south          smi_ini_s  = ', smi_ini_s
+         WRITE(numout,*) '   initial  ice/snw temp  in the north          tmi_ini_n  = ', tmi_ini_n
+         WRITE(numout,*) '   initial  ice/snw temp  in the south          tmi_ini_s  = ', tmi_ini_s
       ENDIF
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limitd_me.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limitd_me.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limitd_me.F90	(revision 5075)
@@ -5,5 +5,5 @@
    !!======================================================================
    !! History :  LIM  ! 2006-02  (M. Vancoppenolle) Original code 
-   !!            3.2  ! 2009-07  (M. Vancoppenolle, Y. Aksenov, G. Madec) bug correction in smsw & sfx_mec
+   !!            3.2  ! 2009-07  (M. Vancoppenolle, Y. Aksenov, G. Madec) bug correction in smsw & sfx_dyn
    !!            4.0  ! 2011-02  (G. Madec) dynamical allocation
    !!----------------------------------------------------------------------
@@ -22,5 +22,4 @@
    USE limthd_lac       ! LIM
    USE limvar           ! LIM
-   USE limcons          ! LIM
    USE in_out_manager   ! I/O manager
    USE lbclnk           ! lateral boundary condition - MPP exchanges
@@ -30,7 +29,8 @@
   ! Check budget (Rousset)
    USE iom              ! I/O manager
-   USE lib_fortran     ! glob_sum
+   USE lib_fortran      ! glob_sum
    USE limdiahsb
-   USE timing          ! Timing
+   USE timing           ! Timing
+   USE limcons          ! conservation tests
 
    IMPLICIT NONE
@@ -42,8 +42,4 @@
    PUBLIC   lim_itd_me_zapsmall
    PUBLIC   lim_itd_me_alloc        ! called by iceini.F90
-
-   REAL(wp) ::   epsi20 = 1.e-20_wp   ! constant values
-   REAL(wp) ::   epsi10 = 1.e-10_wp   ! constant values
-   REAL(wp) ::   epsi06 = 1.e-06_wp   ! constant values
 
    !-----------------------------------------------------------------------
@@ -143,16 +139,10 @@
       REAL(wp), POINTER, DIMENSION(:,:) ::   esnow_mlt       ! energy needed to melt snow in ocean (J m-2)
       REAL(wp), POINTER, DIMENSION(:,:) ::   vt_i_init, vt_i_final  !  ice volume summed over categories
-      REAL(wp) :: zchk_v_i, zchk_smv, zchk_fs, zchk_fw, zchk_v_i_b, zchk_smv_b, zchk_fs_b, zchk_fw_b ! Check conservation (C Rousset)
-      REAL(wp) :: zchk_vmin, zchk_amin, zchk_amax ! Check errors (C Rousset)
-      ! mass and salt flux (clem)
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zviold, zvsold, zsmvold   ! old ice volume...
+      !
+      REAL(wp) :: zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b 
       !!-----------------------------------------------------------------------------
       IF( nn_timing == 1 )  CALL timing_start('limitd_me')
 
       CALL wrk_alloc( jpi, jpj, closing_net, divu_adv, opning, closing_gross, msnow_mlt, esnow_mlt, vt_i_init, vt_i_final )
-
-      CALL wrk_alloc( jpi, jpj, jpl, zviold, zvsold, zsmvold )   ! clem
-
-      IF( numit == nstart  )   CALL lim_itd_me_init   ! Initialization (first time-step only)
 
       IF(ln_ctl) THEN
@@ -162,19 +152,7 @@
 
       IF( ln_limdyn ) THEN          !   Start ridging and rafting   !
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_v_i_b = glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_smv_b = glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_fw_b  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) )
-         zchk_fs_b  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) )
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
-
-      ! mass and salt flux init (clem)
-      zviold(:,:,:) = v_i(:,:,:)
-      zvsold(:,:,:) = v_s(:,:,:)
-      zsmvold(:,:,:) = smv_i(:,:,:)
+
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limitd_me', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
 
       !-----------------------------------------------------------------------------!
@@ -362,6 +340,6 @@
             ! 5) Heat, salt and freshwater fluxes
             !-----------------------------------------------------------------------------!
-            fmmec(ji,jj) = fmmec(ji,jj) + msnow_mlt(ji,jj) * r1_rdtice     ! fresh water source for ocean
-            fhmec(ji,jj) = fhmec(ji,jj) + esnow_mlt(ji,jj) * r1_rdtice     ! heat sink for ocean
+            wfx_snw(ji,jj) = wfx_snw(ji,jj) + msnow_mlt(ji,jj) * r1_rdtice     ! fresh water source for ocean
+            hfx_dyn(ji,jj) = hfx_dyn(ji,jj) + esnow_mlt(ji,jj) * unit_fac / area(ji,jj) * r1_rdtice  ! heat sink for ocean (<0, W.m-2)
 
          END DO
@@ -399,17 +377,4 @@
       CALL lim_itd_me_zapsmall
 
-      !--------------------------------
-      ! Update mass/salt fluxes (clem)
-      !--------------------------------
-      DO jl = 1, jpl
-         DO jj = 1, jpj 
-            DO ji = 1, jpi
-               diag_dyn_gr(ji,jj) = diag_dyn_gr(ji,jj) + ( v_i(ji,jj,jl) - zviold(ji,jj,jl) ) * r1_rdtice
-               rdm_ice(ji,jj) = rdm_ice(ji,jj) + ( v_i(ji,jj,jl) - zviold(ji,jj,jl) ) * rhoic 
-               rdm_snw(ji,jj) = rdm_snw(ji,jj) + ( v_s(ji,jj,jl) - zvsold(ji,jj,jl) ) * rhosn 
-               sfx_mec(ji,jj) = sfx_mec(ji,jj) - ( smv_i(ji,jj,jl) - zsmvold(ji,jj,jl) ) * rhoic * r1_rdtice 
-            END DO
-         END DO
-      END DO
 
       IF(ln_ctl) THEN     ! Control print
@@ -445,33 +410,10 @@
       ENDIF
 
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_fs  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) ) - zchk_fs_b
-         zchk_fw  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) ) - zchk_fw_b
- 
-         zchk_v_i = ( glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_v_i_b - ( zchk_fw / rhoic ) ) * r1_rdtice
-         zchk_smv = ( glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_smv_b ) * r1_rdtice + ( zchk_fs / rhoic )
-
-         zchk_vmin = glob_min(v_i)
-         zchk_amax = glob_max(SUM(a_i,dim=3))
-         zchk_amin = glob_min(a_i)
-       
-         IF(lwp) THEN
-            IF ( ABS( zchk_v_i   ) >  1.e-5 ) WRITE(numout,*) 'violation volume [m3/day]     (limitd_me) = ',(zchk_v_i * rday)
-            IF ( ABS( zchk_smv   ) >  1.e-4 ) WRITE(numout,*) 'violation saline [psu*m3/day] (limitd_me) = ',(zchk_smv * rday)
-            IF ( zchk_vmin <  0.            ) WRITE(numout,*) 'violation v_i<0  [mm]         (limitd_me) = ',(zchk_vmin * 1.e-3)
-            IF ( zchk_amax >  kamax+epsi10  ) WRITE(numout,*) 'violation a_i>amax            (limitd_me) = ',zchk_amax
-            IF ( zchk_amin <  0.            ) WRITE(numout,*) 'violation a_i<0               (limitd_me) = ',zchk_amin
-         ENDIF
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(1, 'limitd_me', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
 
       ENDIF  ! ln_limdyn=.true.
       !
       CALL wrk_dealloc( jpi, jpj, closing_net, divu_adv, opning, closing_gross, msnow_mlt, esnow_mlt, vt_i_init, vt_i_final )
-      !
-      CALL wrk_dealloc( jpi, jpj, jpl, zviold, zvsold, zsmvold )   ! clem
       !
       IF( nn_timing == 1 )  CALL timing_stop('limitd_me')
@@ -670,5 +612,4 @@
       !!---------------------------------------------------------------------!
       INTEGER ::   ji,jj, jl    ! dummy loop indices
-      INTEGER ::   krdg_index   ! 
       REAL(wp) ::   Gstari, astari, hi, hrmean, zdummy   ! local scalar
       REAL(wp), POINTER, DIMENSION(:,:)   ::   zworka    ! temporary array used here
@@ -746,8 +687,6 @@
       !-----------------------------------------------------------------
 
-      krdg_index = 1
-
-      IF( krdg_index == 0 ) THEN       !--- Linear formulation (Thorndike et al., 1975)
-         DO jl = 0, ice_cat_bounds(1,2)       ! only undeformed ice participates
+      IF( partfun_swi == 0 ) THEN       !--- Linear formulation (Thorndike et al., 1975)
+         DO jl = 0, jpl    
             DO jj = 1, jpj 
                DO ji = 1, jpi
@@ -772,11 +711,11 @@
             Gsum(:,:,jl) = EXP( -Gsum(:,:,jl) * astari ) * zdummy
          END DO !jl
-         DO jl = 0, ice_cat_bounds(1,2)
+         DO jl = 0, jpl
              athorn(:,:,jl) = Gsum(:,:,jl-1) - Gsum(:,:,jl)
          END DO
          !
-      ENDIF ! krdg_index
-
-      IF( raftswi == 1 ) THEN      ! Ridging and rafting ice participation functions
+      ENDIF ! partfun_swi
+
+      IF( raft_swi == 1 ) THEN      ! Ridging and rafting ice participation functions
          !
          DO jl = 1, jpl
@@ -794,5 +733,5 @@
          END DO ! jl
 
-      ELSE  ! raftswi = 0
+      ELSE  ! raft_swi = 0
          !
          DO jl = 1, jpl
@@ -802,5 +741,5 @@
       ENDIF
 
-      IF ( raftswi == 1 ) THEN
+      IF ( raft_swi == 1 ) THEN
 
          IF( MAXVAL(aridge + araft - athorn(:,:,1:jpl)) .GT. epsi10 ) THEN
@@ -908,6 +847,6 @@
       INTEGER ::   ij                ! horizontal index, combines i and j loops
       INTEGER ::   icells            ! number of cells with aicen > puny
-      REAL(wp) ::   zindb, zsrdg2   ! local scalar
       REAL(wp) ::   hL, hR, farea, zdummy, zdummy0, ztmelts    ! left and right limits of integration
+      REAL(wp) ::   zsstK            ! SST in Kelvin
 
       INTEGER , POINTER, DIMENSION(:) ::   indxi, indxj   ! compressed indices
@@ -917,5 +856,5 @@
 
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   aicen_init, vicen_init   ! ice  area    & volume before ridging
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   vsnon_init, esnon_init   ! snow volume  & energy before ridging
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   vsnwn_init, esnwn_init   ! snow volume  & energy before ridging
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   smv_i_init, oa_i_init    ! ice salinity & age    before ridging
 
@@ -952,7 +891,7 @@
       CALL wrk_alloc( jpi, jpj,             vrdg1, vrdg2, vsw  , srdg1, srdg2, smsw )
       CALL wrk_alloc( jpi, jpj,             afrft, arft1, arft2, virft, vsrft, esrft, smrft, oirft1, oirft2 )
-      CALL wrk_alloc( jpi, jpj, jpl,        aicen_init, vicen_init, vsnon_init, esnon_init, smv_i_init, oa_i_init )
-      CALL wrk_alloc( jpi, jpj, jkmax,      eirft, erdg1, erdg2, ersw )
-      CALL wrk_alloc( jpi, jpj, jkmax, jpl, eicen_init )
+      CALL wrk_alloc( jpi, jpj, jpl,        aicen_init, vicen_init, vsnwn_init, esnwn_init, smv_i_init, oa_i_init )
+      CALL wrk_alloc( jpi, jpj, nlay_i+1,      eirft, erdg1, erdg2, ersw )
+      CALL wrk_alloc( jpi, jpj, nlay_i+1, jpl, eicen_init )
 
       ! Conservation check
@@ -1008,5 +947,5 @@
          aicen_init(:,:,jl) = a_i(:,:,jl)
          vicen_init(:,:,jl) = v_i(:,:,jl)
-         vsnon_init(:,:,jl) = v_s(:,:,jl)
+         vsnwn_init(:,:,jl) = v_s(:,:,jl)
          !
          smv_i_init(:,:,jl) = smv_i(:,:,jl)
@@ -1014,5 +953,5 @@
       END DO !jl
 
-      esnon_init(:,:,:) = e_s(:,:,1,:)
+      esnwn_init(:,:,:) = e_s(:,:,1,:)
 
       DO jl = 1, jpl  
@@ -1091,17 +1030,17 @@
             !     / rafting category n1.
             !--------------------------------------------------------------------------
-            vrdg1(ji,jj) = vicen_init(ji,jj,jl1) * afrac(ji,jj) / ( 1._wp + ridge_por )
+            vrdg1(ji,jj) = vicen_init(ji,jj,jl1) * afrac(ji,jj)
             vrdg2(ji,jj) = vrdg1(ji,jj) * ( 1. + ridge_por )
             vsw  (ji,jj) = vrdg1(ji,jj) * ridge_por
 
-            vsrdg(ji,jj) = vsnon_init(ji,jj,jl1) * afrac(ji,jj)
-            esrdg(ji,jj) = esnon_init(ji,jj,jl1) * afrac(ji,jj)
-            srdg1(ji,jj) = smv_i_init(ji,jj,jl1) * afrac(ji,jj) / ( 1._wp + ridge_por )
-            srdg2(ji,jj) = smv_i_init(ji,jj,jl1) * afrac(ji,jj)
+            vsrdg(ji,jj) = vsnwn_init(ji,jj,jl1) * afrac(ji,jj)
+            esrdg(ji,jj) = esnwn_init(ji,jj,jl1) * afrac(ji,jj)
+            srdg1(ji,jj) = smv_i_init(ji,jj,jl1) * afrac(ji,jj)
+            srdg2(ji,jj) = smv_i_init(ji,jj,jl1) * afrac(ji,jj) !! MV HC 2014 this line seems useless
 
             ! rafting volumes, heat contents ...
             virft(ji,jj) = vicen_init(ji,jj,jl1) * afrft(ji,jj)
-            vsrft(ji,jj) = vsnon_init(ji,jj,jl1) * afrft(ji,jj)
-            esrft(ji,jj) = esnon_init(ji,jj,jl1) * afrft(ji,jj)
+            vsrft(ji,jj) = vsnwn_init(ji,jj,jl1) * afrft(ji,jj)
+            esrft(ji,jj) = esnwn_init(ji,jj,jl1) * afrft(ji,jj)
             smrft(ji,jj) = smv_i_init(ji,jj,jl1) * afrft(ji,jj) 
 
@@ -1120,14 +1059,11 @@
             ! Salinity
             !-------------
-            smsw(ji,jj)  = sss_m(ji,jj) * vsw(ji,jj) * rhoic / rau0       ! salt content of seawater frozen in voids
-
-            zsrdg2       = srdg1(ji,jj) + smsw(ji,jj)                     ! salt content of new ridge
-
-            srdg2(ji,jj) = MIN( s_i_max * vrdg2(ji,jj) , zsrdg2 )         ! impose a maximum salinity
+            smsw(ji,jj)  = vsw(ji,jj) * sss_m(ji,jj)                      ! salt content of seawater frozen in voids !! MV HC2014
+            srdg2(ji,jj) = srdg1(ji,jj) + smsw(ji,jj)                     ! salt content of new ridge
+
+            !srdg2(ji,jj) = MIN( s_i_max * vrdg2(ji,jj) , zsrdg2 )         ! impose a maximum salinity
             
-            !                                                             ! excess of salt is flushed into the ocean
-            !sfx_mec(ji,jj) = sfx_mec(ji,jj) + ( zsrdg2 - srdg2(ji,jj) ) * rhoic * r1_rdtice
-
-            !rdm_ice(ji,jj) = rdm_ice(ji,jj) + vsw(ji,jj) * rhoic    ! gurvan: increase in ice volume du to seawater frozen in voids             
+            sfx_dyn(ji,jj) = sfx_dyn(ji,jj) - smsw(ji,jj) * rhoic * r1_rdtice
+            wfx_dyn(ji,jj) = wfx_dyn(ji,jj) - vsw (ji,jj) * rhoic * r1_rdtice   ! gurvan: increase in ice volume du to seawater frozen in voids             
 
             !------------------------------------            
@@ -1158,6 +1094,7 @@
                &                                + rhosn*vsrft(ji,jj)*(1.0-fsnowrft)
 
-            esnow_mlt(ji,jj) = esnow_mlt(ji,jj) + esrdg(ji,jj)*(1.0-fsnowrdg)         &   !rafting included
-               &                                + esrft(ji,jj)*(1.0-fsnowrft)          
+            ! in 1e-9 Joules (same as e_s)
+            esnow_mlt(ji,jj) = esnow_mlt(ji,jj) - esrdg(ji,jj)*(1.0-fsnowrdg)         &   !rafting included
+               &                                - esrft(ji,jj)*(1.0-fsnowrft)          
 
             !-----------------------------------------------------------------
@@ -1184,29 +1121,27 @@
                jj = indxj(ij)
                ! heat content of ridged ice
-               erdg1(ji,jj,jk)      = eicen_init(ji,jj,jk,jl1) * afrac(ji,jj) / ( 1._wp + ridge_por ) 
+               erdg1(ji,jj,jk)      = eicen_init(ji,jj,jk,jl1) * afrac(ji,jj) 
                eirft(ji,jj,jk)      = eicen_init(ji,jj,jk,jl1) * afrft(ji,jj)
                e_i  (ji,jj,jk,jl1)  = e_i(ji,jj,jk,jl1) - erdg1(ji,jj,jk) - eirft(ji,jj,jk)
-               ! sea water heat content
-               ztmelts          = - tmut * sss_m(ji,jj) + rtt
-               ! heat content per unit volume
-               zdummy0          = - rcp * ( sst_m(ji,jj) + rt0 - rtt ) * vsw(ji,jj)
-
-               ! corrected sea water salinity
-               zindb  = MAX( 0._wp , SIGN( 1._wp , vsw(ji,jj) - epsi20 ) )
-               zdummy = zindb * ( srdg1(ji,jj) - srdg2(ji,jj) ) / MAX( ridge_por * vsw(ji,jj), epsi20 )
-
-               ztmelts          = - tmut * zdummy + rtt
-               ersw(ji,jj,jk)   = - rcp * ( ztmelts - rtt ) * vsw(ji,jj)
-
-               ! heat flux
-               fheat_mec(ji,jj) = fheat_mec(ji,jj) + ( ersw(ji,jj,jk) - zdummy0 ) * r1_rdtice
+               
+               
+               ! enthalpy of the trapped seawater (J/m2, >0)
+               ! clem: if sst>0, then ersw <0 (is that possible?)
+               zsstK  = sst_m(ji,jj) + rt0
+               ersw(ji,jj,jk)   = - rhoic * vsw(ji,jj) * rcp * ( zsstK - rt0 ) / REAL( nlay_i )
+
+               ! heat flux to the ocean
+               hfx_dyn(ji,jj) = hfx_dyn(ji,jj) + ersw(ji,jj,jk) * r1_rdtice  ! > 0 [W.m-2] ocean->ice flux 
 
                ! Correct dimensions to avoid big values
-               ersw(ji,jj,jk)   = ersw(ji,jj,jk) * 1.e-09
-
-               ! Mutliply by ice volume, and divide by number of layers to get heat content in 10^9 J
-               ersw (ji,jj,jk)  = ersw(ji,jj,jk) * area(ji,jj) * vsw(ji,jj) / REAL( nlay_i )
+               ersw(ji,jj,jk)   = ersw(ji,jj,jk) / unit_fac
+
+               ! Mutliply by ice volume, and divide by number of layers to get heat content in 1.e9 J
+               ! it is added to sea ice because the sign convention is the opposite of the sign convention for the ocean 
+               !! MV HC 2014
+               ersw (ji,jj,jk)  = ersw(ji,jj,jk) * area(ji,jj)
 
                erdg2(ji,jj,jk)  = erdg1(ji,jj,jk) + ersw(ji,jj,jk)
+
             END DO ! ij
          END DO !jk
@@ -1253,5 +1188,5 @@
          !-------------------------------------------------------------------------------
          !        jl1 looping 1-jpl
-         DO jl2  = ice_cat_bounds(1,1), ice_cat_bounds(1,2) 
+         DO jl2  = 1, jpl 
             ! over categories to which ridged ice is transferred
 !CDIR NODEP
@@ -1298,5 +1233,5 @@
          END DO                 ! jl2 (new ridges)            
 
-         DO jl2 = ice_cat_bounds(1,1), ice_cat_bounds(1,2) 
+         DO jl2 = 1, jpl 
 
 !CDIR NODEP
@@ -1361,7 +1296,7 @@
       CALL wrk_dealloc( jpi, jpj,             vrdg1, vrdg2, vsw  , srdg1, srdg2, smsw )
       CALL wrk_dealloc( jpi, jpj,             afrft, arft1, arft2, virft, vsrft, esrft, smrft, oirft1, oirft2 )
-      CALL wrk_dealloc( jpi, jpj, jpl,        aicen_init, vicen_init, vsnon_init, esnon_init, smv_i_init, oa_i_init )
-      CALL wrk_dealloc( jpi, jpj, jkmax,      eirft, erdg1, erdg2, ersw )
-      CALL wrk_dealloc( jpi, jpj, jkmax, jpl, eicen_init )
+      CALL wrk_dealloc( jpi, jpj, jpl,        aicen_init, vicen_init, vsnwn_init, esnwn_init, smv_i_init, oa_i_init )
+      CALL wrk_dealloc( jpi, jpj, nlay_i+1,      eirft, erdg1, erdg2, ersw )
+      CALL wrk_dealloc( jpi, jpj, nlay_i+1, jpl, eicen_init )
       !
    END SUBROUTINE lim_itd_me_ridgeshift
@@ -1404,9 +1339,7 @@
       !!-------------------------------------------------------------------
       INTEGER :: ios                 ! Local integer output status for namelist read
-      NAMELIST/namiceitdme/ ridge_scheme_swi, Cs, Cf, fsnowrdg, fsnowrft,& 
-         Gstar, astar,                                &
-         Hstar, raftswi, hparmeter, Craft, ridge_por, &
-         sal_max_ridge,  partfun_swi, transfun_swi,   &
-         brinstren_swi
+      NAMELIST/namiceitdme/ ridge_scheme_swi, Cs, Cf, fsnowrdg, fsnowrft,              & 
+        &                   Gstar, astar, Hstar, raft_swi, hparmeter, Craft, ridge_por, &
+        &                   partfun_swi, brinstren_swi
       !!-------------------------------------------------------------------
       !
@@ -1432,11 +1365,9 @@
          WRITE(numout,*)'   Equivalent to G* for an exponential part function       astar           ', astar
          WRITE(numout,*)'   Quantity playing a role in max ridged ice thickness     Hstar           ', Hstar
-         WRITE(numout,*)'   Rafting of ice sheets or not                            raftswi         ', raftswi
+         WRITE(numout,*)'   Rafting of ice sheets or not                            raft_swi        ', raft_swi
          WRITE(numout,*)'   Parmeter thickness (threshold between ridge-raft)       hparmeter       ', hparmeter
          WRITE(numout,*)'   Rafting hyperbolic tangent coefficient                  Craft           ', Craft  
          WRITE(numout,*)'   Initial porosity of ridges                              ridge_por       ', ridge_por
-         WRITE(numout,*)'   Maximum salinity of ridging ice                         sal_max_ridge   ', sal_max_ridge
          WRITE(numout,*)'   Switch for part. function (0) linear (1) exponential    partfun_swi     ', partfun_swi
-         WRITE(numout,*)'   Switch for tran. function (0) linear (1) exponential    transfun_swi    ', transfun_swi
          WRITE(numout,*)'   Switch for including brine volume in ice strength comp. brinstren_swi   ', brinstren_swi
       ENDIF
@@ -1462,5 +1393,5 @@
 
       REAL(wp), POINTER, DIMENSION(:,:) ::   zmask   ! 2D workspace
-      REAL(wp)                          ::   zmask_glo
+      REAL(wp)                          ::   zmask_glo, zsal, zvi, zvs, zei, zes
 !!gm      REAL(wp) ::   xtmp      ! temporary variable
       !!-------------------------------------------------------------------
@@ -1468,9 +1399,10 @@
       CALL wrk_alloc( jpi, jpj, zmask )
 
+      ! to be sure that at_i is the sum of a_i(jl)
+      at_i(:,:) = SUM( a_i(:,:,:), dim=3 )
+
       DO jl = 1, jpl
-
          !-----------------------------------------------------------------
          ! Count categories to be zapped.
-         ! Abort model in case of negative area.
          !-----------------------------------------------------------------
          icells = 0
@@ -1478,8 +1410,7 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               IF(  ( a_i(ji,jj,jl) >= -epsi10 .AND. a_i(ji,jj,jl) <  0._wp   ) .OR.   &
-                  & ( a_i(ji,jj,jl) >  0._wp   .AND. a_i(ji,jj,jl) <= epsi10  ) .OR.   &
-                  & ( v_i(ji,jj,jl) == 0._wp   .AND. a_i(ji,jj,jl) >  0._wp   ) .OR.   &
-                  & ( v_i(ji,jj,jl) >  0._wp   .AND. v_i(ji,jj,jl) <= epsi10  ) )   zmask(ji,jj) = 1._wp
+               IF( a_i(ji,jj,jl) <= epsi10 .OR. v_i(ji,jj,jl) <= epsi10 .OR. at_i(ji,jj) <= epsi10 ) THEN
+                  zmask(ji,jj) = 1._wp
+               ENDIF
             END DO
          END DO
@@ -1494,8 +1425,9 @@
             DO jj = 1 , jpj
                DO ji = 1 , jpi
-!!gm                  xtmp = e_i(ji,jj,jk,jl) / area(ji,jj) * r1_rdtice
-!!gm                  xtmp = xtmp * unit_fac
-                  ! fheat_res(ji,jj) = fheat_res(ji,jj) - xtmp
+                  zei  = e_i(ji,jj,jk,jl)
                   e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * ( 1._wp - zmask(ji,jj) )
+                  t_i(ji,jj,jk,jl) = t_i(ji,jj,jk,jl) * ( 1._wp - zmask(ji,jj) ) + rtt * zmask(ji,jj)
+                  ! update exchanges with ocean
+                  hfx_res(ji,jj)   = hfx_res(ji,jj) + ( e_i(ji,jj,jk,jl) - zei ) * unit_fac / area(ji,jj) * r1_rdtice ! W.m-2 <0
                END DO
             END DO
@@ -1504,5 +1436,9 @@
          DO jj = 1 , jpj
             DO ji = 1 , jpi
-
+               
+               zsal = smv_i(ji,jj,jl)
+               zvi  = v_i(ji,jj,jl)
+               zvs  = v_s(ji,jj,jl)
+               zes  = e_s(ji,jj,1,jl)
                !-----------------------------------------------------------------
                ! Zap snow energy and use ocean heat to melt snow
@@ -1514,9 +1450,4 @@
                ! fluxes are positive to the ocean
                ! here the flux has to be negative for the ocean
-!!gm               xtmp = ( rhosn*cpic*( rtt-t_s(ji,jj,1,jl) ) + rhosn*lfus ) * r1_rdtice
-               !           fheat_res(ji,jj) = fheat_res(ji,jj) - xtmp
-
-!!gm               xtmp = ( rhosn*cpic*( rtt-t_s(ji,jj,1,jl) ) + rhosn*lfus ) * r1_rdtice !RB   ???????
-
                t_s(ji,jj,1,jl) = rtt * zmask(ji,jj) + t_s(ji,jj,1,jl) * ( 1._wp - zmask(ji,jj) )
 
@@ -1524,13 +1455,5 @@
                ! zap ice and snow volume, add water and salt to ocean
                !-----------------------------------------------------------------
-
-               !           xtmp = (rhoi*vicen(i,j,n) + rhos*vsnon(i,j,n)) / dt
-               !           sfx_res(ji,jj)  = sfx_res(ji,jj) + ( sss_m(ji,jj)                  )   &
-               !                                            * rhosn * v_s(ji,jj,jl) * r1_rdtice
-               !           sfx_res(ji,jj)  = sfx_res(ji,jj) + ( sss_m(ji,jj) - sm_i(ji,jj,jl) )   & 
-               !                                            * rhoic * v_i(ji,jj,jl) * r1_rdtice
-               !           sfx (i,j)      = sfx (i,j)      + xtmp
-
-               ato_i(ji,jj)    = a_i  (ji,jj,jl) *       zmask(ji,jj)   + ato_i(ji,jj)
+               ato_i(ji,jj)    = a_i  (ji,jj,jl) *           zmask(ji,jj)   + ato_i(ji,jj)
                a_i  (ji,jj,jl) = a_i  (ji,jj,jl) * ( 1._wp - zmask(ji,jj) )
                v_i  (ji,jj,jl) = v_i  (ji,jj,jl) * ( 1._wp - zmask(ji,jj) )
@@ -1539,9 +1462,21 @@
                oa_i (ji,jj,jl) = oa_i (ji,jj,jl) * ( 1._wp - zmask(ji,jj) )
                smv_i(ji,jj,jl) = smv_i(ji,jj,jl) * ( 1._wp - zmask(ji,jj) )
-               !
+               e_s(ji,jj,1,jl) = e_s(ji,jj,1,jl) * ( 1._wp - zmask(ji,jj) )
+               ! additional condition
+               IF( v_s(ji,jj,jl) <= epsi10 ) THEN
+                  v_s(ji,jj,jl)   = 0._wp
+                  e_s(ji,jj,1,jl) = 0._wp
+               ENDIF
+               ! update exchanges with ocean
+               sfx_res(ji,jj)  = sfx_res(ji,jj) - ( smv_i(ji,jj,jl) - zsal ) * rhoic * r1_rdtice
+               wfx_res(ji,jj)  = wfx_res(ji,jj) - ( v_i(ji,jj,jl)   - zvi  ) * rhoic * r1_rdtice
+               wfx_snw(ji,jj)  = wfx_snw(ji,jj) - ( v_s(ji,jj,jl)   - zvs  ) * rhosn * r1_rdtice
+               hfx_res(ji,jj)  = hfx_res(ji,jj) + ( e_s(ji,jj,1,jl) - zes ) * unit_fac / area(ji,jj) * r1_rdtice ! W.m-2 <0
             END DO
          END DO
-         !
-      END DO                 ! jl 
+      END DO ! jl 
+
+      ! to be sure that at_i is the sum of a_i(jl)
+      at_i(:,:) = SUM( a_i(:,:,:), dim=3 )
       !
       CALL wrk_dealloc( jpi, jpj, zmask )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limitd_th.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limitd_th.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limitd_th.F90	(revision 5075)
@@ -6,5 +6,5 @@
    !! History :   -   !          (W. H. Lipscomb and E.C. Hunke) CICE (c) original code
    !!            3.0  ! 2005-12  (M. Vancoppenolle) adaptation to LIM-3
-   !!             -   ! 2006-06  (M. Vancoppenolle) adaptation to include salt, age and types
+   !!             -   ! 2006-06  (M. Vancoppenolle) adaptation to include salt, age
    !!             -   ! 2007-04  (M. Vancoppenolle) Mass conservation checked
    !!----------------------------------------------------------------------
@@ -35,4 +35,5 @@
    USE lib_fortran      ! to use key_nosignedzero
    USE timing          ! Timing
+   USE limcons        ! conservation tests
 
    IMPLICIT NONE
@@ -44,7 +45,4 @@
    PUBLIC   lim_itd_fitline
    PUBLIC   lim_itd_shiftice
-
-   REAL(wp) ::   epsi10 = 1.e-10_wp   !
-   REAL(wp) ::   epsi06 = 1.e-6_wp   !
 
    !!----------------------------------------------------------------------
@@ -65,20 +63,12 @@
       INTEGER, INTENT(in) ::   kt   ! time step index
       !
-      INTEGER ::   jl, ja, jm, jbnd1, jbnd2   ! ice types    dummy loop index         
-      REAL(wp) :: zchk_v_i, zchk_smv, zchk_fs, zchk_fw, zchk_v_i_b, zchk_smv_b, zchk_fs_b, zchk_fw_b ! Check conservation (C Rousset)
-      REAL(wp) :: zchk_vmin, zchk_amin, zchk_amax ! Check errors (C Rousset)
+      INTEGER ::   ji, jj, jk, jl   ! dummy loop index         
+      !
+      REAL(wp) :: zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b 
       !!------------------------------------------------------------------
       IF( nn_timing == 1 )  CALL timing_start('limitd_th')
 
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_v_i_b = glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_smv_b = glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_fw_b  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) )
-         zchk_fs_b  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) )
-       ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limitd_th', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
 
       IF( kt == nit000 .AND. lwp ) THEN
@@ -93,9 +83,5 @@
       ! Given thermodynamic growth rates, transport ice between
       ! thickness categories.
-      DO jm = 1, jpm
-         jbnd1 = ice_cat_bounds(jm,1)
-         jbnd2 = ice_cat_bounds(jm,2)
-         IF( ice_ncat_types(jm) > 1 )   CALL lim_itd_th_rem( jbnd1, jbnd2, jm, kt )
-      END DO
+      IF( jpl > 1 )   CALL lim_itd_th_rem( 1, jpl, kt )
       !
       CALL lim_var_glo2eqv    ! only for info
@@ -105,9 +91,8 @@
       !  3) Add frazil ice growing in leads.
       !------------------------------------------------------------------------------|
-
       CALL lim_thd_lac
       CALL lim_var_glo2eqv    ! only for info
-
-     IF(ln_ctl) THEN   ! Control print
+     
+      IF(ln_ctl) THEN   ! Control print
          CALL prt_ctl_info(' ')
          CALL prt_ctl_info(' - Cell values : ')
@@ -131,37 +116,16 @@
             CALL prt_ctl(tab2d_1=sm_i  (:,:,jl)   , clinfo1= ' lim_itd_th  : sm_i     : ')
             CALL prt_ctl(tab2d_1=smv_i (:,:,jl)   , clinfo1= ' lim_itd_th  : smv_i    : ')
-            DO ja = 1, nlay_i
+            DO jk = 1, nlay_i
                CALL prt_ctl_info(' ')
-               CALL prt_ctl_info(' - Layer : ', ivar1=ja)
+               CALL prt_ctl_info(' - Layer : ', ivar1=jk)
                CALL prt_ctl_info('   ~~~~~~~')
-               CALL prt_ctl(tab2d_1=t_i(:,:,ja,jl) , clinfo1= ' lim_itd_th  : t_i      : ')
-               CALL prt_ctl(tab2d_1=e_i(:,:,ja,jl) , clinfo1= ' lim_itd_th  : e_i      : ')
+               CALL prt_ctl(tab2d_1=t_i(:,:,jk,jl) , clinfo1= ' lim_itd_th  : t_i      : ')
+               CALL prt_ctl(tab2d_1=e_i(:,:,jk,jl) , clinfo1= ' lim_itd_th  : e_i      : ')
             END DO
          END DO
       ENDIF
       !
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF( ln_limdiahsb ) THEN
-         zchk_fs  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) ) - zchk_fs_b
-         zchk_fw  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) ) - zchk_fw_b
- 
-         zchk_v_i = ( glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_v_i_b - ( zchk_fw / rhoic ) ) * r1_rdtice
-         zchk_smv = ( glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_smv_b ) * r1_rdtice + ( zchk_fs / rhoic )
-
-         zchk_vmin = glob_min(v_i)
-         zchk_amax = glob_max(SUM(a_i,dim=3))
-         zchk_amin = glob_min(a_i)
-
-         IF(lwp) THEN
-            IF ( ABS( zchk_v_i   ) >  1.e-5 ) WRITE(numout,*) 'violation volume [m3/day]     (limitd_th) = ',(zchk_v_i * rday)
-            IF ( ABS( zchk_smv   ) >  1.e-4 ) WRITE(numout,*) 'violation saline [psu*m3/day] (limitd_th) = ',(zchk_smv * rday)
-            IF ( zchk_vmin <  0.            ) WRITE(numout,*) 'violation v_i<0  [mm]         (limitd_th) = ',(zchk_vmin * 1.e-3)
-            IF ( zchk_amax >  amax+epsi10   ) WRITE(numout,*) 'violation a_i>amax            (limitd_th) = ',zchk_amax
-            IF ( zchk_amin <  0.            ) WRITE(numout,*) 'violation a_i<0               (limitd_th) = ',zchk_amin
-         ENDIF
-       ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(1, 'limitd_th', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
       !
      IF( nn_timing == 1 )  CALL timing_stop('limitd_th')
@@ -169,5 +133,5 @@
    !
 
-   SUBROUTINE lim_itd_th_rem( klbnd, kubnd, ntyp, kt )
+   SUBROUTINE lim_itd_th_rem( klbnd, kubnd, kt )
       !!------------------------------------------------------------------
       !!                ***  ROUTINE lim_itd_th_rem ***
@@ -182,5 +146,4 @@
       INTEGER , INTENT (in) ::   klbnd   ! Start thickness category index point
       INTEGER , INTENT (in) ::   kubnd   ! End point on which the  the computation is applied
-      INTEGER , INTENT (in) ::   ntyp    ! Number of the type used
       INTEGER , INTENT (in) ::   kt      ! Ocean time step 
       !
@@ -190,5 +153,5 @@
       REAL(wp) ::   zx1, zwk1, zdh0, zetamin, zdamax   ! local scalars
       REAL(wp) ::   zx2, zwk2, zda0, zetamax           !   -      -
-      REAL(wp) ::   zx3,             zareamin, zindb   !   -      -
+      REAL(wp) ::   zx3,             zareamin          !   -      -
       CHARACTER (len = 15) :: fieldid
 
@@ -200,5 +163,5 @@
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   hL          ! left boundary for the ITD for each thickness
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   hR          ! left boundary for the ITD for each thickness
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zht_i_o     ! old ice thickness
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zht_i_b     ! old ice thickness
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   dummy_es
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   zdaice, zdvice          ! local increment of ice area and volume
@@ -218,5 +181,5 @@
       CALL wrk_alloc( jpi,jpj, zremap_flag )    ! integer
       CALL wrk_alloc( jpi,jpj,jpl-1, zdonor )   ! integer
-      CALL wrk_alloc( jpi,jpj,jpl, zdhice, g0, g1, hL, hR, zht_i_o, dummy_es )
+      CALL wrk_alloc( jpi,jpj,jpl, zdhice, g0, g1, hL, hR, zht_i_b, dummy_es )
       CALL wrk_alloc( jpi,jpj,jpl-1, zdaice, zdvice )   
       CALL wrk_alloc( jpi,jpj,jpl+1, zhbnew, kkstart = 0 )   
@@ -247,5 +210,4 @@
          WRITE(numout,*) ' klbnd :       ', klbnd
          WRITE(numout,*) ' kubnd :       ', kubnd
-         WRITE(numout,*) ' ntyp  :       ', ntyp 
       ENDIF
 
@@ -254,9 +216,9 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               zindb             = 1.0 - MAX( 0.0, SIGN( 1.0, - a_i(ji,jj,jl) + epsi10 ) )     !0 if no ice and 1 if yes
-               ht_i(ji,jj,jl)    = v_i(ji,jj,jl) / MAX( a_i(ji,jj,jl), epsi10 ) * zindb
-               zindb             = 1.0 - MAX( 0.0, SIGN( 1.0, - old_a_i(ji,jj,jl) + epsi10) ) !0 if no ice and 1 if yes
-               zht_i_o(ji,jj,jl) = old_v_i(ji,jj,jl) / MAX( old_a_i(ji,jj,jl), epsi10 ) * zindb
-               IF( a_i(ji,jj,jl) > epsi06 )   zdhice(ji,jj,jl) = ht_i(ji,jj,jl) - zht_i_o(ji,jj,jl) 
+               rswitch             = 1.0 - MAX( 0.0, SIGN( 1.0, - a_i(ji,jj,jl) + epsi10 ) )     !0 if no ice and 1 if yes
+               ht_i(ji,jj,jl)    = v_i(ji,jj,jl) / MAX( a_i(ji,jj,jl), epsi10 ) * rswitch
+               rswitch             = 1.0 - MAX( 0.0, SIGN( 1.0, - a_i_b(ji,jj,jl) + epsi10) ) !0 if no ice and 1 if yes
+               zht_i_b(ji,jj,jl) = v_i_b(ji,jj,jl) / MAX( a_i_b(ji,jj,jl), epsi10 ) * rswitch
+               IF( a_i(ji,jj,jl) > epsi10 )   zdhice(ji,jj,jl) = ht_i(ji,jj,jl) - zht_i_b(ji,jj,jl) 
             END DO
          END DO
@@ -302,17 +264,13 @@
             ij = nind_j(ji)
             !
-            IF ( ( zht_i_o(ii,ij,jl) .GT. epsi10 ) .AND. & 
-               ( zht_i_o(ii,ij,jl+1) .GT. epsi10 ) ) THEN
+            zhbnew(ii,ij,jl) = hi_max(jl)
+            IF ( a_i_b(ii,ij,jl) > epsi10 .AND. a_i_b(ii,ij,jl+1) > epsi10 ) THEN
                !interpolate between adjacent category growth rates
-               zslope = ( zdhice(ii,ij,jl+1)     - zdhice(ii,ij,jl) ) / &
-                  ( zht_i_o   (ii,ij,jl+1) - zht_i_o   (ii,ij,jl) )
-               zhbnew(ii,ij,jl) = hi_max(jl) + zdhice(ii,ij,jl) + &
-                  zslope * ( hi_max(jl) - zht_i_o(ii,ij,jl) )
-            ELSEIF (zht_i_o(ii,ij,jl).gt.epsi10) THEN
+               zslope           = ( zdhice(ii,ij,jl+1) - zdhice(ii,ij,jl) ) / ( zht_i_b(ii,ij,jl+1) - zht_i_b(ii,ij,jl) )
+               zhbnew(ii,ij,jl) = hi_max(jl) + zdhice(ii,ij,jl) + zslope * ( hi_max(jl) - zht_i_b(ii,ij,jl) )
+            ELSEIF ( a_i_b(ii,ij,jl) > epsi10) THEN
                zhbnew(ii,ij,jl) = hi_max(jl) + zdhice(ii,ij,jl)
-            ELSEIF (zht_i_o(ii,ij,jl+1).gt.epsi10) THEN
+            ELSEIF ( a_i_b(ii,ij,jl+1) > epsi10) THEN
                zhbnew(ii,ij,jl) = hi_max(jl) + zdhice(ii,ij,jl+1)
-            ELSE
-               zhbnew(ii,ij,jl) = hi_max(jl)
             ENDIF
          END DO
@@ -320,30 +278,17 @@
          !- 4.2 Check that each zhbnew lies between adjacent values of ice thickness
          DO ji = 1, nbrem
-            ! jl, ji
             ii = nind_i(ji)
             ij = nind_j(ji)
-            ! jl, ji
-            IF ( ( a_i(ii,ij,jl) .GT.epsi10) .AND. & 
-               ( ht_i(ii,ij,jl).GE. zhbnew(ii,ij,jl) ) &
-               ) THEN
+            IF( a_i(ii,ij,jl) > epsi10 .AND. ht_i(ii,ij,jl) >= zhbnew(ii,ij,jl) ) THEN
                zremap_flag(ii,ij) = 0
-            ELSEIF ( ( a_i(ii,ij,jl+1) .GT. epsi10 ) .AND. &
-               ( ht_i(ii,ij,jl+1).LE. zhbnew(ii,ij,jl) ) &
-               ) THEN
+            ELSEIF( a_i(ii,ij,jl+1) > epsi10 .AND. ht_i(ii,ij,jl+1) <= zhbnew(ii,ij,jl) ) THEN
                zremap_flag(ii,ij) = 0
             ENDIF
 
             !- 4.3 Check that each zhbnew does not exceed maximal values hi_max  
-            ! jl, ji
-            IF (zhbnew(ii,ij,jl).gt.hi_max(jl+1)) THEN
-               zremap_flag(ii,ij) = 0
-            ENDIF
-            ! jl, ji
-            IF (zhbnew(ii,ij,jl).lt.hi_max(jl-1)) THEN
-               zremap_flag(ii,ij) = 0
-            ENDIF
-            ! jl, ji
-         END DO !ji
-         ! ji
+            IF( zhbnew(ii,ij,jl) > hi_max(jl+1) ) zremap_flag(ii,ij) = 0
+            IF( zhbnew(ii,ij,jl) < hi_max(jl-1) ) zremap_flag(ii,ij) = 0
+         END DO
+
       END DO !jl
 
@@ -354,11 +299,11 @@
       DO jj = 1, jpj
          DO ji = 1, jpi
-            IF ( zremap_flag(ji,jj) == 1 ) THEN
+            IF( zremap_flag(ji,jj) == 1 ) THEN
                nbrem         = nbrem + 1
                nind_i(nbrem) = ji
                nind_j(nbrem) = jj
             ENDIF
-         END DO !ji
-      END DO !jj
+         END DO 
+      END DO 
 
       !-----------------------------------------------------------------------------------------------
@@ -367,6 +312,6 @@
       DO jj = 1, jpj
          DO ji = 1, jpi
-            zhb0(ji,jj) = hi_max_typ(0,ntyp) ! 0eme
-            zhb1(ji,jj) = hi_max_typ(1,ntyp) ! 1er
+            zhb0(ji,jj) = hi_max(0) ! 0eme
+            zhb1(ji,jj) = hi_max(1) ! 1er
 
             zhbnew(ji,jj,klbnd-1) = 0._wp
@@ -380,5 +325,5 @@
             ENDIF
 
-            IF( zhbnew(ji,jj,kubnd) < hi_max(kubnd-1) )   zhbnew(ji,jj,kubnd) = hi_max(kubnd-1)
+            IF( zhbnew(ji,jj,kubnd) < hi_max(kubnd-1) ) zhbnew(ji,jj,kubnd) = hi_max(kubnd-1)
 
          END DO !jj
@@ -389,5 +334,5 @@
       !-----------------------------------------------------------------------------------------------
       !- 7.1 g(h) for category 1 at start of time step
-      CALL lim_itd_fitline( klbnd, zhb0, zhb1, zht_i_o(:,:,klbnd),         &
+      CALL lim_itd_fitline( klbnd, zhb0, zhb1, zht_i_b(:,:,klbnd),         &
          &                  g0(:,:,klbnd), g1(:,:,klbnd), hL(:,:,klbnd),   &
          &                  hR(:,:,klbnd), zremap_flag )
@@ -414,5 +359,5 @@
                   ! Constrain new thickness <= ht_i
                   zdamax = a_i(ii,ij,klbnd) * & 
-                     (1.0 - ht_i(ii,ij,klbnd)/zht_i_o(ii,ij,klbnd)) ! zdamax > 0
+                     (1.0 - ht_i(ii,ij,klbnd)/zht_i_b(ii,ij,klbnd)) ! zdamax > 0
                   !ice area lost due to melting of thin ice
                   zda0   = MIN(zda0, zdamax)
@@ -428,10 +373,7 @@
             ELSE ! if ice accretion
                ! ji, a_i > epsi10; zdh0 > 0
-               IF ( ntyp .EQ. 1 ) zhbnew(ii,ij,klbnd-1) = MIN(zdh0,hi_max(klbnd)) 
+               zhbnew(ii,ij,klbnd-1) = MIN(zdh0,hi_max(klbnd)) 
                ! zhbnew was 0, and is shifted to the right to account for thin ice
                ! growth in openwater (F0 = f1)
-               IF ( ntyp .NE. 1 ) zhbnew(ii,ij,0) = 0 
-               ! in other types there is
-               ! no open water growth (F0 = 0)
             ENDIF ! zdh0 
 
@@ -444,6 +386,5 @@
       DO jl = klbnd, kubnd
          CALL lim_itd_fitline(jl, zhbnew(:,:,jl-1), zhbnew(:,:,jl), ht_i(:,:,jl), &
-            g0(:,:,jl), g1(:,:,jl), hL(:,:,jl), hR(:,:,jl),     &
-            zremap_flag)
+            g0(:,:,jl), g1(:,:,jl), hL(:,:,jl), hR(:,:,jl), zremap_flag)
       END DO
 
@@ -493,6 +434,5 @@
             nd   = zdonor(ii,ij,jl)
             zdaice(ii,ij,jl) = g1(ii,ij,nd)*zx2 + g0(ii,ij,nd)*zx1
-            zdvice(ii,ij,jl) = g1(ii,ij,nd)*zx3 + g0(ii,ij,nd)*zx2 + &
-               zdaice(ii,ij,jl)*hL(ii,ij,nd)
+            zdvice(ii,ij,jl) = g1(ii,ij,nd)*zx3 + g0(ii,ij,nd)*zx2 + zdaice(ii,ij,jl)*hL(ii,ij,nd)
 
          END DO ! ji
@@ -511,8 +451,7 @@
          ii = nind_i(ji)
          ij = nind_j(ji)
-         IF ( ( a_i(ii,ij,1) > epsi10 ) .AND. ( ht_i(ii,ij,1) < hiclim ) ) THEN
+         IF ( a_i(ii,ij,1) > epsi10 .AND. ht_i(ii,ij,1) < hiclim ) THEN
             a_i(ii,ij,1)  = a_i(ii,ij,1) * ht_i(ii,ij,1) / hiclim 
             ht_i(ii,ij,1) = hiclim
-            v_i(ii,ij,1)  = a_i(ii,ij,1) * ht_i(ii,ij,1) !clem-useless
          ENDIF
       END DO !ji
@@ -542,5 +481,5 @@
       CALL wrk_dealloc( jpi,jpj, zremap_flag )    ! integer
       CALL wrk_dealloc( jpi,jpj,jpl-1, zdonor )   ! integer
-      CALL wrk_dealloc( jpi,jpj,jpl, zdhice, g0, g1, hL, hR, zht_i_o, dummy_es )
+      CALL wrk_dealloc( jpi,jpj,jpl, zdhice, g0, g1, hL, hR, zht_i_b, dummy_es )
       CALL wrk_dealloc( jpi,jpj,jpl-1, zdaice, zdvice )   
       CALL wrk_dealloc( jpi,jpj,jpl+1, zhbnew, kkstart = 0 )   
@@ -647,6 +586,4 @@
       REAL(wp) ::   zdo_aice           ! ice age times volume transferred
       REAL(wp) ::   zdaTsf             ! aicen*Tsfcn transferred
-      REAL(wp) ::   zindsn             ! snow or not
-      REAL(wp) ::   zindb              ! ice or not
 
       INTEGER, POINTER, DIMENSION(:) ::   nind_i, nind_j   ! compressed indices for i/j directions
@@ -775,6 +712,6 @@
 
             jl1 = zdonor(ii,ij,jl)
-            zindb             = MAX( 0.0 , SIGN( 1.0 , v_i(ii,ij,jl1) - epsi10 ) )
-            zworka(ii,ij)   = zdvice(ii,ij,jl) / MAX(v_i(ii,ij,jl1),epsi10) * zindb
+            rswitch             = MAX( 0.0 , SIGN( 1.0 , v_i(ii,ij,jl1) - epsi10 ) )
+            zworka(ii,ij)   = zdvice(ii,ij,jl) / MAX(v_i(ii,ij,jl1),epsi10) * rswitch
             IF( jl1 == jl) THEN   ;   jl2 = jl1+1
             ELSE                    ;   jl2 = jl 
@@ -799,5 +736,5 @@
             !--------------
 
-            zdvsnow          = v_s(ii,ij,jl1) * zworka(ii,ij)
+            zdvsnow        = v_s(ii,ij,jl1) * zworka(ii,ij)
             v_s(ii,ij,jl1) = v_s(ii,ij,jl1) - zdvsnow
             v_s(ii,ij,jl2) = v_s(ii,ij,jl2) + zdvsnow 
@@ -807,5 +744,5 @@
             !--------------------
 
-            zdesnow              = e_s(ii,ij,1,jl1) * zworka(ii,ij)
+            zdesnow            = e_s(ii,ij,1,jl1) * zworka(ii,ij)
             e_s(ii,ij,1,jl1)   = e_s(ii,ij,1,jl1) - zdesnow
             e_s(ii,ij,1,jl2)   = e_s(ii,ij,1,jl2) + zdesnow
@@ -815,5 +752,5 @@
             !--------------
 
-            zdo_aice             = oa_i(ii,ij,jl1) * zdaice(ii,ij,jl)
+            zdo_aice           = oa_i(ii,ij,jl1) * zdaice(ii,ij,jl)
             oa_i(ii,ij,jl1)    = oa_i(ii,ij,jl1) - zdo_aice
             oa_i(ii,ij,jl2)    = oa_i(ii,ij,jl2) + zdo_aice
@@ -823,5 +760,5 @@
             !--------------
 
-            zdsm_vice            = smv_i(ii,ij,jl1) * zworka(ii,ij)
+            zdsm_vice          = smv_i(ii,ij,jl1) * zworka(ii,ij)
             smv_i(ii,ij,jl1)   = smv_i(ii,ij,jl1) - zdsm_vice
             smv_i(ii,ij,jl2)   = smv_i(ii,ij,jl2) + zdsm_vice
@@ -831,5 +768,5 @@
             !---------------------
 
-            zdaTsf               = t_su(ii,ij,jl1) * zdaice(ii,ij,jl)
+            zdaTsf             = t_su(ii,ij,jl1) * zdaice(ii,ij,jl)
             zaTsfn(ii,ij,jl1)  = zaTsfn(ii,ij,jl1) - zdaTsf
             zaTsfn(ii,ij,jl2)  = zaTsfn(ii,ij,jl2) + zdaTsf 
@@ -872,5 +809,5 @@
                   ht_i(ji,jj,jl)  =  v_i   (ji,jj,jl) / a_i(ji,jj,jl) 
                   t_su(ji,jj,jl)  =  zaTsfn(ji,jj,jl) / a_i(ji,jj,jl) 
-                  zindsn          =  1.0 - MAX(0.0,SIGN(1.0,-v_s(ji,jj,jl)+epsi10)) !0 if no ice and 1 if yes
+                  rswitch         =  1.0 - MAX(0.0,SIGN(1.0,-v_s(ji,jj,jl)+epsi10)) !0 if no ice and 1 if yes
                ELSE
                   ht_i(ji,jj,jl)  = 0._wp
@@ -888,5 +825,5 @@
    
 
-   SUBROUTINE lim_itd_th_reb( klbnd, kubnd, ntyp )
+   SUBROUTINE lim_itd_th_reb( klbnd, kubnd )
       !!------------------------------------------------------------------
       !!                ***  ROUTINE lim_itd_th_reb ***
@@ -898,5 +835,4 @@
       INTEGER , INTENT (in) ::   klbnd   ! Start thickness category index point
       INTEGER , INTENT (in) ::   kubnd   ! End point on which the  the computation is applied
-      INTEGER , INTENT (in) ::   ntyp    ! number of the ice type involved in the rebinning process
       !
       INTEGER ::   ji,jj, jl   ! dummy loop indices
@@ -910,4 +846,5 @@
       REAL(wp), POINTER, DIMENSION(:,:) ::   vt_s_init, vt_s_final   ! snow volume summed over categories
       !!------------------------------------------------------------------
+      !! clem 2014/04: be carefull, rebining does not conserve salt(maybe?) => the difference is taken into account in limupdate
       
       CALL wrk_alloc( jpi,jpj,jpl, zdonor )   ! interger
@@ -937,12 +874,12 @@
 
       !------------------------------------------------------------------------------
-      ! 2) Make sure thickness of cat klbnd is at least hi_max_typ(klbnd)
+      ! 2) Make sure thickness of cat klbnd is at least hi_max(klbnd)
       !------------------------------------------------------------------------------
       DO jj = 1, jpj 
          DO ji = 1, jpi 
             IF( a_i(ji,jj,klbnd) > epsi10 ) THEN
-               IF( ht_i(ji,jj,klbnd) <= hi_max_typ(0,ntyp) .AND. hi_max_typ(0,ntyp) > 0._wp ) THEN
-                  a_i(ji,jj,klbnd)  = v_i(ji,jj,klbnd) / hi_max_typ(0,ntyp) 
-                  ht_i(ji,jj,klbnd) = hi_max_typ(0,ntyp)
+               IF( ht_i(ji,jj,klbnd) <= hi_max(0) .AND. hi_max(0) > 0._wp ) THEN
+                  a_i(ji,jj,klbnd)  = v_i(ji,jj,klbnd) / hi_max(0) 
+                  ht_i(ji,jj,klbnd) = hi_max(0)
                ENDIF
             ENDIF
@@ -1015,38 +952,36 @@
 
 !clem-change
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( a_i(ji,jj,jl+1) > epsi10 .AND. ht_i(ji,jj,jl+1) <= hi_max(jl) ) THEN
+                  !
+                  zshiftflag = 1
+                  zdonor(ji,jj,jl) = jl + 1
+                  zdaice(ji,jj,jl) = a_i(ji,jj,jl+1) 
+                  zdvice(ji,jj,jl) = v_i(ji,jj,jl+1)
+               ENDIF
+            END DO                 ! ji
+         END DO                 ! jj
+
+         IF(lk_mpp)   CALL mpp_max( zshiftflag )
+         
+         IF( zshiftflag == 1 ) THEN            ! Shift ice between categories
+            CALL lim_itd_shiftice( klbnd, kubnd, zdonor, zdaice, zdvice )
+            ! Reset shift parameters
+            zdonor(:,:,jl) = 0
+            zdaice(:,:,jl) = 0._wp
+            zdvice(:,:,jl) = 0._wp
+         ENDIF
+!clem-change
+
+!         ! clem-change begin: why not doing that?
 !         DO jj = 1, jpj
 !            DO ji = 1, jpi
-!               IF( a_i(ji,jj,jl+1) >  epsi10 .AND.   &
-!                  ht_i(ji,jj,jl+1) <= hi_max(jl) ) THEN
-!                  !
-!                  zshiftflag = 1
-!                  zdonor(ji,jj,jl) = jl + 1
-!                  zdaice(ji,jj,jl) = a_i(ji,jj,jl+1) 
-!                  zdvice(ji,jj,jl) = v_i(ji,jj,jl+1)
+!               IF( a_i(ji,jj,jl+1) > epsi10 .AND. ht_i(ji,jj,jl+1) <= hi_max(jl) ) THEN
+!                  ht_i(ji,jj,jl+1) = hi_max(jl) + epsi10
+!                  a_i (ji,jj,jl+1) = v_i(ji,jj,jl+1) / ht_i(ji,jj,jl+1) 
 !               ENDIF
 !            END DO                 ! ji
 !         END DO                 ! jj
-!
-!         IF(lk_mpp)   CALL mpp_max( zshiftflag )
-!         
-!         IF( zshiftflag == 1 ) THEN            ! Shift ice between categories
-!            CALL lim_itd_shiftice( klbnd, kubnd, zdonor, zdaice, zdvice )
-!            ! Reset shift parameters
-!            zdonor(:,:,jl) = 0
-!            zdaice(:,:,jl) = 0._wp
-!            zdvice(:,:,jl) = 0._wp
-!         ENDIF
-!clem-change
-
-         ! clem-change begin: why not doing that?
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-               IF( a_i(ji,jj,jl+1) >  epsi10 .AND.   &
-                  ht_i(ji,jj,jl+1) <= hi_max(jl) ) THEN
-                  ht_i(ji,jj,jl+1) = hi_max(jl) + epsi10
-                  a_i (ji,jj,jl+1) = v_i(ji,jj,jl+1) / ht_i(ji,jj,jl+1) 
-               ENDIF
-            END DO                 ! ji
-         END DO                 ! jj
          ! clem-change end
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limrhg.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limrhg.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limrhg.F90	(revision 5075)
@@ -50,8 +50,4 @@
    PUBLIC   lim_rhg        ! routine called by lim_dyn (or lim_dyn_2)
 
-   REAL(wp) ::   epsi10 = 1.e-10_wp   !
-   REAL(wp) ::   rzero   = 0._wp   ! constant values
-   REAL(wp) ::   rone    = 1._wp   ! constant values
-      
    !! * Substitutions
 #  include "vectopt_loop_substitute.h90"
@@ -121,5 +117,6 @@
       CHARACTER (len=50) ::   charout
       REAL(wp) ::   zt11, zt12, zt21, zt22, ztagnx, ztagny, delta                         !
-      REAL(wp) ::   za, zstms, zsang, zmask   ! local scalars
+      REAL(wp) ::   za, zstms, zmask   ! local scalars
+      REAL(wp) ::   zc1, zc2, zc3             ! ice mass
 
       REAL(wp) ::   dtevp              ! time step for subcycling
@@ -127,10 +124,10 @@
       REAL(wp) ::   z0, zr, zcca, zccb ! temporary scalars
       REAL(wp) ::   zu_ice2, zv_ice1   !
-      REAL(wp) ::   zddc, zdtc, zzdst   ! delta on corners and on centre
+      REAL(wp) ::   zddc, zdtc         ! delta on corners and on centre
+      REAL(wp) ::   zdst               ! shear at the center of the grid point
       REAL(wp) ::   zdsshx, zdsshy     ! term for the gradient of ocean surface
       REAL(wp) ::   sigma1, sigma2     ! internal ice stress
 
       REAL(wp) ::   zresm         ! Maximal error on ice velocity
-      REAL(wp) ::   zindb         ! ice (1) or not (0)      
       REAL(wp) ::   zdummy        ! dummy argument
       REAL(wp) ::   zintb, zintn  ! dummy argument
@@ -142,6 +139,4 @@
       REAL(wp), POINTER, DIMENSION(:,:) ::   zcorl1, zcorl2   ! coriolis parameter on U/V points
       REAL(wp), POINTER, DIMENSION(:,:) ::   za1ct , za2ct    ! temporary arrays
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zc1              ! ice mass
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zusw             ! temporary weight for ice strength computation
       REAL(wp), POINTER, DIMENSION(:,:) ::   u_oce1, v_oce1   ! ocean u/v component on U points                           
       REAL(wp), POINTER, DIMENSION(:,:) ::   u_oce2, v_oce2   ! ocean u/v component on V points
@@ -149,8 +144,6 @@
       REAL(wp), POINTER, DIMENSION(:,:) ::   zf1   , zf2      ! arrays for internal stresses
       
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zdd   , zdt      ! Divergence and tension at centre of grid cells
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zdt              ! tension at centre of grid cells
       REAL(wp), POINTER, DIMENSION(:,:) ::   zds              ! Shear on northeast corner of grid cells
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zdst             ! Shear on centre of grid cells
-      REAL(wp), POINTER, DIMENSION(:,:) ::   deltat, deltac   ! Delta at centre and corners of grid cells
       REAL(wp), POINTER, DIMENSION(:,:) ::   zs1   , zs2      ! Diagonal stress tensor components zs1 and zs2 
       REAL(wp), POINTER, DIMENSION(:,:) ::   zs12             ! Non-diagonal stress tensor component zs12
@@ -162,7 +155,7 @@
 
       CALL wrk_alloc( jpi,jpj, zpresh, zfrld1, zmass1, zcorl1, za1ct , zpreshc, zfrld2, zmass2, zcorl2, za2ct )
-      CALL wrk_alloc( jpi,jpj, zc1   , u_oce1, u_oce2, u_ice2, zusw  , v_oce1 , v_oce2, v_ice1                )
-      CALL wrk_alloc( jpi,jpj, zf1   , deltat, zu_ice, zf2   , deltac, zv_ice , zdd   , zdt    , zds  , zdst  )
-      CALL wrk_alloc( jpi,jpj, zdd   , zdt   , zds   , zs1   , zs2   , zs12   , zresr , zpice                 )
+      CALL wrk_alloc( jpi,jpj, u_oce1, u_oce2, u_ice2, v_oce1 , v_oce2, v_ice1                )
+      CALL wrk_alloc( jpi,jpj, zf1   , zu_ice, zf2   , zv_ice , zdt    , zds  )
+      CALL wrk_alloc( jpi,jpj, zdt   , zds   , zs1   , zs2   , zs12   , zresr , zpice                 )
 
 #if  defined key_lim2 && ! defined key_lim2_vp
@@ -181,12 +174,14 @@
       !
       !------------------------------------------------------------------------------!
-      ! 1) Ice-Snow mass (zc1), ice strength (zpresh)                                !
+      ! 1) Ice strength (zpresh)                                !
       !------------------------------------------------------------------------------!
       !
       ! Put every vector to 0
-      zpresh (:,:) = 0._wp   ;   zc1   (:,:) = 0._wp
+      delta_i(:,:) = 0._wp   ;
+      zpresh (:,:) = 0._wp   ;  
       zpreshc(:,:) = 0._wp
       u_ice2 (:,:) = 0._wp   ;   v_ice1(:,:) = 0._wp
-      zdd    (:,:) = 0._wp   ;   zdt   (:,:) = 0._wp   ;   zds(:,:) = 0._wp
+      divu_i (:,:) = 0._wp   ;   zdt   (:,:) = 0._wp   ;   zds(:,:) = 0._wp
+      shear_i(:,:) = 0._wp
 
 #if defined key_lim3
@@ -198,5 +193,4 @@
 !CDIR NOVERRCHK
          DO ji = 1 , jpi
-            zc1(ji,jj)    = tms(ji,jj) * ( rhosn * vt_s(ji,jj) + rhoic * vt_i(ji,jj) )
 #if defined key_lim3
             zpresh(ji,jj) = tms(ji,jj) *  strength(ji,jj)
@@ -220,10 +214,9 @@
                &              tms(ji+1,jj)   * wght(ji+1,jj+1,2,1) + &
                &              tms(ji,jj)     * wght(ji+1,jj+1,1,1)
-            zusw(ji,jj)    = 1.0 / MAX( zstms, epsd )
             zpreshc(ji,jj) = (  zpresh(ji+1,jj+1) * wght(ji+1,jj+1,2,2) + &
                &                zpresh(ji,jj+1)   * wght(ji+1,jj+1,1,2) + &
                &                zpresh(ji+1,jj)   * wght(ji+1,jj+1,2,1) + & 
                &                zpresh(ji,jj)     * wght(ji+1,jj+1,1,1)   &
-               &             ) * zusw(ji,jj)
+               &             ) / MAX( zstms, epsd )
          END DO
       END DO
@@ -267,4 +260,8 @@
          DO ji = fs_2, fs_jpim1
 
+            zc1 = tms(ji  ,jj  ) * ( rhosn * vt_s(ji  ,jj  ) + rhoic * vt_i(ji  ,jj  ) )
+            zc2 = tms(ji+1,jj  ) * ( rhosn * vt_s(ji+1,jj  ) + rhoic * vt_i(ji+1,jj  ) )
+            zc3 = tms(ji  ,jj+1) * ( rhosn * vt_s(ji  ,jj+1) + rhoic * vt_i(ji  ,jj+1) )
+
             zt11 = tms(ji  ,jj) * e1t(ji  ,jj)
             zt12 = tms(ji+1,jj) * e1t(ji+1,jj)
@@ -277,6 +274,6 @@
 
             ! Mass, coriolis coeff. and currents
-            zmass1(ji,jj) = ( zt12*zc1(ji,jj) + zt11*zc1(ji+1,jj) ) / (zt11+zt12+epsd)
-            zmass2(ji,jj) = ( zt22*zc1(ji,jj) + zt21*zc1(ji,jj+1) ) / (zt21+zt22+epsd)
+            zmass1(ji,jj) = ( zt12*zc1 + zt11*zc2 ) / (zt11+zt12+epsd)
+            zmass2(ji,jj) = ( zt22*zc1 + zt21*zc3 ) / (zt21+zt22+epsd)
             zcorl1(ji,jj) = zmass1(ji,jj) * ( e1t(ji+1,jj)*fcor(ji,jj) + e1t(ji,jj)*fcor(ji+1,jj) )   &
                &                          / ( e1t(ji,jj) + e1t(ji+1,jj) + epsd )
@@ -346,5 +343,5 @@
                !  
                !- Divergence, tension and shear (Section a. Appendix B of Hunke & Dukowicz, 2002)
-               !- zdd(:,:), zdt(:,:): divergence and tension at centre of grid cells
+               !- divu_i(:,:), zdt(:,:): divergence and tension at centre of grid cells
                !- zds(:,:): shear on northeast corner of grid cells
                !
@@ -355,5 +352,5 @@
                !                      bugs (Martin, for Miguel).
                !
-               !- ALSO: arrays zdd, zdt, zds and delta could 
+               !- ALSO: arrays zdt, zds and delta could 
                !  be removed in the future to minimise memory demand.
                !
@@ -363,10 +360,10 @@
                !
                !
-               zdd(ji,jj) = ( e2u(ji,jj)*u_ice(ji,jj)                      &
-                  &          -e2u(ji-1,jj)*u_ice(ji-1,jj)                  &
-                  &          +e1v(ji,jj)*v_ice(ji,jj)                      &
-                  &          -e1v(ji,jj-1)*v_ice(ji,jj-1)                  &
-                  &          )                                             &
-                  &         / area(ji,jj)
+               divu_i(ji,jj) = ( e2u(ji,jj)*u_ice(ji,jj)                      &
+                  &             -e2u(ji-1,jj)*u_ice(ji-1,jj)                  &
+                  &             +e1v(ji,jj)*v_ice(ji,jj)                      &
+                  &             -e1v(ji,jj-1)*v_ice(ji,jj-1)                  &
+                  &             )                                             &
+                  &            / area(ji,jj)
 
                zdt(ji,jj) = ( ( u_ice(ji,jj)/e2u(ji,jj)                    &
@@ -410,5 +407,5 @@
 
                !- Calculate Delta at centre of grid cells
-               zzdst      = (  e2u(ji  , jj) * v_ice1(ji  ,jj)          &
+               zdst      = (  e2u(ji  , jj) * v_ice1(ji  ,jj)          &
                   &          - e2u(ji-1, jj) * v_ice1(ji-1,jj)          &
                   &          + e1v(ji, jj  ) * u_ice2(ji,jj  )          &
@@ -417,26 +414,11 @@
                   &         / area(ji,jj)
 
-               delta = SQRT( zdd(ji,jj)*zdd(ji,jj) + ( zdt(ji,jj)*zdt(ji,jj) + zzdst*zzdst ) * usecc2 )  
-               ! MV rewriting
-               ! deltat(ji,jj) = MAX( SQRT(zdd(ji,jj)**2 + (zdt(ji,jj)**2 + zzdst**2)*usecc2), creepl )
-               !!gm faster to replace the line above with simply:
-               !!                deltat(ji,jj) = MAX( delta, creepl )
-               !!gm end  
-               deltat(ji,jj) = delta + creepl
-               ! END MV
+               delta = SQRT( divu_i(ji,jj)*divu_i(ji,jj) + ( zdt(ji,jj)*zdt(ji,jj) + zdst*zdst ) * usecc2 )  
+               delta_i(ji,jj) = delta + creepl
                !-Calculate stress tensor components zs1 and zs2 
                !-at centre of grid cells (see section 3.5 of CICE user's guide).
-               !zs1(ji,jj) = ( zs1(ji,jj) - dtotel*( ( 1._wp - alphaevp) * zs1(ji,jj) +   &
-               !   &          ( delta / deltat(ji,jj) - zdd(ji,jj) / deltat(ji,jj) ) * zpresh(ji,jj) ) )  &       
-               !   &          / ( 1._wp + alphaevp * dtotel )
-
-               !zs2(ji,jj) = ( zs2(ji,jj) - dtotel * ( ( 1._wp - alphaevp ) * ecc2 * zs2(ji,jj) -   &
-               !              zdt(ji,jj) / deltat(ji,jj) * zpresh(ji,jj) ) )   &
-               !   &          / ( 1._wp + alphaevp * ecc2 * dtotel )
-
-               ! new formulation from S. Bouillon to help stabilizing the code (no need of alphaevp)
-               zs1(ji,jj) = ( zs1(ji,jj) + dtotel * ( ( zdd(ji,jj) / deltat(ji,jj) - delta / deltat(ji,jj) )  &
+               zs1(ji,jj) = ( zs1(ji,jj) + dtotel * ( ( divu_i(ji,jj) / delta_i(ji,jj) - delta / delta_i(ji,jj) )  &
                   &         * zpresh(ji,jj) ) ) / ( 1._wp + dtotel )
-               zs2(ji,jj) = ( zs2(ji,jj) + dtotel * ( ecci * zdt(ji,jj) / deltat(ji,jj) * zpresh(ji,jj) ) )  &
+               zs2(ji,jj) = ( zs2(ji,jj) + dtotel * ( ecci * zdt(ji,jj) / delta_i(ji,jj) * zpresh(ji,jj) ) )  &
                   &         / ( 1._wp + dtotel )
 
@@ -470,14 +452,9 @@
                   &        / ( e1f(ji,jj) * e2f(ji,jj) )
 
-               deltac(ji,jj) = SQRT(zddc**2+(zdtc**2+zds(ji,jj)**2)*usecc2) + creepl
+               zddc = SQRT(zddc**2+(zdtc**2+zds(ji,jj)**2)*usecc2) + creepl
 
                !-Calculate stress tensor component zs12 at corners (see section 3.5 of CICE user's guide).
-               !zs12(ji,jj) = ( zs12(ji,jj) - dtotel * ( (1.0-alphaevp) * ecc2 * zs12(ji,jj) - zds(ji,jj) /  &
-               !   &          ( 2._wp * deltac(ji,jj) ) * zpreshc(ji,jj) ) )  &
-               !   &          / ( 1._wp + alphaevp * ecc2 * dtotel ) 
-
-               ! new formulation from S. Bouillon to help stabilizing the code (no need of alphaevp)
                zs12(ji,jj) = ( zs12(ji,jj) + dtotel *  &
-                  &          ( ecci * zds(ji,jj) / ( 2._wp * deltac(ji,jj) ) * zpreshc(ji,jj) ) )  &
+                  &          ( ecci * zds(ji,jj) / ( 2._wp * zddc ) * zpreshc(ji,jj) ) )  &
                   &          / ( 1.0 + dtotel ) 
 
@@ -514,6 +491,5 @@
 !CDIR NOVERRCHK
                DO ji = fs_2, fs_jpim1
-                  zmask        = (1.0-MAX(rzero,SIGN(rone,-zmass1(ji,jj))))*tmu(ji,jj)
-                  zsang        = SIGN ( 1.0 , fcor(ji,jj) ) * sangvg
+                  zmask        = (1.0-MAX(0._wp,SIGN(1._wp,-zmass1(ji,jj))))*tmu(ji,jj)
                   z0           = zmass1(ji,jj)/dtevp
 
@@ -525,7 +501,7 @@
                      (zv_ice1-v_oce1(ji,jj))**2) * (1.0-zfrld1(ji,jj))
                   zr           = z0*u_ice(ji,jj) + zf1(ji,jj) + za1ct(ji,jj) + &
-                     za*(cangvg*u_oce1(ji,jj)-zsang*v_oce1(ji,jj))
-                  zcca         = z0+za*cangvg
-                  zccb         = zcorl1(ji,jj)+za*zsang
+                     za*(u_oce1(ji,jj))
+                  zcca         = z0+za
+                  zccb         = zcorl1(ji,jj)
                   u_ice(ji,jj) = (zr+zccb*zv_ice1)/(zcca+epsd)*zmask 
 
@@ -538,5 +514,4 @@
 #endif
 #if defined key_bdy
-         ! clem: change u_ice and v_ice at the boundary for each iteration
          CALL bdy_ice_lim_dyn( 'U' )
 #endif         
@@ -547,6 +522,5 @@
                DO ji = fs_2, fs_jpim1
 
-                  zmask        = (1.0-MAX(rzero,SIGN(rone,-zmass2(ji,jj))))*tmv(ji,jj)
-                  zsang        = SIGN(1.0,fcor(ji,jj))*sangvg
+                  zmask        = (1.0-MAX(0._wp,SIGN(1._wp,-zmass2(ji,jj))))*tmv(ji,jj)
                   z0           = zmass2(ji,jj)/dtevp
                   ! SB modif because ocean has no slip boundary condition
@@ -557,7 +531,7 @@
                      (v_ice(ji,jj)-v_oce2(ji,jj))**2)*(1.0-zfrld2(ji,jj))
                   zr           = z0*v_ice(ji,jj) + zf2(ji,jj) + &
-                     za2ct(ji,jj) + za*(cangvg*v_oce2(ji,jj)+zsang*u_oce2(ji,jj))
-                  zcca         = z0+za*cangvg
-                  zccb         = zcorl2(ji,jj)+za*zsang
+                     za2ct(ji,jj) + za*(v_oce2(ji,jj))
+                  zcca         = z0+za
+                  zccb         = zcorl2(ji,jj)
                   v_ice(ji,jj) = (zr-zccb*zu_ice2)/(zcca+epsd)*zmask
 
@@ -570,5 +544,4 @@
 #endif
 #if defined key_bdy
-         ! clem: change u_ice and v_ice at the boundary for each iteration
          CALL bdy_ice_lim_dyn( 'V' )
 #endif         
@@ -579,6 +552,5 @@
 !CDIR NOVERRCHK
                DO ji = fs_2, fs_jpim1
-                  zmask        = (1.0-MAX(rzero,SIGN(rone,-zmass2(ji,jj))))*tmv(ji,jj)
-                  zsang        = SIGN(1.0,fcor(ji,jj))*sangvg
+                  zmask        = (1.0-MAX(0._wp,SIGN(1._wp,-zmass2(ji,jj))))*tmv(ji,jj)
                   z0           = zmass2(ji,jj)/dtevp
                   ! SB modif because ocean has no slip boundary condition
@@ -590,7 +562,7 @@
                      (v_ice(ji,jj)-v_oce2(ji,jj))**2)*(1.0-zfrld2(ji,jj))
                   zr           = z0*v_ice(ji,jj) + zf2(ji,jj) + &
-                     za2ct(ji,jj) + za*(cangvg*v_oce2(ji,jj)+zsang*u_oce2(ji,jj))
-                  zcca         = z0+za*cangvg
-                  zccb         = zcorl2(ji,jj)+za*zsang
+                     za2ct(ji,jj) + za*(v_oce2(ji,jj))
+                  zcca         = z0+za
+                  zccb         = zcorl2(ji,jj)
                   v_ice(ji,jj) = (zr-zccb*zu_ice2)/(zcca+epsd)*zmask
 
@@ -603,5 +575,4 @@
 #endif
 #if defined key_bdy
-         ! clem: change u_ice and v_ice at the boundary for each iteration
          CALL bdy_ice_lim_dyn( 'V' )
 #endif         
@@ -611,12 +582,6 @@
 !CDIR NOVERRCHK
                DO ji = fs_2, fs_jpim1
-                  zmask        = (1.0-MAX(rzero,SIGN(rone,-zmass1(ji,jj))))*tmu(ji,jj)
-                  zsang        = SIGN(1.0,fcor(ji,jj))*sangvg
+                  zmask        = (1.0-MAX(0._wp,SIGN(1._wp,-zmass1(ji,jj))))*tmu(ji,jj)
                   z0           = zmass1(ji,jj)/dtevp
-                  ! SB modif because ocean has no slip boundary condition
-                  ! GG Bug
-                  !                   zv_ice1       = 0.5*( (v_ice(ji,jj)+v_ice(ji,jj-1))*e1t(ji+1,jj)      &
-                  !                      &                 +(v_ice(ji+1,jj)+v_ice(ji+1,jj-1))*e1t(ji,jj))   &
-                  !                      &               /(e1t(ji+1,jj)+e1t(ji,jj)) * tmu(ji,jj)
                   zv_ice1       = 0.5*( (v_ice(ji,jj)+v_ice(ji,jj-1))*e1t(ji,jj)      &
                      &                 +(v_ice(ji+1,jj)+v_ice(ji+1,jj-1))*e1t(ji+1,jj))   &
@@ -626,7 +591,7 @@
                      (zv_ice1-v_oce1(ji,jj))**2)*(1.0-zfrld1(ji,jj))
                   zr           = z0*u_ice(ji,jj) + zf1(ji,jj) + za1ct(ji,jj) + &
-                     za*(cangvg*u_oce1(ji,jj)-zsang*v_oce1(ji,jj))
-                  zcca         = z0+za*cangvg
-                  zccb         = zcorl1(ji,jj)+za*zsang
+                     za*(u_oce1(ji,jj))
+                  zcca         = z0+za
+                  zccb         = zcorl1(ji,jj)
                   u_ice(ji,jj) = (zr+zccb*zv_ice1)/(zcca+epsd)*zmask 
                END DO ! ji
@@ -638,5 +603,4 @@
 #endif
 #if defined key_bdy
-         ! clem: change u_ice and v_ice at the boundary for each iteration
          CALL bdy_ice_lim_dyn( 'U' )
 #endif         
@@ -661,6 +625,4 @@
       ! 4) Prevent ice velocities when the ice is thin
       !------------------------------------------------------------------------------!
-      !clem : add hminrhg in the namelist
-      !
       ! If the ice thickness is below hminrhg (5cm) then ice velocity should equal the
       ! ocean velocity, 
@@ -670,6 +632,4 @@
 !CDIR NOVERRCHK
          DO ji = fs_2, fs_jpim1
-            zindb  = MAX( 0.0, SIGN( 1.0, at_i(ji,jj) - epsi10 ) ) 
-            !zdummy = zindb * vt_i(ji,jj) / MAX(at_i(ji,jj) , epsi10 )
             zdummy = vt_i(ji,jj)
             IF ( zdummy .LE. hminrhg ) THEN
@@ -687,5 +647,4 @@
 #endif
 #if defined key_bdy
-      ! clem: change u_ice and v_ice at the boundary
       CALL bdy_ice_lim_dyn( 'U' )
       CALL bdy_ice_lim_dyn( 'V' )
@@ -694,6 +653,4 @@
       DO jj = k_j1+1, k_jpj-1 
          DO ji = fs_2, fs_jpim1
-            zindb  = MAX( 0.0, SIGN( 1.0, at_i(ji,jj) - epsi10 ) ) 
-            !zdummy = zindb * vt_i(ji,jj) / MAX(at_i(ji,jj) , epsi10 )
             zdummy = vt_i(ji,jj)
             IF ( zdummy .LE. hminrhg ) THEN
@@ -717,17 +674,15 @@
 !CDIR NOVERRCHK
          DO ji = fs_2, jpim1   !RB bug no vect opt due to tmi
-            !- zdd(:,:), zdt(:,:): divergence and tension at centre 
+            !- divu_i(:,:), zdt(:,:): divergence and tension at centre 
             !- zds(:,:): shear on northeast corner of grid cells
-            zindb  = MAX( 0.0, SIGN( 1.0, at_i(ji,jj) - epsi10 ) ) 
-            !zdummy = zindb * vt_i(ji,jj) / MAX(at_i(ji,jj) , epsi10 )
             zdummy = vt_i(ji,jj)
             IF ( zdummy .LE. hminrhg ) THEN
 
-               zdd(ji,jj) = ( e2u(ji,jj)*u_ice(ji,jj)                      &
-                  &          -e2u(ji-1,jj)*u_ice(ji-1,jj)                  &
-                  &          +e1v(ji,jj)*v_ice(ji,jj)                      &
-                  &          -e1v(ji,jj-1)*v_ice(ji,jj-1)                  &
-                  &         )                                              &
-                  &         / area(ji,jj)
+               divu_i(ji,jj) = ( e2u(ji,jj)*u_ice(ji,jj)                      &
+                  &             -e2u(ji-1,jj)*u_ice(ji-1,jj)                  &
+                  &             +e1v(ji,jj)*v_ice(ji,jj)                      &
+                  &             -e1v(ji,jj-1)*v_ice(ji,jj-1)                  &
+                  &            )                                              &
+                  &            / area(ji,jj)
 
                zdt(ji,jj) = ( ( u_ice(ji,jj)/e2u(ji,jj)                    &
@@ -751,16 +706,11 @@
                   &        * tmi(ji+1,jj) * tmi(ji+1,jj+1)
 
-               zdst(ji,jj) = (  e2u( ji  , jj   ) * v_ice1(ji  ,jj  )    &
+               zdst = (  e2u( ji  , jj   ) * v_ice1(ji  ,jj  )    &
                   &           - e2u( ji-1, jj   ) * v_ice1(ji-1,jj  )    &
                   &           + e1v( ji  , jj   ) * u_ice2(ji  ,jj  )    &
                   &           - e1v( ji  , jj-1 ) * u_ice2(ji  ,jj-1)  ) / area(ji,jj)
 
-!              deltat(ji,jj) = SQRT(    zdd(ji,jj)*zdd(ji,jj)   & 
-!                  &                 + ( zdt(ji,jj)*zdt(ji,jj) + zdst(ji,jj)*zdst(ji,jj) ) * usecc2 & 
-!                  &                          ) + creepl
-               ! MV rewriting
-               delta = SQRT( zdd(ji,jj)*zdd(ji,jj) + ( zdt(ji,jj)*zdt(ji,jj) + zdst(ji,jj)*zdst(ji,jj) ) * usecc2 )  
-               deltat(ji,jj) = delta + creepl
-               ! END MV
+               delta = SQRT( divu_i(ji,jj)*divu_i(ji,jj) + ( zdt(ji,jj)*zdt(ji,jj) + zdst*zdst ) * usecc2 )  
+               delta_i(ji,jj) = delta + creepl
             
             ENDIF ! zdummy
@@ -777,12 +727,10 @@
       DO jj = k_j1+1, k_jpj-1
          DO ji = fs_2, fs_jpim1
-            divu_i (ji,jj) = zdd   (ji,jj)
-            delta_i(ji,jj) = deltat(ji,jj)
             ! begin TECLIM change 
-            zdst(ji,jj)= (  e2u( ji  , jj   ) * v_ice1(ji,jj)           &   
+            zdst= (  e2u( ji  , jj   ) * v_ice1(ji,jj)           &   
                &          - e2u( ji-1, jj   ) * v_ice1(ji-1,jj)         &   
                &          + e1v( ji  , jj   ) * u_ice2(ji,jj)           &   
                &          - e1v( ji  , jj-1 ) * u_ice2(ji,jj-1) ) / area(ji,jj) 
-            shear_i(ji,jj) = SQRT( zdt(ji,jj) * zdt(ji,jj) + zdst(ji,jj) * zdst(ji,jj) )
+            shear_i(ji,jj) = SQRT( zdt(ji,jj) * zdt(ji,jj) + zdst * zdst )
             ! end TECLIM change
          END DO
@@ -838,7 +786,7 @@
       !
       CALL wrk_dealloc( jpi,jpj, zpresh, zfrld1, zmass1, zcorl1, za1ct , zpreshc, zfrld2, zmass2, zcorl2, za2ct )
-      CALL wrk_dealloc( jpi,jpj, zc1   , u_oce1, u_oce2, u_ice2, zusw  , v_oce1 , v_oce2, v_ice1                )
-      CALL wrk_dealloc( jpi,jpj, zf1   , deltat, zu_ice, zf2   , deltac, zv_ice , zdd   , zdt    , zds  , zdst  )
-      CALL wrk_dealloc( jpi,jpj, zdd   , zdt   , zds   , zs1   , zs2   , zs12   , zresr , zpice                 )
+      CALL wrk_dealloc( jpi,jpj, u_oce1, u_oce2, u_ice2, v_oce1 , v_oce2, v_ice1                )
+      CALL wrk_dealloc( jpi,jpj, zf1   , zu_ice, zf2   , zv_ice , zdt    , zds  )
+      CALL wrk_dealloc( jpi,jpj, zdt   , zds   , zs1   , zs2   , zs12   , zresr , zpice                 )
 
    END SUBROUTINE lim_rhg
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limrst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limrst.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limrst.F90	(revision 5075)
@@ -142,5 +142,5 @@
          CALL iom_rstput( iter, nitrst, numriw, znam , z2d )
       END DO
-
+      
       DO jl = 1, jpl 
          WRITE(zchar,'(I1)') jl
@@ -162,5 +162,4 @@
       CALL iom_rstput( iter, nitrst, numriw, 'u_ice'        , u_ice      )
       CALL iom_rstput( iter, nitrst, numriw, 'v_ice'        , v_ice      )
-      CALL iom_rstput( iter, nitrst, numriw, 'fsbbq'        , fsbbq      )
       CALL iom_rstput( iter, nitrst, numriw, 'stress1_i'    , stress1_i  )
       CALL iom_rstput( iter, nitrst, numriw, 'stress2_i'    , stress2_i  )
@@ -309,6 +308,6 @@
       INTEGER :: ji, jj, jk, jl, indx
       REAL(wp) ::   zfice, ziter
-      REAL(wp) ::   zs_inf, z_slope_s, zsmax, zsmin, zalpha, zindb   ! local scalars used for the salinity profile
-      REAL(wp), POINTER, DIMENSION(:)  ::   zs_zero 
+      REAL(wp) ::   zs_inf, z_slope_s, zsmax, zsmin, zalpha   ! local scalars used for the salinity profile
+      REAL(wp), POINTER, DIMENSION(:)   ::   zs_zero 
       REAL(wp), POINTER, DIMENSION(:,:) ::   z2d
       CHARACTER(len=15) ::   znam
@@ -393,5 +392,4 @@
       CALL iom_get( numrir, jpdom_autoglo, 'u_ice'     , u_ice      )
       CALL iom_get( numrir, jpdom_autoglo, 'v_ice'     , v_ice      )
-      CALL iom_get( numrir, jpdom_autoglo, 'fsbbq'     , fsbbq      )
       CALL iom_get( numrir, jpdom_autoglo, 'stress1_i' , stress1_i  )
       CALL iom_get( numrir, jpdom_autoglo, 'stress2_i' , stress2_i  )
@@ -522,4 +520,15 @@
       END DO
       !
+      ! clem: I do not understand why the following IF is needed
+      !       I suspect something inconsistent in the main code with option num_sal=1
+      IF( num_sal == 1 ) THEN
+         DO jl = 1, jpl 
+            sm_i(:,:,jl) = bulk_sal
+            DO jk = 1, nlay_i 
+               s_i(:,:,jk,jl) = bulk_sal
+            END DO
+         END DO
+      ENDIF
+      !
       !CALL iom_close( numrir ) !clem: closed in sbcice_lim.F90
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limsbc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limsbc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limsbc.F90	(revision 5075)
@@ -27,12 +27,10 @@
    USE par_ice          ! ice parameters
    USE dom_oce          ! ocean domain
-   USE domvvl           ! ocean vertical scale factors
-   USE dom_ice,    ONLY : tms
+   USE dom_ice,    ONLY : tms, area
    USE ice              ! LIM sea-ice variables
    USE sbc_ice          ! Surface boundary condition: sea-ice fields
    USE sbc_oce          ! Surface boundary condition: ocean fields
    USE sbccpl
-   USE cpl_oasis3, ONLY : lk_cpl
-   USE oce       , ONLY : iatte, oatte, sshn, sshb, snwice_mass, snwice_mass_b, snwice_fmass
+   USE oce       , ONLY : fraqsr_1lev, sshn, sshb, snwice_mass, snwice_mass_b, snwice_fmass
    USE albedo           ! albedo parameters
    USE lbclnk           ! ocean lateral boundary condition - MPP exchanges
@@ -43,4 +41,6 @@
    USE lib_fortran      ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
    USE traqsr           ! clem: add penetration of solar flux into the calculation of heat budget
+   USE iom
+   USE domvvl           ! Variable volume
 
    IMPLICIT NONE
@@ -50,7 +50,4 @@
    PUBLIC   lim_sbc_flx    ! called by sbc_ice_lim
    PUBLIC   lim_sbc_tau    ! called by sbc_ice_lim
-
-   REAL(wp)  ::   rzero  = 0._wp    
-   REAL(wp)  ::   rone   = 1._wp
 
    REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::   utau_oce, vtau_oce   ! air-ocean surface i- & j-stress     [N/m2]
@@ -97,107 +94,67 @@
       !!              - fr_i    : ice fraction
       !!              - tn_ice  : sea-ice surface temperature
-      !!              - alb_ice : sea-ice alberdo (lk_cpl=T)
+      !!              - alb_ice : sea-ice albedo (lk_cpl=T)
       !!
       !! References : Goosse, H. et al. 1996, Bul. Soc. Roy. Sc. Liege, 65, 87-90.
       !!              Tartinville et al. 2001 Ocean Modelling, 3, 95-108.
+      !!              These refs are now obsolete since everything has been revised
+      !!              The ref should be Rousset et al., 2015?
       !!---------------------------------------------------------------------
-      INTEGER, INTENT(in) ::   kt    ! number of iteration
-      !
-      INTEGER  ::   ji, jj, jl           ! dummy loop indices
-      INTEGER  ::   ierr, ifvt, i1mfr, idfr           ! local integer
-      INTEGER  ::   iflt, ial , iadv , ifral, ifrdv   !   -      -
-      REAL(wp) ::   zinda, zemp, zemp_snow, zfmm      ! local scalars
-      REAL(wp) ::   zemp_snw                          !   -      -
-      REAL(wp) ::   zfcm1 , zfcm2                     !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zalb, zalbp     ! 2D/3D workspace
-      REAL(wp) ::   zzfcm1, zfscmbq ! clem: for light penetration
+      INTEGER, INTENT(in) ::   kt                                   ! number of iteration
+      !
+      INTEGER  ::   ji, jj, jl, jk                                  ! dummy loop indices
+      !
+      REAL(wp) ::   zemp                                            !  local scalars
+      REAL(wp) ::   zf_mass                                         ! Heat flux associated with mass exchange ice->ocean (W.m-2)
+      REAL(wp) ::   zfcm1                                           ! New solar flux received by the ocean
+      !
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zalb_cs, zalb_os     ! 2D/3D workspace
       !!---------------------------------------------------------------------
-      
-      IF( lk_cpl )   CALL wrk_alloc( jpi, jpj, jpl, zalb, zalbp )
-
-      !------------------------------------------!
-      !      heat flux at the ocean surface      !
-      !------------------------------------------!
+
+      ! make calls for heat fluxes before it is modified
+      IF( iom_use('qsr_oce') )   CALL iom_put( "qsr_oce" , qsr(:,:) * pfrld(:,:) )   !     solar flux at ocean surface
+      IF( iom_use('qns_oce') )   CALL iom_put( "qns_oce" , qns(:,:) * pfrld(:,:) )   ! non-solar flux at ocean surface
+      IF( iom_use('qsr_ice') )   CALL iom_put( "qsr_ice" , SUM( qsr_ice(:,:,:) * a_i_b(:,:,:), dim=3 ) ) !     solar flux at ice surface
+      IF( iom_use('qns_ice') )   CALL iom_put( "qns_ice" , SUM( qns_ice(:,:,:) * a_i_b(:,:,:), dim=3 ) ) ! non-solar flux at ice surface
+      IF( iom_use('qtr_ice') )   CALL iom_put( "qtr_ice" , SUM( ftr_ice(:,:,:) * a_i_b(:,:,:), dim=3 ) ) !     solar flux transmitted thru ice
+      IF( iom_use('qt_oce' ) )   CALL iom_put( "qt_oce"  , ( qsr(:,:) + qns(:,:) ) * pfrld(:,:) )  
+      IF( iom_use('qt_ice' ) )   CALL iom_put( "qt_ice"  , SUM( ( qns_ice(:,:,:) + qsr_ice(:,:,:) ) * a_i_b(:,:,:), dim=3 ) )
+
       ! pfrld is the lead fraction at the previous time step (actually between TRP and THD)
-      ! changed to old_frld and old ht_i
-
       DO jj = 1, jpj
          DO ji = 1, jpi
-            zinda   = 1.0 - MAX( rzero , SIGN( rone , - ( 1.0 - pfrld(ji,jj) ) ) )
-            ifvt    = zinda  *  MAX( rzero , SIGN( rone, - phicif(ji,jj) ) )  !subscripts are bad here
-            i1mfr   = 1.0 - MAX( rzero , SIGN( rone ,  - at_i(ji,jj) ) )
-            idfr    = 1.0 - MAX( rzero , SIGN( rone , ( 1.0 - at_i(ji,jj) ) - pfrld(ji,jj) ) )
-            iflt    = zinda  * (1 - i1mfr) * (1 - ifvt )
-            ial     = ifvt   * i1mfr + ( 1 - ifvt ) * idfr
-            iadv    = ( 1  - i1mfr ) * zinda
-            ifral   = ( 1  - i1mfr * ( 1 - ial ) )   
-            ifrdv   = ( 1  - ifral * ( 1 - ial ) ) * iadv 
-
-            ! switch --- 1.0 ---------------- 0.0 --------------------
-            ! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-            ! zinda   | if pfrld = 1       | if pfrld < 1            |
-            !  -> ifvt| if pfrld old_ht_i
-            ! i1mfr   | if frld = 1        | if frld  < 1            |
-            ! idfr    | if frld <= pfrld    | if frld > pfrld        |
-            ! iflt    | 
-            ! ial     |
-            ! iadv    |
-            ! ifral
-            ! ifrdv
-
-            !   computation the solar flux at ocean surface
-            IF (lk_cpl) THEN ! be carfeful: not been tested yet
-               ! original line
-               !zfcm1 = qsr_tot(ji,jj) + fstric(ji,jj) * at_i(ji,jj)
-               ! new line to include solar penetration (not tested)
-               zfcm1 = qsr_tot(ji,jj) + fstric(ji,jj) * at_i(ji,jj) / ( 1.0 - zinda + zinda * iatte(ji,jj) )
+
+            !------------------------------------------!
+            !      heat flux at the ocean surface      !
+            !------------------------------------------!
+            ! Solar heat flux reaching the ocean = zfcm1 (W.m-2) 
+            !---------------------------------------------------
+            IF( lk_cpl ) THEN 
+               !!! LIM2 version zqsr = qsr_tot(ji,jj) + ( fstric(ji,jj) - qsr_ice(ji,jj,1) ) * ( 1.0 - pfrld(ji,jj) )
+               zfcm1 = qsr_tot(ji,jj)
                DO jl = 1, jpl
-                  zfcm1 = zfcm1 - qsr_ice(ji,jj,jl) * a_i(ji,jj,jl)
+                  zfcm1 = zfcm1 + ( ftr_ice(ji,jj,jl) - qsr_ice(ji,jj,jl) ) * a_i_b(ji,jj,jl)
                END DO
             ELSE
-               zfcm1   = pfrld(ji,jj) * qsr(ji,jj)  + &
-                    &    ( 1._wp - pfrld(ji,jj) ) * fstric(ji,jj) / ( 1.0 - zinda + zinda * iatte(ji,jj) )
+               !!! LIM2 version zqsr = pfrld(ji,jj) * qsr(ji,jj)  + ( 1.  - pfrld(ji,jj) ) * fstric(ji,jj)
+               zfcm1   = pfrld(ji,jj) * qsr(ji,jj)
+               DO jl = 1, jpl
+                  zfcm1   = zfcm1 + a_i_b(ji,jj,jl) * ftr_ice(ji,jj,jl)
+               END DO
             ENDIF
-            ! fstric     Solar flux transmitted trough the ice
-            ! qsr        Net short wave heat flux on free ocean
-            ! new line
-            fscmbq(ji,jj) = ( 1.0 - pfrld(ji,jj) ) * fstric(ji,jj) / ( 1.0 - zinda + zinda * iatte(ji,jj) )
-
-            ! solar flux and fscmbq with light penetration (clem)
-            zzfcm1  = pfrld(ji,jj) * qsr(ji,jj) * oatte(ji,jj) + ( 1. - pfrld(ji,jj) ) * fstric(ji,jj)
-            zfscmbq = ( 1.0 - pfrld(ji,jj) ) * fstric(ji,jj)
-
-            !  computation the non solar heat flux at ocean surface
-            zfcm2 = - zzfcm1                                                                    & !
-               &    + iflt    * zfscmbq                                                         & ! total ablation: heat given to the ocean
-               &    + ifral   * ( ial * qcmif(ji,jj) + (1 - ial) * qldif(ji,jj) ) * r1_rdtice   &
-               &    + ifrdv   * (       qfvbq(ji,jj) +             qdtcn(ji,jj) ) * r1_rdtice   &
-               &    + fhmec(ji,jj)                                                              & ! snow melt when ridging
-               &    + fheat_mec(ji,jj)                                                          & ! ridge formation
-               &    + fheat_res(ji,jj)                                                            ! residual heat flux
-            ! qcmif   Energy needed to bring the ocean surface layer until its freezing (ok)
-            ! qldif   heat balance of the lead (or of the open ocean)
-            ! qfvbq   latent heat uptake/release after accretion/ablation
-            ! qdtcn   Energy from the turbulent oceanic heat flux heat flux coming in the lead
-
-            IF( num_sal == 2 )   zfcm2 = zfcm2 + fhbri(ji,jj)    ! add contribution due to brine drainage 
-
-            ! bottom radiative component is sent to the computation of the oceanic heat flux
-            fsbbq(ji,jj) = ( 1._wp - ( ifvt + iflt ) ) * fscmbq(ji,jj)     
-
-            ! used to compute the oceanic heat flux at the next time step
-            qsr(ji,jj) = zfcm1                                       ! solar heat flux 
-            qns(ji,jj) = zfcm2 - fdtcn(ji,jj)                        ! non solar heat flux
-            !                           ! fdtcn : turbulent oceanic heat flux
-         END DO
-      END DO
-
-      !------------------------------------------!
-      !      mass flux at the ocean surface      !
-      !------------------------------------------!
-
-!!gm   optimisation: this loop have to be merged with the previous one
-      DO jj = 1, jpj
-         DO ji = 1, jpi
+
+            ! Total heat flux reaching the ocean = hfx_out (W.m-2) 
+            !---------------------------------------------------
+            zf_mass        = hfx_thd(ji,jj) + hfx_dyn(ji,jj) + hfx_res(ji,jj) ! heat flux from snow is 0 (T=0 degC)
+            hfx_out(ji,jj) = hfx_out(ji,jj) + zf_mass + zfcm1
+
+            ! New qsr and qns used to compute the oceanic heat flux at the next time step
+            !---------------------------------------------------
+            qsr(ji,jj) = zfcm1                                      
+            qns(ji,jj) = hfx_out(ji,jj) - zfcm1              
+
+            !------------------------------------------!
+            !      mass flux at the ocean surface      !
+            !------------------------------------------!
             !  case of realistic freshwater flux (Tartinville et al., 2001) (presently ACTIVATED)
             !  ------------------------------------------------------------------------------------- 
@@ -208,27 +165,22 @@
             !                     Even if i see Ice melting as a FW and SALT flux
             !        
-
             !  computing freshwater exchanges at the ice/ocean interface
-            IF (lk_cpl) THEN 
+            IF( lk_cpl ) THEN 
                zemp = - emp_tot(ji,jj) + emp_ice(ji,jj) * ( 1. - pfrld(ji,jj) )    &   !
-                  &   - rdm_snw(ji,jj) / rdt_ice
+                  &   + wfx_snw(ji,jj)
             ELSE
-               zemp =   emp(ji,jj)     * ( 1.0 - at_i(ji,jj)          )  &   ! evaporation over oceanic fraction
-                  &   - tprecip(ji,jj) *         at_i(ji,jj)             &   ! all precipitation reach the ocean
-                  &   + sprecip(ji,jj) * ( 1. - (pfrld(ji,jj)**betas) )  &   ! except solid precip intercepted by sea-ice
-                  &   - fmmec(ji,jj)                                         ! snow falling when ridging
+               zemp =   emp(ji,jj)     *           pfrld(ji,jj)            &   ! evaporation over oceanic fraction
+                  &   - tprecip(ji,jj) * ( 1._wp - pfrld(ji,jj) )          &   ! all precipitation reach the ocean
+                  &   + sprecip(ji,jj) * ( 1._wp - pfrld(ji,jj)**betas )       ! except solid precip intercepted by sea-ice
             ENDIF
 
-            ! mass flux at the ocean/ice interface (sea ice fraction)
-            zemp_snw = rdm_snw(ji,jj) * r1_rdtice                         ! snow melting = pure water that enters the ocean
-            zfmm     = rdm_ice(ji,jj) * r1_rdtice                         ! Freezing minus melting  
-
-            fmmflx(ji,jj) = zfmm                                     ! F/M mass flux save at least for biogeochemical model
-
-            emp(ji,jj) = zemp + zemp_snw + zfmm  ! mass flux + F/M mass flux (always ice/ocean mass exchange)
+            ! mass flux from ice/ocean
+            wfx_ice(ji,jj) = wfx_bog(ji,jj) + wfx_bom(ji,jj) + wfx_sum(ji,jj) + wfx_sni(ji,jj)   &
+                           + wfx_opw(ji,jj) + wfx_dyn(ji,jj) + wfx_res(ji,jj)
+
+            ! mass flux at the ocean/ice interface
+            fmmflx(ji,jj) = - wfx_ice(ji,jj) * r1_rdtice                    ! F/M mass flux save at least for biogeochemical model
+            emp(ji,jj)    = zemp - wfx_ice(ji,jj) - wfx_snw(ji,jj)       ! mass flux + F/M mass flux (always ice/ocean mass exchange)
             
-            !  correcting brine salt fluxes   (zinda = 1  if pfrld=1 , =0 otherwise)
-            zinda        = 1.0 - MAX( rzero , SIGN( rone , - ( 1.0 - pfrld(ji,jj) ) ) )
-            sfx_bri(ji,jj) = zinda * sfx_bri(ji,jj)
          END DO
       END DO
@@ -237,18 +189,16 @@
       !      salt flux at the ocean surface      !
       !------------------------------------------!
-
-      IF( num_sal == 2 ) THEN      ! variable ice salinity: brine drainage included in the salt flux
-         sfx(:,:) = sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) + sfx_bri(:,:)
-      ELSE                         ! constant ice salinity:
-         sfx(:,:) = sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:)
-      ENDIF
-      !-----------------------------------------------!
-      !   mass of snow and ice per unit area          !
-      !-----------------------------------------------!
-      IF( nn_ice_embd /= 0 ) THEN                               ! embedded sea-ice (mass required)
-         snwice_mass_b(:,:) = snwice_mass(:,:)                  ! save mass from the previous ice time step
-         !                                                      ! new mass per unit area
+      sfx(:,:) = sfx_bog(:,:) + sfx_bom(:,:) + sfx_sum(:,:) + sfx_sni(:,:) + sfx_opw(:,:)   &
+         &     + sfx_res(:,:) + sfx_dyn(:,:) + sfx_bri(:,:)
+
+      !-------------------------------------------------------------!
+      !   mass of snow and ice per unit area for embedded sea-ice   !
+      !-------------------------------------------------------------!
+      IF( nn_ice_embd /= 0 ) THEN
+         ! save mass from the previous ice time step
+         snwice_mass_b(:,:) = snwice_mass(:,:)                  
+         ! new mass per unit area
          snwice_mass  (:,:) = tms(:,:) * ( rhosn * vt_s(:,:) + rhoic * vt_i(:,:)  ) 
-         !                                                      ! time evolution of snow+ice mass
+         ! time evolution of snow+ice mass
          snwice_fmass (:,:) = ( snwice_mass(:,:) - snwice_mass_b(:,:) ) * r1_rdtice
       ENDIF
@@ -261,11 +211,18 @@
 
       !------------------------------------------------!
-      !    Computation of snow/ice and ocean albedo    !
+      !    Snow/ice albedo (only if sent to coupler)   !
       !------------------------------------------------!
       IF( lk_cpl ) THEN          ! coupled case
-         CALL albedo_ice( t_su, ht_i, ht_s, zalbp, zalb )                  ! snow/ice albedo
-         !
-         alb_ice(:,:,:) =  0.5_wp * zalbp(:,:,:) + 0.5_wp * zalb (:,:,:)   ! Ice albedo (mean clear and overcast skys)
-      ENDIF
+
+            CALL wrk_alloc( jpi, jpj, jpl, zalb_cs, zalb_os )
+
+            CALL albedo_ice( t_su, ht_i, ht_s, zalb_cs, zalb_os )  ! cloud-sky and overcast-sky ice albedos
+
+            alb_ice(:,:,:) = ( 1. - cldf_ice ) * zalb_cs(:,:,:) + cldf_ice * zalb_os(:,:,:)
+
+            CALL wrk_dealloc( jpi, jpj, jpl, zalb_cs, zalb_os )
+
+      ENDIF
+
 
       IF(ln_ctl) THEN
@@ -275,7 +232,5 @@
          CALL prt_ctl( tab3d_1=tn_ice, clinfo1=' lim_sbc: tn_ice : ', kdim=jpl )
       ENDIF
-      !
-      IF( lk_cpl )   CALL wrk_dealloc( jpi, jpj, jpl, zalb, zalbp )
-      ! 
+
    END SUBROUTINE lim_sbc_flx
 
@@ -390,6 +345,5 @@
       ! clem modif
       IF( .NOT. ln_rstart ) THEN
-         iatte(:,:) = 1._wp
-         oatte(:,:) = 1._wp
+         fraqsr_1lev(:,:) = 1._wp
       ENDIF
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd.F90	(revision 5075)
@@ -8,5 +8,5 @@
    !!            3.0  ! 2005-11 (M. Vancoppenolle)  LIM-3 : Multi-layer thermodynamics + salinity variations
    !!             -   ! 2007-04 (M. Vancoppenolle) add lim_thd_glohec, lim_thd_con_dh and lim_thd_con_dif
-   !!            3.2  ! 2009-07 (M. Vancoppenolle, Y. Aksenov, G. Madec) bug correction in rdm_snw
+   !!            3.2  ! 2009-07 (M. Vancoppenolle, Y. Aksenov, G. Madec) bug correction in wfx_snw
    !!            3.3  ! 2010-11 (G. Madec) corrected snow melting heat (due to factor betas)
    !!            4.0  ! 2011-02 (G. Madec) dynamical allocation
@@ -22,5 +22,5 @@
    USE phycst         ! physical constants
    USE dom_oce        ! ocean space and time domain variables
-   USE oce     , ONLY :  iatte, oatte
+   USE oce     , ONLY : fraqsr_1lev 
    USE ice            ! LIM: sea-ice variables
    USE par_ice        ! LIM: sea-ice parameters
@@ -43,4 +43,5 @@
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
    USE timing         ! Timing
+   USE limcons        ! conservation tests
 
    IMPLICIT NONE
@@ -49,8 +50,4 @@
    PUBLIC   lim_thd        ! called by limstp module
    PUBLIC   lim_thd_init   ! called by iceini module
-
-   REAL(wp) ::   epsi10 = 1.e-10_wp   !
-   REAL(wp) ::   zzero  = 0._wp      !
-   REAL(wp) ::   zone   = 1._wp      !
 
    !! * Substitutions
@@ -68,5 +65,5 @@
       !!                ***  ROUTINE lim_thd  ***       
       !!  
-      !! ** Purpose : This routine manages the ice thermodynamic.
+      !! ** Purpose : This routine manages ice thermodynamics
       !!         
       !! ** Action : - Initialisation of some variables
@@ -74,42 +71,39 @@
       !!               at the ice base, snow acc.,heat budget of the leads)
       !!             - selection of the icy points and put them in an array
-      !!             - call lim_vert_ther for vert ice thermodynamic
-      !!             - back to the geographic grid
-      !!             - selection of points for lateral accretion
-      !!             - call lim_lat_acc  for the ice accretion
+      !!             - call lim_thd_dif  for vertical heat diffusion
+      !!             - call lim_thd_dh   for vertical ice growth and melt
+      !!             - call lim_thd_ent  for enthalpy remapping
+      !!             - call lim_thd_sal  for ice desalination
+      !!             - call lim_thd_temp to  retrieve temperature from ice enthalpy
       !!             - back to the geographic grid
       !!     
-      !! ** References : H. Goosse et al. 1996, Bul. Soc. Roy. Sc. Liege, 65, 87-90
+      !! ** References : 
       !!---------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt    ! number of iteration
       !!
-      INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
-      INTEGER  ::   nbpb             ! nb of icy pts for thermo. cal.
-      REAL(wp) ::   zfric_umin = 5e-03_wp    ! lower bound for the friction velocity
-      REAL(wp) ::   zfric_umax = 2e-02_wp    ! upper bound for the friction velocity
-      REAL(wp) ::   zinda, zindb, zthsnice, zfric_u     ! local scalar
-      REAL(wp) ::   zfntlat, zpareff, zareamin, zcoef   !    -         -
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zqlbsbq   ! link with lead energy budget qldif
-      REAL(wp) :: zchk_v_i, zchk_smv, zchk_fs, zchk_fw, zchk_v_i_b, zchk_smv_b, zchk_fs_b, zchk_fw_b ! Check conservation (C Rousset)
-      REAL(wp) :: zchk_vmin, zchk_amin, zchk_amax ! Check errors (C Rousset)
+      INTEGER  :: ji, jj, jk, jl   ! dummy loop indices
+      INTEGER  :: nbpb             ! nb of icy pts for thermo. cal.
+      INTEGER  :: ii, ij           ! temporary dummy loop index
+      REAL(wp) :: zfric_umin = 0._wp        ! lower bound for the friction velocity (cice value=5.e-04)
+      REAL(wp) :: zch        = 0.0057_wp    ! heat transfer coefficient
+      REAL(wp) :: zareamin 
+      REAL(wp) :: zfric_u, zqld, zqfr
+      !
+      REAL(wp) :: zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b 
+      !
+      REAL(wp), POINTER, DIMENSION(:,:) ::  zqsr, zqns
       !!-------------------------------------------------------------------
+      CALL wrk_alloc( jpi, jpj, zqsr, zqns )
+
       IF( nn_timing == 1 )  CALL timing_start('limthd')
 
-      CALL wrk_alloc( jpi, jpj, zqlbsbq )
-   
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_v_i_b = glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_smv_b = glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_fw_b  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) )
-         zchk_fs_b  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) )
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
-
-      !------------------------------------------------------------------------------!
-      ! 1) Initialization of diagnostic variables                                    !
-      !------------------------------------------------------------------------------!
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limthd', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
+
+      !------------------------------------------------------------------------!
+      ! 1) Initialization of some variables                                    !
+      !------------------------------------------------------------------------!
+      ftr_ice(:,:,:) = 0._wp  ! part of solar radiation transmitted through the ice
+
 
       !--------------------
@@ -121,10 +115,10 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
+                  !0 if no ice and 1 if yes
+                  rswitch = 1.0 - MAX(  0.0 , SIGN( 1.0 , - v_i(ji,jj,jl) + epsi10 )  )
                   !Energy of melting q(S,T) [J.m-3]
-                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) / ( area(ji,jj) * MAX( v_i(ji,jj,jl) , epsi10 ) ) * REAL( nlay_i )
-                  !0 if no ice and 1 if yes
-                  zindb = 1.0 - MAX(  0.0 , SIGN( 1.0 , - v_i(ji,jj,jl) + epsi10 )  )
-                  !convert units ! very important that this line is here
-                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * unit_fac * zindb 
+                  e_i(ji,jj,jk,jl) = rswitch * e_i(ji,jj,jk,jl) / ( area(ji,jj) * MAX( v_i(ji,jj,jl) , epsi10 ) ) * REAL( nlay_i )
+                  !convert units ! very important that this line is here        
+                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * unit_fac 
                END DO
             END DO
@@ -133,27 +127,37 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
+                  !0 if no ice and 1 if yes
+                  rswitch = 1.0 - MAX(  0.0 , SIGN( 1.0 , - v_s(ji,jj,jl) + epsi10 )  )
                   !Energy of melting q(S,T) [J.m-3]
-                  e_s(ji,jj,jk,jl) = e_s(ji,jj,jk,jl) / ( area(ji,jj) * MAX( v_s(ji,jj,jl) , epsi10 ) ) * REAL( nlay_s )
-                  !0 if no ice and 1 if yes
-                  zindb = 1.0 - MAX(  0.0 , SIGN( 1.0 , - v_s(ji,jj,jl) + epsi10 )  )
+                  e_s(ji,jj,jk,jl) = rswitch * e_s(ji,jj,jk,jl) / ( area(ji,jj) * MAX( v_s(ji,jj,jl) , epsi10 ) ) * REAL( nlay_s )
                   !convert units ! very important that this line is here
-                  e_s(ji,jj,jk,jl) = e_s(ji,jj,jk,jl) * unit_fac * zindb 
+                  e_s(ji,jj,jk,jl) = e_s(ji,jj,jk,jl) * unit_fac 
                END DO
             END DO
          END DO
       END DO
-
-      !-----------------------------------
-      ! 1.4) Compute global heat content
-      !-----------------------------------
-      qt_i_in  (:,:) = 0.e0
-      qt_s_in  (:,:) = 0.e0
-      qt_i_fin (:,:) = 0.e0
-      qt_s_fin (:,:) = 0.e0
-      sum_fluxq(:,:) = 0.e0
-      fatm     (:,:) = 0.e0
 
       ! 2) Partial computation of forcing for the thermodynamic sea ice model.      !
       !-----------------------------------------------------------------------------!
+
+      !--- Ocean solar and non solar fluxes to be used in zqld
+      IF ( .NOT. lk_cpl ) THEN   ! --- forced case, fluxes to the lead are the same as over the ocean
+         !
+         zqsr(:,:) = qsr(:,:)      ; zqns(:,:) = qns(:,:)
+         !
+      ELSE                       ! --- coupled case, fluxes to the lead are total - intercepted
+         !
+         zqsr(:,:) = qsr_tot(:,:)  ; zqns(:,:) = qns_tot(:,:)
+         !
+         DO jl = 1, jpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zqsr(ji,jj) = zqsr(ji,jj) - qsr_ice(ji,jj,jl) * a_i_b(ji,jj,jl)
+                  zqns(ji,jj) = zqns(ji,jj) - qns_ice(ji,jj,jl) * a_i_b(ji,jj,jl)
+               END DO
+            END DO
+         END DO
+         !
+      ENDIF
 
 !CDIR NOVERRCHK
@@ -161,5 +165,5 @@
 !CDIR NOVERRCHK
          DO ji = 1, jpi
-            zinda          = tms(ji,jj) * ( 1.0 - MAX( zzero , SIGN( zone , - at_i(ji,jj) + epsi10 ) ) )
+            rswitch          = tms(ji,jj) * ( 1._wp - MAX( 0._wp , SIGN( 1._wp , - at_i(ji,jj) + epsi10 ) ) ) ! 0 if no ice
             !
             !           !  solar irradiance transmission at the mixed layer bottom and used in the lead heat budget
@@ -168,39 +172,77 @@
             !           !  net downward heat flux from the ice to the ocean, expressed as a function of ocean 
             !           !  temperature and turbulent mixing (McPhee, 1992)
-            ! friction velocity
-            zfric_u        = MAX ( MIN( SQRT( ust2s(ji,jj) ) , zfric_umax ) , zfric_umin ) 
-
-            ! here the drag will depend on ice thickness and type (0.006)
-            fdtcn(ji,jj)  = zinda * rau0 * rcp * 0.006  * zfric_u * ( ( sst_m(ji,jj) + rt0 ) - t_bo(ji,jj) ) 
-            ! also category dependent
-            !           !-- Energy from the turbulent oceanic heat flux heat flux coming in the lead 
-            qdtcn(ji,jj)  = zinda * fdtcn(ji,jj) * ( 1.0 - at_i(ji,jj) ) * rdt_ice
-            !                       
-            !           !-- Lead heat budget, qldif (part 1, next one is in limthd_dh) 
-            !           !   caution: exponent betas used as more snow can fallinto leads
-            qldif(ji,jj) =  tms(ji,jj) * rdt_ice  * (                             &
-               &   pfrld(ji,jj)        * (  qsr(ji,jj) * oatte(ji,jj)             &   ! solar heat + clem modif
-               &                            + qns(ji,jj)                          &   ! non solar heat
-               &                            + fdtcn(ji,jj)                        &   ! turbulent ice-ocean heat
-               &                            + fsbbq(ji,jj) * ( 1.0 - zinda )  )   &   ! residual heat from previous step
-               & - pfrld(ji,jj)**betas * sprecip(ji,jj) * lfus                    )   ! latent heat of sprecip melting
             !
-            ! Positive heat budget is used for bottom ablation
-            zfntlat        = 1.0 - MAX( zzero , SIGN( zone ,  - qldif(ji,jj) ) )
-            != 1 if positive heat budget
-            zpareff        = 1.0 - zinda * zfntlat
-            != 0 if ice and positive heat budget and 1 if one of those two is false
-            zqlbsbq(ji,jj) = qldif(ji,jj) * ( 1.0 - zpareff ) / ( rdt_ice * MAX( at_i(ji,jj), epsi10 ) )
+
+            ! --- Energy received in the lead, zqld is defined everywhere (J.m-2) --- !
+            ! REMARK valid at least in forced mode from clem
+            ! precip is included in qns but not in qns_ice
+            IF ( lk_cpl ) THEN
+               zqld =  tms(ji,jj) * rdt_ice *  &
+                  &    (   zqsr(ji,jj) * fraqsr_1lev(ji,jj) + zqns(ji,jj)               &   ! pfrld already included in coupled mode
+                  &    + ( pfrld(ji,jj)**betas - pfrld(ji,jj) ) * sprecip(ji,jj)  *     &   ! heat content of precip
+                  &      ( cpic * ( MIN( tatm_ice(ji,jj), rt0_snow ) - rtt ) - lfus )   &
+                  &    + ( 1._wp - pfrld(ji,jj) ) * ( tprecip(ji,jj) - sprecip(ji,jj) ) * rcp * ( tatm_ice(ji,jj) - rtt ) )
+            ELSE
+               zqld =  tms(ji,jj) * rdt_ice *  &
+                  &      ( pfrld(ji,jj) * ( zqsr(ji,jj) * fraqsr_1lev(ji,jj) + zqns(ji,jj) )    &
+                  &    + ( pfrld(ji,jj)**betas - pfrld(ji,jj) ) * sprecip(ji,jj)  *             &  ! heat content of precip
+                  &      ( cpic * ( MIN( tatm_ice(ji,jj), rt0_snow ) - rtt ) - lfus )           &
+                  &    + ( 1._wp - pfrld(ji,jj) ) * ( tprecip(ji,jj) - sprecip(ji,jj) ) * rcp * ( tatm_ice(ji,jj) - rtt ) )
+            ENDIF
+
+            !-- Energy needed to bring ocean surface layer until its freezing (<0, J.m-2) --- !
+            zqfr = tms(ji,jj) * rau0 * rcp * fse3t_m(ji,jj) * ( t_bo(ji,jj) - ( sst_m(ji,jj) + rt0 ) )
+
+            !-- Energy Budget of the leads (J.m-2). Must be < 0 to form ice
+            qlead(ji,jj) = MIN( 0._wp , zqld - zqfr ) 
+
+            ! If there is ice and leads are warming, then transfer energy from the lead budget and use it for bottom melting 
+            IF( at_i(ji,jj) > epsi10 .AND. zqld > 0._wp ) THEN
+               fhld (ji,jj) = zqld * r1_rdtice / at_i(ji,jj) ! divided by at_i since this is (re)multiplied by a_i in limthd_dh.F90
+               qlead(ji,jj) = 0._wp
+            ELSE
+               fhld (ji,jj) = 0._wp
+            ENDIF
             !
-            ! Heat budget of the lead, energy transferred from ice to ocean
-            qldif  (ji,jj) = zpareff * qldif(ji,jj)
-            qdtcn  (ji,jj) = zpareff * qdtcn(ji,jj)
-            !
-            ! Energy needed to bring ocean surface layer until its freezing (qcmif, limflx)
-            qcmif  (ji,jj) =  rau0 * rcp * fse3t_m(ji,jj) * ( t_bo(ji,jj) - ( sst_m(ji,jj) + rt0 ) )
-            !
-            ! oceanic heat flux (limthd_dh)
-            fbif   (ji,jj) = zinda * (  fsbbq(ji,jj) / MAX( at_i(ji,jj) , epsi10 ) + fdtcn(ji,jj) )
-            !
+            !-- Energy from the turbulent oceanic heat flux --- !
+            !clem zfric_u        = MAX ( MIN( SQRT( ust2s(ji,jj) ) , zfric_umax ) , zfric_umin )
+            zfric_u      = MAX( SQRT( ust2s(ji,jj) ), zfric_umin ) 
+            fhtur(ji,jj) = MAX( 0._wp, rswitch * rau0 * rcp * zch  * zfric_u * ( ( sst_m(ji,jj) + rt0 ) - t_bo(ji,jj) ) ) ! W.m-2 
+            ! upper bound for fhtur: we do not want SST to drop below Tfreeze. 
+            ! So we say that the heat retrieved from the ocean (fhtur+fhld) must be < to the heat necessary to reach Tfreeze (zqfr)   
+            ! This is not a clean budget, so that should be corrected at some point
+            fhtur(ji,jj) = rswitch * MIN( fhtur(ji,jj), - fhld(ji,jj) - zqfr * r1_rdtice / MAX( at_i(ji,jj), epsi10 ) )
+
+            ! -----------------------------------------
+            ! Net heat flux on top of ice-ocean [W.m-2]
+            ! -----------------------------------------
+            !     First  step here      : heat flux at the ocean surface + precip
+            !     Second step below     : heat flux at the ice   surface (after limthd_dif) 
+            hfx_in(ji,jj) = hfx_in(ji,jj)                                                                                         & 
+               ! heat flux above the ocean
+               &    +             pfrld(ji,jj)   * ( zqns(ji,jj) + zqsr(ji,jj) )                                                  &
+               ! latent heat of precip (note that precip is included in qns but not in qns_ice)
+               &    +   ( 1._wp - pfrld(ji,jj) ) * sprecip(ji,jj) * ( cpic * ( MIN( tatm_ice(ji,jj), rt0_snow ) - rtt ) - lfus )  &
+               &    +   ( 1._wp - pfrld(ji,jj) ) * ( tprecip(ji,jj) - sprecip(ji,jj) ) * rcp * ( tatm_ice(ji,jj) - rtt )
+
+            ! -----------------------------------------------------------------------------
+            ! Net heat flux that is retroceded to the ocean or taken from the ocean [W.m-2]
+            ! -----------------------------------------------------------------------------
+            !     First  step here              :  non solar + precip - qlead - qturb
+            !     Second step in limthd_dh      :  heat remaining if total melt (zq_rema) 
+            !     Third  step in limsbc         :  heat from ice-ocean mass exchange (zf_mass) + solar
+            hfx_out(ji,jj) = hfx_out(ji,jj)                                                                                       & 
+               ! Non solar heat flux received by the ocean
+               &    +        pfrld(ji,jj) * qns(ji,jj)                                                                            &
+               ! latent heat of precip (note that precip is included in qns but not in qns_ice)
+               &    +      ( pfrld(ji,jj)**betas - pfrld(ji,jj) ) * sprecip(ji,jj)       &
+               &         * ( cpic * ( MIN( tatm_ice(ji,jj), rt0_snow ) - rtt ) - lfus )  &
+               &    +      ( 1._wp - pfrld(ji,jj) ) * ( tprecip(ji,jj) - sprecip(ji,jj) ) * rcp * ( tatm_ice(ji,jj) - rtt )       &
+               ! heat flux taken from the ocean where there is open water ice formation
+               &    -      qlead(ji,jj) * r1_rdtice                                                                               &
+               ! heat flux taken from the ocean during bottom growth/melt (fhld should be 0 while bott growth)
+               &    -      at_i(ji,jj) * fhtur(ji,jj)                                                                             &
+               &    -      at_i(ji,jj) *  fhld(ji,jj)
+
          END DO
       END DO
@@ -234,4 +276,5 @@
                DO jj = mj0(jjindx), mj1(jjindx)
                   jiindex_1d = (jj - 1) * jpi + ji
+                  WRITE(numout,*) ' lim_thd : Category no : ', jl 
                END DO
             END DO
@@ -250,19 +293,19 @@
             !-------------------------
 
-            CALL tab_2d_1d( nbpb, at_i_b     (1:nbpb), at_i            , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, a_i_b      (1:nbpb), a_i(:,:,jl)     , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, ht_i_b     (1:nbpb), ht_i(:,:,jl)    , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, ht_s_b     (1:nbpb), ht_s(:,:,jl)    , jpi, jpj, npb(1:nbpb) )
-
-            CALL tab_2d_1d( nbpb, t_su_b     (1:nbpb), t_su(:,:,jl)    , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, sm_i_b     (1:nbpb), sm_i(:,:,jl)    , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, at_i_1d     (1:nbpb), at_i            , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, a_i_1d      (1:nbpb), a_i(:,:,jl)     , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, ht_i_1d     (1:nbpb), ht_i(:,:,jl)    , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, ht_s_1d     (1:nbpb), ht_s(:,:,jl)    , jpi, jpj, npb(1:nbpb) )
+
+            CALL tab_2d_1d( nbpb, t_su_1d     (1:nbpb), t_su(:,:,jl)    , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, sm_i_1d     (1:nbpb), sm_i(:,:,jl)    , jpi, jpj, npb(1:nbpb) )
             DO jk = 1, nlay_s
-               CALL tab_2d_1d( nbpb, t_s_b(1:nbpb,jk), t_s(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
-               CALL tab_2d_1d( nbpb, q_s_b(1:nbpb,jk), e_s(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
+               CALL tab_2d_1d( nbpb, t_s_1d(1:nbpb,jk), t_s(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
+               CALL tab_2d_1d( nbpb, q_s_1d(1:nbpb,jk), e_s(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
             END DO
             DO jk = 1, nlay_i
-               CALL tab_2d_1d( nbpb, t_i_b(1:nbpb,jk), t_i(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
-               CALL tab_2d_1d( nbpb, q_i_b(1:nbpb,jk), e_i(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
-               CALL tab_2d_1d( nbpb, s_i_b(1:nbpb,jk), s_i(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
+               CALL tab_2d_1d( nbpb, t_i_1d(1:nbpb,jk), t_i(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
+               CALL tab_2d_1d( nbpb, q_i_1d(1:nbpb,jk), e_i(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
+               CALL tab_2d_1d( nbpb, s_i_1d(1:nbpb,jk), s_i(:,:,jk,jl)  , jpi, jpj, npb(1:nbpb) )
             END DO
 
@@ -271,58 +314,73 @@
             CALL tab_2d_1d( nbpb, fr1_i0_1d  (1:nbpb), fr1_i0          , jpi, jpj, npb(1:nbpb) )
             CALL tab_2d_1d( nbpb, fr2_i0_1d  (1:nbpb), fr2_i0          , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, qnsr_ice_1d(1:nbpb), qns_ice(:,:,jl) , jpi, jpj, npb(1:nbpb) )
-#if ! defined key_coupled
-            CALL tab_2d_1d( nbpb, qla_ice_1d (1:nbpb), qla_ice(:,:,jl) , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, dqla_ice_1d(1:nbpb), dqla_ice(:,:,jl), jpi, jpj, npb(1:nbpb) )
-#endif
+            CALL tab_2d_1d( nbpb, qns_ice_1d (1:nbpb), qns_ice(:,:,jl) , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, ftr_ice_1d (1:nbpb), ftr_ice(:,:,jl) , jpi, jpj, npb(1:nbpb) )
+            IF( .NOT. lk_cpl ) THEN
+               CALL tab_2d_1d( nbpb, qla_ice_1d (1:nbpb), qla_ice(:,:,jl) , jpi, jpj, npb(1:nbpb) )
+               CALL tab_2d_1d( nbpb, dqla_ice_1d(1:nbpb), dqla_ice(:,:,jl), jpi, jpj, npb(1:nbpb) )
+            ENDIF
             CALL tab_2d_1d( nbpb, dqns_ice_1d(1:nbpb), dqns_ice(:,:,jl), jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, t_bo_b     (1:nbpb), t_bo            , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, t_bo_1d     (1:nbpb), t_bo            , jpi, jpj, npb(1:nbpb) )
             CALL tab_2d_1d( nbpb, sprecip_1d (1:nbpb), sprecip         , jpi, jpj, npb(1:nbpb) ) 
-            CALL tab_2d_1d( nbpb, fbif_1d    (1:nbpb), fbif            , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, qldif_1d   (1:nbpb), qldif           , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, rdm_ice_1d (1:nbpb), rdm_ice         , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, rdm_snw_1d (1:nbpb), rdm_snw         , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, dmgwi_1d   (1:nbpb), dmgwi           , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, qlbbq_1d   (1:nbpb), zqlbsbq         , jpi, jpj, npb(1:nbpb) )
-
-            CALL tab_2d_1d( nbpb, sfx_thd_1d (1:nbpb), sfx_thd         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, fhtur_1d   (1:nbpb), fhtur           , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, qlead_1d   (1:nbpb), qlead           , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, fhld_1d    (1:nbpb), fhld            , jpi, jpj, npb(1:nbpb) )
+
+            CALL tab_2d_1d( nbpb, wfx_snw_1d (1:nbpb), wfx_snw         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, wfx_sub_1d (1:nbpb), wfx_sub         , jpi, jpj, npb(1:nbpb) )
+
+            CALL tab_2d_1d( nbpb, wfx_bog_1d (1:nbpb), wfx_bog         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, wfx_bom_1d (1:nbpb), wfx_bom         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, wfx_sum_1d (1:nbpb), wfx_sum         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, wfx_sni_1d (1:nbpb), wfx_sni         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, wfx_res_1d (1:nbpb), wfx_res         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, wfx_spr_1d (1:nbpb), wfx_spr         , jpi, jpj, npb(1:nbpb) )
+
+            CALL tab_2d_1d( nbpb, sfx_bog_1d (1:nbpb), sfx_bog         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, sfx_bom_1d (1:nbpb), sfx_bom         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, sfx_sum_1d (1:nbpb), sfx_sum         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, sfx_sni_1d (1:nbpb), sfx_sni         , jpi, jpj, npb(1:nbpb) )
             CALL tab_2d_1d( nbpb, sfx_bri_1d (1:nbpb), sfx_bri         , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, fhbri_1d   (1:nbpb), fhbri           , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, fstbif_1d  (1:nbpb), fstric          , jpi, jpj, npb(1:nbpb) )
-            CALL tab_2d_1d( nbpb, qfvbq_1d   (1:nbpb), qfvbq           , jpi, jpj, npb(1:nbpb) )
-
-            CALL tab_2d_1d( nbpb, iatte_1d   (1:nbpb), iatte           , jpi, jpj, npb(1:nbpb) ) ! clem modif
-            CALL tab_2d_1d( nbpb, oatte_1d   (1:nbpb), oatte           , jpi, jpj, npb(1:nbpb) ) ! clem modif
+            CALL tab_2d_1d( nbpb, sfx_res_1d (1:nbpb), sfx_res         , jpi, jpj, npb(1:nbpb) )
+
+            CALL tab_2d_1d( nbpb, hfx_thd_1d (1:nbpb), hfx_thd         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_spr_1d (1:nbpb), hfx_spr         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_sum_1d (1:nbpb), hfx_sum         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_bom_1d (1:nbpb), hfx_bom         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_bog_1d (1:nbpb), hfx_bog         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_dif_1d (1:nbpb), hfx_dif         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_opw_1d (1:nbpb), hfx_opw         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_snw_1d (1:nbpb), hfx_snw         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_sub_1d (1:nbpb), hfx_sub         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_err_1d (1:nbpb), hfx_err         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_res_1d (1:nbpb), hfx_res         , jpi, jpj, npb(1:nbpb) )
+            CALL tab_2d_1d( nbpb, hfx_err_rem_1d (1:nbpb), hfx_err_rem , jpi, jpj, npb(1:nbpb) )
+
             !--------------------------------
             ! 4.3) Thermodynamic processes
             !--------------------------------
 
-            IF( con_i .AND. jiindex_1d > 0 )   CALL lim_thd_enmelt( 1, nbpb )   ! computes sea ice energy of melting
-            IF( con_i .AND. jiindex_1d > 0 )   CALL lim_thd_glohec( qt_i_in, qt_s_in, q_i_layer_in, 1, nbpb, jl )
-
-            !                                 !---------------------------------!
-            CALL lim_thd_dif( 1, nbpb, jl )   ! Ice/Snow Temperature profile    !
-            !                                 !---------------------------------!
-
-            CALL lim_thd_enmelt( 1, nbpb )    ! computes sea ice energy of melting compulsory for limthd_dh
-
-            IF( con_i .AND. jiindex_1d > 0 )   CALL lim_thd_glohec ( qt_i_fin, qt_s_fin, q_i_layer_fin, 1, nbpb, jl ) 
-            IF( con_i .AND. jiindex_1d > 0 )   CALL lim_thd_con_dif( 1 , nbpb , jl )
-
-            !                                 !---------------------------------!
-            CALL lim_thd_dh( 1, nbpb, jl )    ! Ice/Snow thickness              ! 
-            !                                 !---------------------------------!
-
-            !                                 !---------------------------------!
-            CALL lim_thd_ent( 1, nbpb, jl )   ! Ice/Snow enthalpy remapping     !
-            !                                 !---------------------------------!
-
-            !                                 !---------------------------------!
-            CALL lim_thd_sal( 1, nbpb )       ! Ice salinity computation        !
-            !                                 !---------------------------------!
-
-            !           CALL lim_thd_enmelt(1,nbpb)   ! computes sea ice energy of melting
-            IF( con_i .AND. jiindex_1d > 0 )   CALL lim_thd_glohec( qt_i_fin, qt_s_fin, q_i_layer_fin, 1, nbpb, jl ) 
-            IF( con_i .AND. jiindex_1d > 0 )   CALL lim_thd_con_dh ( 1 , nbpb , jl )
+            !---------------------------------!
+            ! Ice/Snow Temperature profile    !
+            !---------------------------------!
+            CALL lim_thd_dif( 1, nbpb )
+
+            !---------------------------------!
+            ! Ice/Snow thicnkess              !
+            !---------------------------------!
+            CALL lim_thd_dh( 1, nbpb )    
+
+            ! --- Ice enthalpy remapping --- !
+            CALL lim_thd_ent( 1, nbpb, q_i_1d(1:nbpb,:) ) 
+                                            
+            !---------------------------------!
+            ! --- Ice salinity --- !
+            !---------------------------------!
+            CALL lim_thd_sal( 1, nbpb )    
+
+            !---------------------------------!
+            ! --- temperature update --- !
+            !---------------------------------!
+            CALL lim_thd_temp( 1, nbpb )
 
             !--------------------------------
@@ -330,45 +388,53 @@
             !--------------------------------
 
-               CALL tab_1d_2d( nbpb, at_i          , npb, at_i_b    (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, ht_i(:,:,jl)  , npb, ht_i_b    (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, ht_s(:,:,jl)  , npb, ht_s_b    (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, a_i (:,:,jl)  , npb, a_i_b     (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, t_su(:,:,jl)  , npb, t_su_b    (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, sm_i(:,:,jl)  , npb, sm_i_b    (1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, at_i          , npb, at_i_1d    (1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, ht_i(:,:,jl)  , npb, ht_i_1d    (1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, ht_s(:,:,jl)  , npb, ht_s_1d    (1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, a_i (:,:,jl)  , npb, a_i_1d     (1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, t_su(:,:,jl)  , npb, t_su_1d    (1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, sm_i(:,:,jl)  , npb, sm_i_1d    (1:nbpb)   , jpi, jpj )
             DO jk = 1, nlay_s
-               CALL tab_1d_2d( nbpb, t_s(:,:,jk,jl), npb, t_s_b     (1:nbpb,jk), jpi, jpj)
-               CALL tab_1d_2d( nbpb, e_s(:,:,jk,jl), npb, q_s_b     (1:nbpb,jk), jpi, jpj)
+               CALL tab_1d_2d( nbpb, t_s(:,:,jk,jl), npb, t_s_1d     (1:nbpb,jk), jpi, jpj)
+               CALL tab_1d_2d( nbpb, e_s(:,:,jk,jl), npb, q_s_1d     (1:nbpb,jk), jpi, jpj)
             END DO
             DO jk = 1, nlay_i
-               CALL tab_1d_2d( nbpb, t_i(:,:,jk,jl), npb, t_i_b     (1:nbpb,jk), jpi, jpj)
-               CALL tab_1d_2d( nbpb, e_i(:,:,jk,jl), npb, q_i_b     (1:nbpb,jk), jpi, jpj)
-               CALL tab_1d_2d( nbpb, s_i(:,:,jk,jl), npb, s_i_b     (1:nbpb,jk), jpi, jpj)
-            END DO
-               CALL tab_1d_2d( nbpb, fstric        , npb, fstbif_1d (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, qldif         , npb, qldif_1d  (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, qfvbq         , npb, qfvbq_1d  (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, rdm_ice       , npb, rdm_ice_1d(1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, rdm_snw       , npb, rdm_snw_1d(1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, dmgwi         , npb, dmgwi_1d  (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, rdvosif       , npb, dvsbq_1d  (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, rdvobif       , npb, dvbbq_1d  (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, fdvolif       , npb, dvlbq_1d  (1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, rdvonif       , npb, dvnbq_1d  (1:nbpb)   , jpi, jpj ) 
-               CALL tab_1d_2d( nbpb, sfx_thd       , npb, sfx_thd_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, t_i(:,:,jk,jl), npb, t_i_1d     (1:nbpb,jk), jpi, jpj)
+               CALL tab_1d_2d( nbpb, e_i(:,:,jk,jl), npb, q_i_1d     (1:nbpb,jk), jpi, jpj)
+               CALL tab_1d_2d( nbpb, s_i(:,:,jk,jl), npb, s_i_1d     (1:nbpb,jk), jpi, jpj)
+            END DO
+               CALL tab_1d_2d( nbpb, qlead         , npb, qlead_1d  (1:nbpb)   , jpi, jpj )
+
+               CALL tab_1d_2d( nbpb, wfx_snw       , npb, wfx_snw_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, wfx_sub       , npb, wfx_sub_1d(1:nbpb)   , jpi, jpj )
+
+               CALL tab_1d_2d( nbpb, wfx_bog       , npb, wfx_bog_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, wfx_bom       , npb, wfx_bom_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, wfx_sum       , npb, wfx_sum_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, wfx_sni       , npb, wfx_sni_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, wfx_res       , npb, wfx_res_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, wfx_spr       , npb, wfx_spr_1d(1:nbpb)   , jpi, jpj )
+
+               CALL tab_1d_2d( nbpb, sfx_bog       , npb, sfx_bog_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, sfx_bom       , npb, sfx_bom_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, sfx_sum       , npb, sfx_sum_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, sfx_sni       , npb, sfx_sni_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, sfx_res       , npb, sfx_res_1d(1:nbpb)   , jpi, jpj )
+               CALL tab_1d_2d( nbpb, sfx_bri       , npb, sfx_bri_1d(1:nbpb)   , jpi, jpj )
+
+              CALL tab_1d_2d( nbpb, hfx_thd       , npb, hfx_thd_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_spr       , npb, hfx_spr_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_sum       , npb, hfx_sum_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_bom       , npb, hfx_bom_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_bog       , npb, hfx_bog_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_dif       , npb, hfx_dif_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_opw       , npb, hfx_opw_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_snw       , npb, hfx_snw_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_sub       , npb, hfx_sub_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_err       , npb, hfx_err_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_res       , npb, hfx_res_1d(1:nbpb)   , jpi, jpj )
+              CALL tab_1d_2d( nbpb, hfx_err_rem   , npb, hfx_err_rem_1d(1:nbpb)   , jpi, jpj )
             !
-            IF( num_sal == 2 ) THEN
-               CALL tab_1d_2d( nbpb, sfx_bri       , npb, sfx_bri_1d(1:nbpb)   , jpi, jpj )
-               CALL tab_1d_2d( nbpb, fhbri         , npb, fhbri_1d  (1:nbpb)   , jpi, jpj )
-            ENDIF
-            !
-            !+++++       temporary stuff for a dummy version
-            CALL tab_1d_2d( nbpb, dh_i_surf2D, npb, dh_i_surf(1:nbpb)      , jpi, jpj )
-            CALL tab_1d_2d( nbpb, dh_i_bott2D, npb, dh_i_bott(1:nbpb)      , jpi, jpj )
-            CALL tab_1d_2d( nbpb, fsup2D     , npb, fsup     (1:nbpb)      , jpi, jpj )
-            CALL tab_1d_2d( nbpb, focea2D    , npb, focea    (1:nbpb)      , jpi, jpj )
-            CALL tab_1d_2d( nbpb, s_i_newice , npb, s_i_new  (1:nbpb)      , jpi, jpj )
-            CALL tab_1d_2d( nbpb, izero(:,:,jl) , npb, i0    (1:nbpb)      , jpi, jpj )
-            CALL tab_1d_2d( nbpb, qns_ice(:,:,jl), npb, qnsr_ice_1d(1:nbpb), jpi, jpj)
-            !+++++
+              CALL tab_1d_2d( nbpb, qns_ice(:,:,jl), npb, qns_ice_1d(1:nbpb) , jpi, jpj)
+              CALL tab_1d_2d( nbpb, ftr_ice(:,:,jl), npb, ftr_ice_1d(1:nbpb) , jpi, jpj )
             !
             IF( lk_mpp )   CALL mpp_comm_free( ncomm_ice ) !RB necessary ??
@@ -384,9 +450,8 @@
       ! 5.1) Ice heat content              
       !------------------------
-      ! Enthalpies are global variables we have to readjust the units (heat content in 10^9 Joules)
-      zcoef = 1._wp / ( unit_fac * REAL( nlay_i ) )
+      ! Enthalpies are global variables we have to readjust the units (heat content in Joules)
       DO jl = 1, jpl
          DO jk = 1, nlay_i
-            e_i(:,:,jk,jl) = e_i(:,:,jk,jl) * area(:,:) * a_i(:,:,jl) * ht_i(:,:,jl) * zcoef
+            e_i(:,:,jk,jl) = e_i(:,:,jk,jl) * area(:,:) * a_i(:,:,jl) * ht_i(:,:,jl) / ( unit_fac * REAL( nlay_i ) )
          END DO
       END DO
@@ -395,9 +460,8 @@
       ! 5.2) Snow heat content              
       !------------------------
-      ! Enthalpies are global variables we have to readjust the units (heat content in 10^9 Joules)
-      zcoef = 1._wp / ( unit_fac * REAL( nlay_s ) )
+      ! Enthalpies are global variables we have to readjust the units (heat content in Joules)
       DO jl = 1, jpl
          DO jk = 1, nlay_s
-            e_s(:,:,jk,jl) = e_s(:,:,jk,jl) * area(:,:) * a_i(:,:,jl) * ht_s(:,:,jl) * zcoef
+            e_s(:,:,jk,jl) = e_s(:,:,jk,jl) * area(:,:) * a_i(:,:,jl) * ht_s(:,:,jl) / ( unit_fac * REAL( nlay_s ) )
          END DO
       END DO
@@ -411,9 +475,4 @@
       ! 5.4) Diagnostic thermodynamic growth rates
       !--------------------------------------------
-!clem@useless      d_v_i_thd(:,:,:) = v_i      (:,:,:) - old_v_i(:,:,:)    ! ice volumes 
-!clem@mv-to-itd    dv_dt_thd(:,:,:) = d_v_i_thd(:,:,:) * r1_rdtice * rday
-
-      IF( con_i .AND. jiindex_1d > 0 )   fbif(:,:) = fbif(:,:) + zqlbsbq(:,:)
-
       IF(ln_ctl) THEN            ! Control print
          CALL prt_ctl_info(' ')
@@ -448,334 +507,20 @@
       ENDIF
       !
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_fs  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) ) - zchk_fs_b
-         zchk_fw  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) ) - zchk_fw_b
- 
-         zchk_v_i = ( glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_v_i_b - ( zchk_fw / rhoic ) ) * r1_rdtice
-         zchk_smv = ( glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_smv_b ) * r1_rdtice + ( zchk_fs / rhoic )
-
-         zchk_vmin = glob_min(v_i)
-         zchk_amax = glob_max(SUM(a_i,dim=3))
-         zchk_amin = glob_min(a_i)
-       
-         IF(lwp) THEN
-            IF ( ABS( zchk_v_i   ) >  1.e-5 ) WRITE(numout,*) 'violation volume [m3/day]     (limthd) = ',(zchk_v_i * rday)
-            IF ( ABS( zchk_smv   ) >  1.e-4 ) WRITE(numout,*) 'violation saline [psu*m3/day] (limthd) = ',(zchk_smv * rday)
-            IF ( zchk_vmin <  0.            ) WRITE(numout,*) 'violation v_i<0  [mm]         (limthd) = ',(zchk_vmin * 1.e-3)
-            IF ( zchk_amax >  amax+epsi10   ) WRITE(numout,*) 'violation a_i>amax            (limthd) = ',zchk_amax
-            IF ( zchk_amin <  0.            ) WRITE(numout,*) 'violation a_i<0               (limthd) = ',zchk_amin
-         ENDIF
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
-      !
-      CALL wrk_dealloc( jpi, jpj, zqlbsbq )
+      !
+      CALL wrk_dealloc( jpi, jpj, zqsr, zqns )
+
+      !
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(1, 'limthd', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
       !
       IF( nn_timing == 1 )  CALL timing_stop('limthd')
-   END SUBROUTINE lim_thd
-
-
-   SUBROUTINE lim_thd_glohec( eti, ets, etilayer, kideb, kiut, jl )
+
+   END SUBROUTINE lim_thd 
+
+   SUBROUTINE lim_thd_temp( kideb, kiut )
       !!-----------------------------------------------------------------------
-      !!                   ***  ROUTINE lim_thd_glohec *** 
+      !!                   ***  ROUTINE lim_thd_temp *** 
       !!                 
-      !! ** Purpose :  Compute total heat content for each category
-      !!               Works with 1d vectors only
-      !!-----------------------------------------------------------------------
-      INTEGER , INTENT(in   )                         ::   kideb, kiut   ! bounds for the spatial loop
-      INTEGER , INTENT(in   )                         ::   jl            ! category number
-      REAL(wp), INTENT(  out), DIMENSION (jpij,jpl  ) ::   eti, ets      ! vertically-summed heat content for ice & snow
-      REAL(wp), INTENT(  out), DIMENSION (jpij,jkmax) ::   etilayer      ! heat content for ice layers
-      !!
-      INTEGER  ::   ji,jk   ! loop indices
-      !!-----------------------------------------------------------------------
-      eti(:,:) = 0._wp
-      ets(:,:) = 0._wp
-      !
-      DO jk = 1, nlay_i                ! total q over all layers, ice [J.m-2]
-         DO ji = kideb, kiut
-            etilayer(ji,jk) = q_i_b(ji,jk) * ht_i_b(ji) / REAL( nlay_i )
-            eti     (ji,jl) = eti(ji,jl) + etilayer(ji,jk) 
-         END DO
-      END DO
-      DO ji = kideb, kiut              ! total q over all layers, snow [J.m-2]
-         ets(ji,jl) = ets(ji,jl) + q_s_b(ji,1) * ht_s_b(ji) / REAL( nlay_s )
-      END DO
-      !
-      WRITE(numout,*) ' lim_thd_glohec '
-      WRITE(numout,*) ' qt_i_in : ', eti(jiindex_1d,jl) * r1_rdtice
-      WRITE(numout,*) ' qt_s_in : ', ets(jiindex_1d,jl) * r1_rdtice
-      WRITE(numout,*) ' qt_in   : ', ( eti(jiindex_1d,jl) + ets(jiindex_1d,jl) ) * r1_rdtice
-      !
-   END SUBROUTINE lim_thd_glohec
-
-
-   SUBROUTINE lim_thd_con_dif( kideb, kiut, jl )
-      !!-----------------------------------------------------------------------
-      !!                   ***  ROUTINE lim_thd_con_dif *** 
-      !!                 
-      !! ** Purpose :   Test energy conservation after heat diffusion
-      !!-------------------------------------------------------------------
-      INTEGER , INTENT(in   ) ::   kideb, kiut   ! bounds for the spatial loop
-      INTEGER , INTENT(in   ) ::   jl            ! category number
-
-      INTEGER  ::   ji, jk         ! loop indices
-      INTEGER  ::   ii, ij
-      INTEGER  ::   numce          ! number of points for which conservation is violated
-      REAL(wp) ::   meance         ! mean conservation error
-      REAL(wp) ::   max_cons_err, max_surf_err
-      !!---------------------------------------------------------------------
-
-      max_cons_err =  1.0_wp          ! maximum tolerated conservation error
-      max_surf_err =  0.001_wp        ! maximum tolerated surface error
-
-      !--------------------------
-      ! Increment of energy
-      !--------------------------
-      ! global
-      DO ji = kideb, kiut
-         dq_i(ji,jl) = qt_i_fin(ji,jl) - qt_i_in(ji,jl) + qt_s_fin(ji,jl) - qt_s_in(ji,jl)
-      END DO
-      ! layer by layer
-      dq_i_layer(:,:) = q_i_layer_fin(:,:) - q_i_layer_in(:,:)
-
-      !----------------------------------------
-      ! Atmospheric heat flux, ice heat budget
-      !----------------------------------------
-      DO ji = kideb, kiut
-         ii = MOD( npb(ji) - 1 , jpi ) + 1
-         ij =    ( npb(ji) - 1 ) / jpi + 1
-         fatm     (ji,jl) = qnsr_ice_1d(ji) + ( 1._wp - i0(ji) ) * qsr_ice_1d(ji)
-         sum_fluxq(ji,jl) = fc_su(ji) - fc_bo_i(ji) + qsr_ice_1d(ji) * i0(ji) - fstroc(ii,ij,jl)
-      END DO
-
-      !--------------------
-      ! Conservation error
-      !--------------------
-      DO ji = kideb, kiut
-         cons_error(ji,jl) = ABS( dq_i(ji,jl) * r1_rdtice + sum_fluxq(ji,jl) )
-      END DO
-
-      numce  = 0
-      meance = 0._wp
-      DO ji = kideb, kiut
-         IF ( cons_error(ji,jl) .GT. max_cons_err ) THEN
-            numce = numce + 1
-            meance = meance + cons_error(ji,jl)
-         ENDIF
-      END DO
-      IF( numce > 0 )   meance = meance / numce
-
-      WRITE(numout,*) ' Maximum tolerated conservation error : ', max_cons_err
-      WRITE(numout,*) ' After lim_thd_dif, category : ', jl
-      WRITE(numout,*) ' Mean conservation error on big error points ', meance, numit
-      WRITE(numout,*) ' Number of points where there is a cons err gt than c.e. : ', numce, numit
-
-      !-------------------------------------------------------
-      ! Surface error due to imbalance between Fatm and Fcsu
-      !-------------------------------------------------------
-      numce  = 0
-      meance = 0._wp
-
-      DO ji = kideb, kiut
-         surf_error(ji,jl) = ABS ( fatm(ji,jl) - fc_su(ji) )
-         IF( ( t_su_b(ji) .LT. rtt ) .AND. ( surf_error(ji,jl) .GT. max_surf_err ) ) THEN
-            numce = numce + 1 
-            meance = meance + surf_error(ji,jl)
-         ENDIF
-      ENDDO
-      IF( numce > 0 )   meance = meance / numce
-
-      WRITE(numout,*) ' Maximum tolerated surface error : ', max_surf_err
-      WRITE(numout,*) ' After lim_thd_dif, category : ', jl
-      WRITE(numout,*) ' Mean surface error on big error points ', meance, numit
-      WRITE(numout,*) ' Number of points where there is a surf err gt than surf_err : ', numce, numit
-
-      WRITE(numout,*) ' fc_su      : ', fc_su(jiindex_1d)
-      WRITE(numout,*) ' fatm       : ', fatm(jiindex_1d,jl)
-      WRITE(numout,*) ' t_su       : ', t_su_b(jiindex_1d)
-
-      !---------------------------------------
-      ! Write ice state in case of big errors
-      !---------------------------------------
-      DO ji = kideb, kiut
-         IF ( ( ( t_su_b(ji) .LT. rtt ) .AND. ( surf_error(ji,jl) .GT. max_surf_err ) ) .OR. &
-            ( cons_error(ji,jl) .GT. max_cons_err  ) ) THEN
-            ii                 = MOD( npb(ji) - 1, jpi ) + 1
-            ij                 = ( npb(ji) - 1 ) / jpi + 1
-            !
-            WRITE(numout,*) ' alerte 1     '
-            WRITE(numout,*) ' Untolerated conservation / surface error after '
-            WRITE(numout,*) ' heat diffusion in the ice '
-            WRITE(numout,*) ' Category   : ', jl
-            WRITE(numout,*) ' ii , ij  : ', ii, ij
-            WRITE(numout,*) ' lat, lon   : ', gphit(ii,ij), glamt(ii,ij)
-            WRITE(numout,*) ' cons_error : ', cons_error(ji,jl)
-            WRITE(numout,*) ' surf_error : ', surf_error(ji,jl)
-            WRITE(numout,*) ' dq_i       : ', - dq_i(ji,jl) * r1_rdtice
-            WRITE(numout,*) ' Fdt        : ', sum_fluxq(ji,jl)
-            WRITE(numout,*)
-            !        WRITE(numout,*) ' qt_i_in   : ', qt_i_in(ji,jl)
-            !        WRITE(numout,*) ' qt_s_in   : ', qt_s_in(ji,jl)
-            !        WRITE(numout,*) ' qt_i_fin  : ', qt_i_fin(ji,jl)
-            !        WRITE(numout,*) ' qt_s_fin  : ', qt_s_fin(ji,jl)
-            !        WRITE(numout,*) ' qt        : ', qt_i_fin(ji,jl) + qt_s_fin(ji,jl)
-            WRITE(numout,*) ' ht_i       : ', ht_i_b(ji)
-            WRITE(numout,*) ' ht_s       : ', ht_s_b(ji)
-            WRITE(numout,*) ' t_su       : ', t_su_b(ji)
-            WRITE(numout,*) ' t_s        : ', t_s_b(ji,1)
-            WRITE(numout,*) ' t_i        : ', t_i_b(ji,1:nlay_i)
-            WRITE(numout,*) ' t_bo       : ', t_bo_b(ji)
-            WRITE(numout,*) ' q_i        : ', q_i_b(ji,1:nlay_i)
-            WRITE(numout,*) ' s_i        : ', s_i_b(ji,1:nlay_i)
-            WRITE(numout,*) ' tmelts     : ', rtt - tmut*s_i_b(ji,1:nlay_i)
-            WRITE(numout,*)
-            WRITE(numout,*) ' Fluxes '
-            WRITE(numout,*) ' ~~~~~~ '
-            WRITE(numout,*) ' fatm       : ', fatm(ji,jl)
-            WRITE(numout,*) ' fc_su      : ', fc_su    (ji)
-            WRITE(numout,*) ' fstr_inice : ', qsr_ice_1d(ji)*i0(ji)
-            WRITE(numout,*) ' fc_bo      : ', - fc_bo_i  (ji)
-            WRITE(numout,*) ' foc        : ', fbif_1d(ji)
-            WRITE(numout,*) ' fstroc     : ', fstroc   (ii,ij,jl)
-            WRITE(numout,*) ' i0         : ', i0(ji)
-            WRITE(numout,*) ' qsr_ice    : ', (1.0-i0(ji))*qsr_ice_1d(ji)
-            WRITE(numout,*) ' qns_ice    : ', qnsr_ice_1d(ji)
-            WRITE(numout,*) ' Conduction fluxes : '
-            WRITE(numout,*) ' fc_s      : ', fc_s(ji,0:nlay_s)
-            WRITE(numout,*) ' fc_i      : ', fc_i(ji,0:nlay_i)
-            WRITE(numout,*)
-            WRITE(numout,*) ' Layer by layer ... '
-            WRITE(numout,*) ' dq_snow : ', ( qt_s_fin(ji,jl) - qt_s_in(ji,jl) ) * r1_rdtice
-            WRITE(numout,*) ' dfc_snow  : ', fc_s(ji,1) - fc_s(ji,0)
-            DO jk = 1, nlay_i
-               WRITE(numout,*) ' layer  : ', jk
-               WRITE(numout,*) ' dq_ice : ', dq_i_layer(ji,jk) * r1_rdtice  
-               WRITE(numout,*) ' radab  : ', radab(ji,jk)
-               WRITE(numout,*) ' dfc_i  : ', fc_i(ji,jk) - fc_i(ji,jk-1)
-               WRITE(numout,*) ' tot f  : ', fc_i(ji,jk) - fc_i(ji,jk-1) - radab(ji,jk)
-            END DO
-
-         ENDIF
-         !
-      END DO
-      !
-   END SUBROUTINE lim_thd_con_dif
-
-
-   SUBROUTINE lim_thd_con_dh( kideb, kiut, jl )
-      !!-----------------------------------------------------------------------
-      !!                   ***  ROUTINE lim_thd_con_dh  *** 
-      !!                 
-      !! ** Purpose :   Test energy conservation after enthalpy redistr.
-      !!-----------------------------------------------------------------------
-      INTEGER, INTENT(in) ::   kideb, kiut   ! bounds for the spatial loop
-      INTEGER, INTENT(in) ::   jl            ! category number
-      !
-      INTEGER  ::   ji                ! loop indices
-      INTEGER  ::   ii, ij, numce         ! local integers
-      REAL(wp) ::   meance, max_cons_err    !local scalar
-      !!---------------------------------------------------------------------
-
-      max_cons_err = 1._wp
-
-      !--------------------------
-      ! Increment of energy
-      !--------------------------
-      DO ji = kideb, kiut
-         dq_i(ji,jl) = qt_i_fin(ji,jl) - qt_i_in(ji,jl) + qt_s_fin(ji,jl) - qt_s_in(ji,jl)   ! global
-      END DO
-      dq_i_layer(:,:)    = q_i_layer_fin(:,:) - q_i_layer_in(:,:)                            ! layer by layer
-
-      !----------------------------------------
-      ! Atmospheric heat flux, ice heat budget
-      !----------------------------------------
-      DO ji = kideb, kiut
-         ii = MOD( npb(ji) - 1 , jpi ) + 1
-         ij =    ( npb(ji) - 1 ) / jpi + 1
-
-         fatm      (ji,jl) = qnsr_ice_1d(ji) + qsr_ice_1d(ji)                       ! total heat flux
-         sum_fluxq (ji,jl) = fatm(ji,jl) + fbif_1d(ji) - ftotal_fin(ji) - fstroc(ii,ij,jl) 
-         cons_error(ji,jl) = ABS( dq_i(ji,jl) * r1_rdtice + sum_fluxq(ji,jl) )
-      END DO
-
-      !--------------------
-      ! Conservation error
-      !--------------------
-      DO ji = kideb, kiut
-         cons_error(ji,jl) = ABS( dq_i(ji,jl) * r1_rdtice + sum_fluxq(ji,jl) )
-      END DO
-
-      numce = 0
-      meance = 0._wp
-      DO ji = kideb, kiut
-         IF( cons_error(ji,jl) .GT. max_cons_err ) THEN
-            numce = numce + 1
-            meance = meance + cons_error(ji,jl)
-         ENDIF
-      ENDDO
-      IF(numce > 0 ) meance = meance / numce
-
-      WRITE(numout,*) ' Error report - Category : ', jl
-      WRITE(numout,*) ' ~~~~~~~~~~~~ '
-      WRITE(numout,*) ' Maximum tolerated conservation error : ', max_cons_err
-      WRITE(numout,*) ' After lim_thd_ent, category : ', jl
-      WRITE(numout,*) ' Mean conservation error on big error points ', meance, numit
-      WRITE(numout,*) ' Number of points where there is a cons err gt than 0.1 W/m2 : ', numce, numit
-
-      !---------------------------------------
-      ! Write ice state in case of big errors
-      !---------------------------------------
-      DO ji = kideb, kiut
-         IF ( cons_error(ji,jl) .GT. max_cons_err  ) THEN
-            ii = MOD( npb(ji) - 1, jpi ) + 1
-            ij =    ( npb(ji) - 1 ) / jpi + 1
-            !
-            WRITE(numout,*) ' alerte 1 - category : ', jl
-            WRITE(numout,*) ' Untolerated conservation error after limthd_ent '
-            WRITE(numout,*) ' ii , ij  : ', ii, ij
-            WRITE(numout,*) ' lat, lon   : ', gphit(ii,ij), glamt(ii,ij)
-            WRITE(numout,*) ' * '
-            WRITE(numout,*) ' Ftotal     : ', sum_fluxq(ji,jl)
-            WRITE(numout,*) ' dq_t       : ', - dq_i(ji,jl) * r1_rdtice
-            WRITE(numout,*) ' dq_i       : ', - ( qt_i_fin(ji,jl) - qt_i_in(ji,jl) ) * r1_rdtice
-            WRITE(numout,*) ' dq_s       : ', - ( qt_s_fin(ji,jl) - qt_s_in(ji,jl) ) * r1_rdtice
-            WRITE(numout,*) ' cons_error : ', cons_error(ji,jl)
-            WRITE(numout,*) ' * '
-            WRITE(numout,*) ' Fluxes        --- : '
-            WRITE(numout,*) ' fatm       : ', fatm(ji,jl)
-            WRITE(numout,*) ' foce       : ', fbif_1d(ji)
-            WRITE(numout,*) ' fres       : ', ftotal_fin(ji)
-            WRITE(numout,*) ' fhbri      : ', fhbricat(ii,ij,jl)
-            WRITE(numout,*) ' * '
-            WRITE(numout,*) ' Heat contents --- : '
-            WRITE(numout,*) ' qt_s_in    : ', qt_s_in(ji,jl) * r1_rdtice
-            WRITE(numout,*) ' qt_i_in    : ', qt_i_in(ji,jl) * r1_rdtice
-            WRITE(numout,*) ' qt_in      : ', ( qt_i_in(ji,jl) + qt_s_in(ji,jl) ) * r1_rdtice
-            WRITE(numout,*) ' qt_s_fin   : ', qt_s_fin(ji,jl) * r1_rdtice
-            WRITE(numout,*) ' qt_i_fin   : ', qt_i_fin(ji,jl) * r1_rdtice
-            WRITE(numout,*) ' qt_fin     : ', ( qt_i_fin(ji,jl) + qt_s_fin(ji,jl) ) * r1_rdtice
-            WRITE(numout,*) ' * '
-            WRITE(numout,*) ' Ice variables --- : '
-            WRITE(numout,*) ' ht_i       : ', ht_i_b(ji)
-            WRITE(numout,*) ' ht_s       : ', ht_s_b(ji)
-            WRITE(numout,*) ' dh_s_tot  : ', dh_s_tot(ji)
-            WRITE(numout,*) ' dh_snowice: ', dh_snowice(ji)
-            WRITE(numout,*) ' dh_i_surf : ', dh_i_surf(ji)
-            WRITE(numout,*) ' dh_i_bott : ', dh_i_bott(ji)
-         ENDIF
-         !
-      END DO
-      !
-   END SUBROUTINE lim_thd_con_dh
-
-
-   SUBROUTINE lim_thd_enmelt( kideb, kiut )
-      !!-----------------------------------------------------------------------
-      !!                   ***  ROUTINE lim_thd_enmelt *** 
-      !!                 
-      !! ** Purpose :   Computes sea ice energy of melting q_i (J.m-3)
+      !! ** Purpose :   Computes sea ice temperature (Kelvin) from enthalpy
       !!
       !! ** Method  :   Formula (Bitz and Lipscomb, 1999)
@@ -784,23 +529,24 @@
       !!
       INTEGER  ::   ji, jk   ! dummy loop indices
-      REAL(wp) ::   ztmelts  ! local scalar 
+      REAL(wp) ::   ztmelts, zaaa, zbbb, zccc, zdiscrim  ! local scalar 
       !!-------------------------------------------------------------------
-      !
-      DO jk = 1, nlay_i             ! Sea ice energy of melting
+      ! Recover ice temperature
+      DO jk = 1, nlay_i
          DO ji = kideb, kiut
-            ztmelts      =  - tmut  * s_i_b(ji,jk) + rtt 
-            q_i_b(ji,jk) =    rhoic * ( cpic * ( ztmelts - t_i_b(ji,jk) )                                 &
-               &                      + lfus * ( 1.0 - (ztmelts-rtt) / MIN( t_i_b(ji,jk)-rtt, -epsi10 ) )   &
-               &                      - rcp  * ( ztmelts-rtt  )  ) 
-         END DO
-      END DO
-      DO jk = 1, nlay_s             ! Snow energy of melting
-         DO ji = kideb, kiut
-            q_s_b(ji,jk) = rhosn * ( cpic * ( rtt - t_s_b(ji,jk) ) + lfus )
-         END DO
-      END DO
-      !
-   END SUBROUTINE lim_thd_enmelt
-
+            ztmelts       =  -tmut * s_i_1d(ji,jk) + rtt
+            ! Conversion q(S,T) -> T (second order equation)
+            zaaa          =  cpic
+            zbbb          =  ( rcp - cpic ) * ( ztmelts - rtt ) + q_i_1d(ji,jk) / rhoic - lfus
+            zccc          =  lfus * ( ztmelts - rtt )
+            zdiscrim      =  SQRT( MAX( zbbb * zbbb - 4._wp * zaaa * zccc, 0._wp ) )
+            t_i_1d(ji,jk) =  rtt - ( zbbb + zdiscrim ) / ( 2._wp * zaaa )
+            
+            ! mask temperature
+            rswitch       =  1._wp - MAX( 0._wp , SIGN( 1._wp , - ht_i_1d(ji) ) ) 
+            t_i_1d(ji,jk) =  rswitch * t_i_1d(ji,jk) + ( 1._wp - rswitch ) * rtt
+         END DO 
+      END DO 
+
+   END SUBROUTINE lim_thd_temp
 
    SUBROUTINE lim_thd_init
@@ -818,7 +564,5 @@
       INTEGER  ::   ios                 ! Local integer output status for namelist read
       NAMELIST/namicethd/ hmelt , hiccrit, fraz_swi, maxfrazb, vfrazb, Cfrazb,   &
-         &                hicmin, hiclim,                                        &
-         &                sbeta  , parlat, hakspl, hibspl, exld,                 &
-         &                hakdif, hnzst  , thth  , parsub, alphs, betas,         & 
+         &                hiclim, hnzst, parsub, betas,                          & 
          &                kappa_i, nconv_i_thd, maxer_i_thd, thcon_i_swi
       !!-------------------------------------------------------------------
@@ -838,4 +582,6 @@
 902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namicethd in configuration namelist', lwp )
       IF(lwm) WRITE ( numoni, namicethd )
+
+      IF( lk_cpl .AND. parsub /= 0.0 )   CALL ctl_stop( 'In coupled mode, use parsub = 0. or send dqla' )
       !
       IF(lwp) THEN                          ! control print
@@ -843,22 +589,13 @@
          WRITE(numout,*)'   Namelist of ice parameters for ice thermodynamic computation '
          WRITE(numout,*)'      maximum melting at the bottom                           hmelt        = ', hmelt
-         WRITE(numout,*)'      ice thick. for lateral accretion in NH (SH)             hiccrit(1/2) = ', hiccrit
+         WRITE(numout,*)'      ice thick. for lateral accretion                        hiccrit      = ', hiccrit
          WRITE(numout,*)'      Frazil ice thickness as a function of wind or not       fraz_swi     = ', fraz_swi
          WRITE(numout,*)'      Maximum proportion of frazil ice collecting at bottom   maxfrazb     = ', maxfrazb
          WRITE(numout,*)'      Thresold relative drift speed for collection of frazil  vfrazb       = ', vfrazb
          WRITE(numout,*)'      Squeezing coefficient for collection of frazil          Cfrazb       = ', Cfrazb
-         WRITE(numout,*)'      ice thick. corr. to max. energy stored in brine pocket  hicmin       = ', hicmin  
          WRITE(numout,*)'      minimum ice thickness                                   hiclim       = ', hiclim 
          WRITE(numout,*)'      numerical carac. of the scheme for diffusion in ice '
-         WRITE(numout,*)'      Cranck-Nicholson (=0.5), implicit (=1), explicit (=0)   sbeta        = ', sbeta
-         WRITE(numout,*)'      percentage of energy used for lateral ablation          parlat       = ', parlat
-         WRITE(numout,*)'      slope of distr. for Hakkinen-Mellor lateral melting     hakspl       = ', hakspl  
-         WRITE(numout,*)'      slope of distribution for Hibler lateral melting        hibspl       = ', hibspl
-         WRITE(numout,*)'      exponent for leads-closure rate                         exld         = ', exld
-         WRITE(numout,*)'      coefficient for diffusions of ice and snow              hakdif       = ', hakdif
-         WRITE(numout,*)'      threshold thick. for comp. of eq. thermal conductivity  zhth         = ', thth 
          WRITE(numout,*)'      thickness of the surf. layer in temp. computation       hnzst        = ', hnzst
          WRITE(numout,*)'      switch for snow sublimation  (=1) or not (=0)           parsub       = ', parsub  
-         WRITE(numout,*)'      coefficient for snow density when snow ice formation    alphs        = ', alphs
          WRITE(numout,*)'      coefficient for ice-lead partition of snowfall          betas        = ', betas
          WRITE(numout,*)'      extinction radiation parameter in sea ice (1.0)         kappa_i      = ', kappa_i
@@ -866,8 +603,6 @@
          WRITE(numout,*)'      maximal err. on T for heat diffusion computation        maxer_i_thd  = ', maxer_i_thd
          WRITE(numout,*)'      switch for comp. of thermal conductivity in the ice     thcon_i_swi  = ', thcon_i_swi
+         WRITE(numout,*)'      check heat conservation in the ice/snow                 con_i        = ', con_i
       ENDIF
-      !
-      rcdsn = hakdif * rcdsn 
-      rcdic = hakdif * rcdic
       !
    END SUBROUTINE lim_thd_init
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_dh.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_dh.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_dh.F90	(revision 5075)
@@ -6,5 +6,5 @@
    !! History :  LIM  ! 2003-05 (M. Vancoppenolle) Original code in 1D
    !!                 ! 2005-06 (M. Vancoppenolle) 3D version 
-   !!            3.2  ! 2009-07 (M. Vancoppenolle, Y. Aksenov, G. Madec) bug correction in rdm_snw & rdm_ice
+   !!            3.2  ! 2009-07 (M. Vancoppenolle, Y. Aksenov, G. Madec) bug correction in wfx_snw & wfx_ice
    !!            3.4  ! 2011-02 (G. Madec) dynamical allocation
    !!            3.5  ! 2012-10 (G. Madec & co) salt flux + bug fixes 
@@ -26,15 +26,9 @@
    USE wrk_nemo       ! work arrays
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
-
+   
    IMPLICIT NONE
    PRIVATE
 
    PUBLIC   lim_thd_dh   ! called by lim_thd
-
-   REAL(wp) ::   epsi20 = 1.e-20   ! constant values
-   REAL(wp) ::   epsi10 = 1.e-10   !
-   REAL(wp) ::   epsi13 = 1.e-13   !
-   REAL(wp) ::   zzero  = 0._wp    !
-   REAL(wp) ::   zone   = 1._wp    !
 
    !!----------------------------------------------------------------------
@@ -45,5 +39,5 @@
 CONTAINS
 
-   SUBROUTINE lim_thd_dh( kideb, kiut, jl )
+   SUBROUTINE lim_thd_dh( kideb, kiut )
       !!------------------------------------------------------------------
       !!                ***  ROUTINE lim_thd_dh  ***
@@ -70,36 +64,35 @@
       !!------------------------------------------------------------------
       INTEGER , INTENT(in) ::   kideb, kiut   ! Start/End point on which the  the computation is applied
-      INTEGER , INTENT(in) ::   jl            ! Thickness cateogry number
       !! 
       INTEGER  ::   ji , jk        ! dummy loop indices
       INTEGER  ::   ii, ij         ! 2D corresponding indices to ji
-      INTEGER  ::   isnow          ! switch for presence (1) or absence (0) of snow
-      INTEGER  ::   isnowic        ! snow ice formation not
-      INTEGER  ::   i_ice_switch   ! ice thickness above a certain treshold or not
       INTEGER  ::   iter
 
-      REAL(wp) ::   zzfmass_i, zihgnew                     ! local scalar
-      REAL(wp) ::   zzfmass_s, zhsnew, ztmelts             ! local scalar
-      REAL(wp) ::   zhn, zdhcf, zdhbf, zhni, zhnfi, zihg   !
-      REAL(wp) ::   zdhnm, zhnnew, zhisn, zihic, zzc       !
+      REAL(wp) ::   ztmelts             ! local scalar
+      REAL(wp) ::   zdh, zfdum  !
       REAL(wp) ::   zfracs       ! fractionation coefficient for bottom salt entrapment
       REAL(wp) ::   zcoeff       ! dummy argument for snowfall partitioning over ice and leads
-      REAL(wp) ::   zsm_snowice  ! snow-ice salinity
+      REAL(wp) ::   zs_snic  ! snow-ice salinity
       REAL(wp) ::   zswi1        ! switch for computation of bottom salinity
       REAL(wp) ::   zswi12       ! switch for computation of bottom salinity
       REAL(wp) ::   zswi2        ! switch for computation of bottom salinity
       REAL(wp) ::   zgrr         ! bottom growth rate
-      REAL(wp) ::   ztform       ! bottom formation temperature
-      !
-      REAL(wp), POINTER, DIMENSION(:) ::   zh_i        ! ice layer thickness
+      REAL(wp) ::   zt_i_new     ! bottom formation temperature
+
+      REAL(wp) ::   zQm          ! enthalpy exchanged with the ocean (J/m2), >0 towards the ocean
+      REAL(wp) ::   zEi          ! specific enthalpy of sea ice (J/kg)
+      REAL(wp) ::   zEw          ! specific enthalpy of exchanged water (J/kg)
+      REAL(wp) ::   zdE          ! specific enthalpy difference (J/kg)
+      REAL(wp) ::   zfmdt        ! exchange mass flux x time step (J/m2), >0 towards the ocean
+      REAL(wp) ::   zsstK        ! SST in Kelvin
+
       REAL(wp), POINTER, DIMENSION(:) ::   zh_s        ! snow layer thickness
-      REAL(wp), POINTER, DIMENSION(:) ::   ztfs        ! melting point
-      REAL(wp), POINTER, DIMENSION(:) ::   zhsold      ! old snow thickness
-      REAL(wp), POINTER, DIMENSION(:) ::   zqprec      ! energy of fallen snow
-      REAL(wp), POINTER, DIMENSION(:) ::   zqfont_su   ! incoming, remaining surface energy
-      REAL(wp), POINTER, DIMENSION(:) ::   zqfont_bo   ! incoming, bottom energy
-      REAL(wp), POINTER, DIMENSION(:) ::   z_f_surf    ! surface heat for ablation
-      REAL(wp), POINTER, DIMENSION(:) ::   zhgnew      ! new ice thickness
-      REAL(wp), POINTER, DIMENSION(:) ::   zfmass_i    ! 
+      REAL(wp), POINTER, DIMENSION(:) ::   zqprec      ! energy of fallen snow                       (J.m-3)
+      REAL(wp), POINTER, DIMENSION(:) ::   zq_su       ! heat for surface ablation                   (J.m-2)
+      REAL(wp), POINTER, DIMENSION(:) ::   zq_bo       ! heat for bottom ablation                    (J.m-2)
+      REAL(wp), POINTER, DIMENSION(:) ::   zq_1cat     ! corrected heat in case 1-cat and hmelt>15cm (J.m-2)
+      REAL(wp), POINTER, DIMENSION(:) ::   zq_rema     ! remaining heat at the end of the routine    (J.m-2)
+      REAL(wp), POINTER, DIMENSION(:) ::   zf_tt     ! Heat budget to determine melting or freezing(W.m-2)
+      INTEGER , POINTER, DIMENSION(:) ::   icount      ! number of layers vanished by melting 
 
       REAL(wp), POINTER, DIMENSION(:) ::   zdh_s_mel   ! snow melt 
@@ -108,87 +101,107 @@
 
       REAL(wp), POINTER, DIMENSION(:,:) ::   zdeltah
-
-      ! Pathological cases
-      REAL(wp), POINTER, DIMENSION(:) ::   zfdt_init   ! total incoming heat for ice melt
-      REAL(wp), POINTER, DIMENSION(:) ::   zfdt_final  ! total remaing heat for ice melt
-      REAL(wp), POINTER, DIMENSION(:) ::   zqt_i       ! total ice heat content
-      REAL(wp), POINTER, DIMENSION(:) ::   zqt_s       ! total snow heat content
-      REAL(wp), POINTER, DIMENSION(:) ::   zqt_dummy   ! dummy heat content
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zqt_i_lay   ! total ice heat content
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zh_i      ! ice layer thickness
+
+      REAL(wp), POINTER, DIMENSION(:) ::   zqh_i       ! total ice heat content  (J.m-2)
+      REAL(wp), POINTER, DIMENSION(:) ::   zqh_s       ! total snow heat content (J.m-2)
+      REAL(wp), POINTER, DIMENSION(:) ::   zq_s        ! total snow enthalpy     (J.m-3)
 
       ! mass and salt flux (clem)
-      REAL(wp) :: zdvres, zdvsur, zdvbot
-      REAL(wp), POINTER, DIMENSION(:) ::   zviold, zvsold   ! old ice volume...
+      REAL(wp) :: zdvres, zswitch_sal
 
       ! Heat conservation 
-      INTEGER  ::   num_iter_max, numce_dh
-      REAL(wp) ::   meance_dh
-      REAL(wp) ::   zinda 
-      REAL(wp), POINTER, DIMENSION(:) ::   zinnermelt
-      REAL(wp), POINTER, DIMENSION(:) ::   zfbase, zdq_i
+      INTEGER  ::   num_iter_max
+
       !!------------------------------------------------------------------
 
-      CALL wrk_alloc( jpij, zh_i, zh_s, ztfs, zhsold, zqprec, zqfont_su, zqfont_bo, z_f_surf, zhgnew, zfmass_i )
-      CALL wrk_alloc( jpij, zdh_s_mel, zdh_s_pre, zdh_s_sub, zfdt_init, zfdt_final, zqt_i, zqt_s, zqt_dummy )
-      CALL wrk_alloc( jpij, zinnermelt, zfbase, zdq_i )
-      CALL wrk_alloc( jpij, jkmax, zdeltah, zqt_i_lay )
-
-      CALL wrk_alloc( jpij, zviold, zvsold ) ! clem
+      ! Discriminate between varying salinity (num_sal=2) and prescribed cases (other values)
+      SELECT CASE( num_sal )                       ! varying salinity or not
+         CASE( 1, 3, 4 ) ;   zswitch_sal = 0       ! prescribed salinity profile
+         CASE( 2 )       ;   zswitch_sal = 1       ! varying salinity profile
+      END SELECT
+
+      CALL wrk_alloc( jpij, zh_s, zqprec, zq_su, zq_bo, zf_tt, zq_1cat, zq_rema )
+      CALL wrk_alloc( jpij, zdh_s_mel, zdh_s_pre, zdh_s_sub, zqh_i, zqh_s, zq_s )
+      CALL wrk_alloc( jpij, nlay_i+1, zdeltah, zh_i )
+      CALL wrk_alloc( jpij, icount )
       
-      ftotal_fin(:) = 0._wp
-      zfdt_init (:) = 0._wp
-      zfdt_final(:) = 0._wp
-
-      dh_i_surf (:) = 0._wp
-      dh_i_bott (:) = 0._wp
-      dh_snowice(:) = 0._wp
-
-      DO ji = kideb, kiut
-         old_ht_i_b(ji) = ht_i_b(ji)
-         old_ht_s_b(ji) = ht_s_b(ji)
-         zviold(ji) = a_i_b(ji) * ht_i_b(ji) ! clem
-         zvsold(ji) = a_i_b(ji) * ht_s_b(ji) ! clem
-      END DO
+      dh_i_surf  (:) = 0._wp ; dh_i_bott  (:) = 0._wp ; dh_snowice(:) = 0._wp
+      dsm_i_se_1d(:) = 0._wp ; dsm_i_si_1d(:) = 0._wp   
+ 
+      zqprec (:) = 0._wp ; zq_su  (:) = 0._wp ; zq_bo  (:) = 0._wp ; zf_tt  (:) = 0._wp
+      zq_1cat(:) = 0._wp ; zq_rema(:) = 0._wp
+
+      zh_s     (:) = 0._wp       
+      zdh_s_pre(:) = 0._wp
+      zdh_s_mel(:) = 0._wp
+      zdh_s_sub(:) = 0._wp
+      zqh_s    (:) = 0._wp      
+      zqh_i    (:) = 0._wp   
+
+      zh_i      (:,:) = 0._wp       
+      zdeltah   (:,:) = 0._wp       
+      icount    (:)   = 0
+
+      ! initialize layer thicknesses and enthalpies
+      h_i_old (:,0:nlay_i+1) = 0._wp
+      qh_i_old(:,0:nlay_i+1) = 0._wp
+      DO jk = 1, nlay_i
+         DO ji = kideb, kiut
+            h_i_old (ji,jk) = ht_i_1d(ji) / REAL( nlay_i )
+            qh_i_old(ji,jk) = q_i_1d(ji,jk) * h_i_old(ji,jk)
+         ENDDO
+      ENDDO
       !
       !------------------------------------------------------------------------------!
-      !  1) Calculate available heat for surface ablation                            !
+      !  1) Calculate available heat for surface and bottom ablation                 !
       !------------------------------------------------------------------------------!
       !
       DO ji = kideb, kiut
-         isnow         = INT(  1.0 - MAX(  0.0 , SIGN( 1.0 , - ht_s_b(ji) )  )  )
-         ztfs     (ji) = isnow * rtt + ( 1.0 - isnow ) * rtt
-         z_f_surf (ji) = qnsr_ice_1d(ji) + ( 1.0 - i0(ji) ) * qsr_ice_1d(ji) - fc_su(ji)
-         z_f_surf (ji) = MAX(  zzero , z_f_surf(ji)  ) * MAX(  zzero , SIGN( zone , t_su_b(ji) - ztfs(ji) )  )
-         zfdt_init(ji) = ( z_f_surf(ji) + MAX( fbif_1d(ji) + qlbbq_1d(ji) + fc_bo_i(ji),0.0 ) ) * rdt_ice
-      END DO ! ji
-
-      zqfont_su  (:) = 0._wp
-      zqfont_bo  (:) = 0._wp
-      dsm_i_se_1d(:) = 0._wp     
-      dsm_i_si_1d(:) = 0._wp   
+         rswitch       = 1._wp - MAX(  0._wp , SIGN( 1._wp , - ht_s_1d(ji) ) )
+         ztmelts       = rswitch * rtt + ( 1._wp - rswitch ) * rtt
+
+         zfdum      = qns_ice_1d(ji) + ( 1._wp - i0(ji) ) * qsr_ice_1d(ji) - fc_su(ji) 
+         zf_tt(ji)  = fc_bo_i(ji) + fhtur_1d(ji) + fhld_1d(ji) 
+
+         zq_su (ji) = MAX( 0._wp, zfdum     * rdt_ice ) * MAX( 0._wp , SIGN( 1._wp, t_su_1d(ji) - ztmelts ) )
+         zq_bo (ji) = MAX( 0._wp, zf_tt(ji) * rdt_ice )
+      END DO
+
       !
       !------------------------------------------------------------------------------!
-      !  2) Computing layer thicknesses and  snow and sea-ice enthalpies.            !
+      ! If snow temperature is above freezing point, then snow melts 
+      ! (should not happen but sometimes it does)
       !------------------------------------------------------------------------------!
-      !
-      DO ji = kideb, kiut     ! Layer thickness
-         zh_i(ji) = ht_i_b(ji) / REAL( nlay_i )
-         zh_s(ji) = ht_s_b(ji) / REAL( nlay_s )
-      END DO
-      !
-      zqt_s(:) = 0._wp        ! Total enthalpy of the snow
+      DO ji = kideb, kiut
+         IF( t_s_1d(ji,1) > rtt ) THEN !!! Internal melting
+            ! Contribution to heat flux to the ocean [W.m-2], < 0  
+            hfx_res_1d(ji) = hfx_res_1d(ji) + q_s_1d(ji,1) * ht_s_1d(ji) * a_i_1d(ji) * r1_rdtice
+            ! Contribution to mass flux
+            wfx_snw_1d(ji) = wfx_snw_1d(ji) + rhosn * ht_s_1d(ji) * a_i_1d(ji) * r1_rdtice
+            ! updates
+            ht_s_1d(ji)   = 0._wp
+            q_s_1d (ji,1) = 0._wp
+            t_s_1d (ji,1) = rtt
+         END IF
+      END DO
+
+      !------------------------------------------------------------!
+      !  2) Computing layer thicknesses and enthalpies.            !
+      !------------------------------------------------------------!
+      !
+      DO ji = kideb, kiut     
+         zh_s(ji) = ht_s_1d(ji) / REAL( nlay_s )
+      END DO
+      !
       DO jk = 1, nlay_s
          DO ji = kideb, kiut
-            zqt_s(ji) =  zqt_s(ji) + q_s_b(ji,jk) * ht_s_b(ji) / REAL( nlay_s )
+            zqh_s(ji) =  zqh_s(ji) + q_s_1d(ji,jk) * zh_s(ji)
          END DO
       END DO
       !
-      zqt_i(:) = 0._wp        ! Total enthalpy of the ice
       DO jk = 1, nlay_i
          DO ji = kideb, kiut
-            zzc = q_i_b(ji,jk) * ht_i_b(ji) / REAL( nlay_i )
-            zqt_i(ji)        =  zqt_i(ji) + zzc
-            zqt_i_lay(ji,jk) =              zzc
+            zh_i(ji,jk) = ht_i_1d(ji) / REAL( nlay_i )
+            zqh_i(ji)   = zqh_i(ji) + q_i_1d(ji,jk) * zh_i(ji,jk)
          END DO
       END DO
@@ -212,149 +225,166 @@
       ! Martin Vancoppenolle, December 2006
 
-      ! Snow fall
-      DO ji = kideb, kiut
-         zcoeff = ( 1.0 - ( 1.0 - at_i_b(ji) )**betas ) / at_i_b(ji) 
+      DO ji = kideb, kiut
+         !-----------
+         ! Snow fall
+         !-----------
+         ! thickness change
+         zcoeff = ( 1._wp - ( 1._wp - at_i_1d(ji) )**betas ) / at_i_1d(ji) 
          zdh_s_pre(ji) = zcoeff * sprecip_1d(ji) * rdt_ice / rhosn
-      END DO
-      zdh_s_mel(:) =  0._wp
-
-      ! Melt of fallen snow
-      DO ji = kideb, kiut
-         ! tatm_ice is now in K
-         zqprec   (ji)   =  rhosn * ( cpic * ( rtt - tatm_ice_1d(ji) ) + lfus )  
-         zqfont_su(ji)   =  z_f_surf(ji) * rdt_ice
-         zdeltah  (ji,1) =  MIN( 0.e0 , - zqfont_su(ji) / MAX( zqprec(ji) , epsi13 ) )
-         zqfont_su(ji)   =  MAX( 0.e0 , - zdh_s_pre(ji) - zdeltah(ji,1)              ) * zqprec(ji)
-         zdeltah  (ji,1) =  MAX( - zdh_s_pre(ji) , zdeltah(ji,1) )
-         zdh_s_mel(ji)   =  zdh_s_mel(ji) + zdeltah(ji,1)
-         ! heat conservation
-         qt_s_in(ji,jl)  =  qt_s_in(ji,jl) + zqprec(ji) * zdh_s_pre(ji)
-         zqt_s  (ji)     =  zqt_s  (ji)    + zqprec(ji) * zdh_s_pre(ji)
-         zqt_s  (ji)     =  MAX( zqt_s(ji) - zqfont_su(ji) , 0.e0 ) 
-      END DO
-
-
-      ! Snow melt due to surface heat imbalance
+         ! enthalpy of the precip (>0, J.m-3) (tatm_ice is now in K)
+         zqprec   (ji) = rhosn * ( cpic * ( rtt - MIN( tatm_ice_1d(ji), rt0_snow) ) + lfus )   
+         IF( sprecip_1d(ji) == 0._wp ) zqprec(ji) = 0._wp
+         ! heat flux from snow precip (>0, W.m-2)
+         hfx_spr_1d(ji) = hfx_spr_1d(ji) + zdh_s_pre(ji) * a_i_1d(ji) * zqprec(ji) * r1_rdtice
+         ! mass flux, <0
+         wfx_spr_1d(ji) = wfx_spr_1d(ji) - rhosn * a_i_1d(ji) * zdh_s_pre(ji) * r1_rdtice
+         ! update thickness
+         ht_s_1d    (ji) = MAX( 0._wp , ht_s_1d(ji) + zdh_s_pre(ji) )
+
+         !---------------------
+         ! Melt of falling snow
+         !---------------------
+         ! thickness change
+         IF( zdh_s_pre(ji) > 0._wp ) THEN
+         rswitch        = 1._wp - MAX( 0._wp , SIGN( 1._wp , - zqprec(ji) + epsi20 ) )
+         zdh_s_mel (ji) = - rswitch * zq_su(ji) / MAX( zqprec(ji) , epsi20 )
+         zdh_s_mel (ji) = MAX( - zdh_s_pre(ji), zdh_s_mel(ji) ) ! bound melting 
+         ! heat used to melt snow (W.m-2, >0)
+         hfx_snw_1d(ji) = hfx_snw_1d(ji) - zdh_s_mel(ji) * a_i_1d(ji) * zqprec(ji) * r1_rdtice
+         ! snow melting only = water into the ocean (then without snow precip), >0
+         wfx_snw_1d(ji) = wfx_snw_1d(ji) - rhosn * a_i_1d(ji) * zdh_s_mel(ji) * r1_rdtice
+         
+         ! updates available heat + thickness
+         zq_su (ji) = MAX( 0._wp , zq_su (ji) + zdh_s_mel(ji) * zqprec(ji) )      
+         ht_s_1d(ji) = MAX( 0._wp , ht_s_1d(ji) + zdh_s_mel(ji) )
+         zh_s  (ji) = ht_s_1d(ji) / REAL( nlay_s )
+
+         ENDIF
+      END DO
+
+      ! If heat still available, then melt more snow
+      zdeltah(:,:) = 0._wp ! important
       DO jk = 1, nlay_s
          DO ji = kideb, kiut
-            zdeltah  (ji,jk) = - zqfont_su(ji) / q_s_b(ji,jk)
-            zqfont_su(ji)    =  MAX( 0.0 , - zh_s(ji) - zdeltah(ji,jk) ) * q_s_b(ji,jk) 
-            zdeltah  (ji,jk) =  MAX( zdeltah(ji,jk) , - zh_s(ji) )
-            zdh_s_mel(ji)    =  zdh_s_mel(ji) + zdeltah(ji,jk)        ! resulting melt of snow    
+            ! thickness change
+            rswitch          = 1._wp - MAX( 0._wp, SIGN( 1._wp, - ht_s_1d(ji) ) ) 
+            rswitch          = rswitch * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, - q_s_1d(ji,jk) + epsi20 ) ) ) 
+            zdeltah  (ji,jk) = - rswitch * zq_su(ji) / MAX( q_s_1d(ji,jk), epsi20 )
+            zdeltah  (ji,jk) = MAX( zdeltah(ji,jk) , - zh_s(ji) ) ! bound melting
+            zdh_s_mel(ji)    = zdh_s_mel(ji) + zdeltah(ji,jk)    
+            ! heat used to melt snow(W.m-2, >0)
+            hfx_snw_1d(ji)   = hfx_snw_1d(ji) - zdeltah(ji,jk) * a_i_1d(ji) * q_s_1d(ji,jk) * r1_rdtice 
+            ! snow melting only = water into the ocean (then without snow precip)
+            wfx_snw_1d(ji)   = wfx_snw_1d(ji) - rhosn * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice
+
+            ! updates available heat + thickness
+            zq_su (ji) = MAX( 0._wp , zq_su (ji) + zdeltah(ji,jk) * q_s_1d(ji,jk) )
+            ht_s_1d(ji) = MAX( 0._wp , ht_s_1d(ji) + zdeltah(ji,jk) )
+
          END DO
       END DO
 
-      ! Apply snow melt to snow depth
-      DO ji = kideb, kiut
-         dh_s_tot(ji)   =  zdh_s_mel(ji) + zdh_s_pre(ji)
-         ! Old and new snow depths
-         zhsold(ji)     =  ht_s_b(ji)
-         zhsnew         =  ht_s_b(ji) + dh_s_tot(ji)
-         ! If snow is still present zhn = 1, else zhn = 0
-         zhn            =  1.0 - MAX(  zzero , SIGN( zone , - zhsnew )  )
-         ht_s_b(ji)     =  MAX( zzero , zhsnew )
-         ! we recompute dh_s_tot (clem) 
-         dh_s_tot (ji)  =  ht_s_b(ji) - zhsold(ji)
-         ! Volume and mass variations of snow
-         dvsbq_1d  (ji) =  a_i_b(ji) * ( ht_s_b(ji) - zhsold(ji) - zdh_s_pre(ji) )
-         dvsbq_1d  (ji) =  MIN( zzero, dvsbq_1d(ji) )
-         !clem rdm_snw_1d(ji) =  rdm_snw_1d(ji) + rhosn * dvsbq_1d(ji)
+      !----------------------
+      ! 3.2 Snow sublimation 
+      !----------------------
+      ! qla_ice is always >=0 (upwards), heat goes to the atmosphere, therefore snow sublimates
+      ! clem comment: not counted in mass exchange in limsbc since this is an exchange with atm. (not ocean)
+      ! clem comment: ice should also sublimate
+      IF( lk_cpl ) THEN
+         ! coupled mode: sublimation already included in emp_ice (to do in limsbc_ice)
+         zdh_s_sub(:)      =  0._wp 
+      ELSE
+         ! forced  mode: snow thickness change due to sublimation
+         DO ji = kideb, kiut
+            zdh_s_sub(ji)  =  MAX( - ht_s_1d(ji) , - parsub * qla_ice_1d(ji) / ( rhosn * lsub ) * rdt_ice )
+            ! Heat flux by sublimation [W.m-2], < 0
+            !      sublimate first snow that had fallen, then pre-existing snow
+            zcoeff         =      ( MAX( zdh_s_sub(ji), - MAX( 0._wp, zdh_s_pre(ji) + zdh_s_mel(ji) ) )   * zqprec(ji) +   &
+               &  ( zdh_s_sub(ji) - MAX( zdh_s_sub(ji), - MAX( 0._wp, zdh_s_pre(ji) + zdh_s_mel(ji) ) ) ) * q_s_1d(ji,1) )  &
+               &  * a_i_1d(ji) * r1_rdtice
+            hfx_sub_1d(ji) = hfx_sub_1d(ji) + zcoeff
+            ! Mass flux by sublimation
+            wfx_sub_1d(ji) =  wfx_sub_1d(ji) - rhosn * a_i_1d(ji) * zdh_s_sub(ji) * r1_rdtice
+            ! new snow thickness
+            ht_s_1d(ji)     =  MAX( 0._wp , ht_s_1d(ji) + zdh_s_sub(ji) )
+         END DO
+      ENDIF
+
+      ! --- Update snow diags --- !
+      DO ji = kideb, kiut
+         dh_s_tot(ji)   = zdh_s_mel(ji) + zdh_s_pre(ji) + zdh_s_sub(ji)
+         zh_s(ji)       = ht_s_1d(ji) / REAL( nlay_s )
       END DO ! ji
 
+      !-------------------------------------------
+      ! 3.3 Update temperature, energy
+      !-------------------------------------------
+      ! new temp and enthalpy of the snow (remaining snow precip + remaining pre-existing snow)
+      zq_s(:) = 0._wp 
+      DO jk = 1, nlay_s
+         DO ji = kideb,kiut
+            rswitch       =  MAX(  0._wp , SIGN( 1._wp, - ht_s_1d(ji) + epsi20 )  )
+            q_s_1d(ji,jk) = ( 1._wp - rswitch ) / MAX( ht_s_1d(ji), epsi20 ) *             &
+              &            ( (   MAX( 0._wp, dh_s_tot(ji) )              ) * zqprec(ji) +  &
+              &              ( - MAX( 0._wp, dh_s_tot(ji) ) + ht_s_1d(ji) ) * rhosn * ( cpic * ( rtt - t_s_1d(ji,jk) ) + lfus ) )
+            zq_s(ji)     =  zq_s(ji) + q_s_1d(ji,jk)
+         END DO
+      END DO
+
       !--------------------------
-      ! 3.2 Surface ice ablation 
+      ! 3.4 Surface ice ablation 
       !--------------------------
-      DO ji = kideb, kiut 
-         z_f_surf (ji) =  zqfont_su(ji) * r1_rdtice   ! heat conservation test
-         zdq_i    (ji) =  0._wp
-      END DO ! ji
-
+      zdeltah(:,:) = 0._wp ! important
       DO jk = 1, nlay_i
          DO ji = kideb, kiut 
-            !                                                    ! melt of layer jk
-            zdeltah  (ji,jk) = - zqfont_su(ji) / q_i_b(ji,jk)
-            !                                                    ! recompute heat available
-            zqfont_su(ji   ) = MAX( 0.0 , - zh_i(ji) - zdeltah(ji,jk) ) * q_i_b(ji,jk) 
-            !                                                    ! melt of layer jk cannot be higher than its thickness
-            zdeltah  (ji,jk) = MAX( zdeltah(ji,jk) , - zh_i(ji) )
-            !                                                    ! update surface melt
-            dh_i_surf(ji   ) = dh_i_surf(ji) + zdeltah(ji,jk) 
-            !                                                    ! for energy conservation
-            zdq_i    (ji   ) = zdq_i(ji) + zdeltah(ji,jk) * q_i_b(ji,jk) * r1_rdtice
-            !
-            ! clem
-            sfx_thd_1d(ji) = sfx_thd_1d(ji) - sm_i_b(ji) * a_i_b(ji)    &
-               &                              * MIN( zdeltah(ji,jk) , 0._wp ) * rhoic / rdt_ice
+            zEi            = - q_i_1d(ji,jk) / rhoic                ! Specific enthalpy of layer k [J/kg, <0]
+
+            ztmelts        = - tmut * s_i_1d(ji,jk) + rtt           ! Melting point of layer k [K]
+
+            zEw            =    rcp * ( ztmelts - rt0 )            ! Specific enthalpy of resulting meltwater [J/kg, <0]
+
+            zdE            =    zEi - zEw                          ! Specific enthalpy difference < 0
+
+            zfmdt          = - zq_su(ji) / zdE                     ! Mass flux to the ocean [kg/m2, >0]
+
+            zdeltah(ji,jk) = - zfmdt / rhoic                       ! Melt of layer jk [m, <0]
+
+            zdeltah(ji,jk) = MIN( 0._wp , MAX( zdeltah(ji,jk) , - zh_i(ji,jk) ) )    ! Melt of layer jk cannot exceed the layer thickness [m, <0]
+
+            zq_su(ji)      = MAX( 0._wp , zq_su(ji) - zdeltah(ji,jk) * rhoic * zdE ) ! update available heat
+
+            dh_i_surf(ji)  = dh_i_surf(ji) + zdeltah(ji,jk)        ! Cumulate surface melt
+
+            zfmdt          = - rhoic * zdeltah(ji,jk)              ! Recompute mass flux [kg/m2, >0]
+
+            zQm            = zfmdt * zEw                           ! Energy of the melt water sent to the ocean [J/m2, <0]
+
+            ! Contribution to salt flux (clem: using sm_i_1d and not s_i_1d(jk) is ok)
+            sfx_sum_1d(ji)   = sfx_sum_1d(ji) - sm_i_1d(ji) * a_i_1d(ji) * zdeltah(ji,jk) * rhoic * r1_rdtice
+
+            ! Contribution to heat flux [W.m-2], < 0
+            hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_rdtice
+
+            ! Total heat flux used in this process [W.m-2], > 0  
+            hfx_sum_1d(ji) = hfx_sum_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_rdtice
+
+            ! Contribution to mass flux
+            wfx_sum_1d(ji) =  wfx_sum_1d(ji) - rhoic * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice
+           
+            ! record which layers have disappeared (for bottom melting) 
+            !    => icount=0 : no layer has vanished
+            !    => icount=5 : 5 layers have vanished
+            rswitch     = MAX( 0._wp , SIGN( 1._wp , - ( zh_i(ji,jk) + zdeltah(ji,jk) ) ) ) 
+            icount(ji)  = icount(ji) + NINT( rswitch )
+            zh_i(ji,jk) = MAX( 0._wp , zh_i(ji,jk) + zdeltah(ji,jk) )
+
+            ! update heat content (J.m-2) and layer thickness
+            qh_i_old(ji,jk) = qh_i_old(ji,jk) + zdeltah(ji,jk) * q_i_1d(ji,jk)
+            h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
          END DO
       END DO
-
-      !                                          !-------------------
-      IF( con_i .AND. jiindex_1d > 0 ) THEN      ! Conservation test
-         !                                       !-------------------
-         numce_dh  = 0
-         meance_dh = 0._wp
-         DO ji = kideb, kiut
-            IF ( ( z_f_surf(ji) + zdq_i(ji) ) .GE. 1.0e-3 ) THEN
-               numce_dh  = numce_dh + 1
-               meance_dh = meance_dh + z_f_surf(ji) + zdq_i(ji)
-            ENDIF
-            IF( z_f_surf(ji) + zdq_i(ji) .GE. 1.0e-3  ) THEN!
-               WRITE(numout,*) ' ALERTE heat loss for surface melt '
-               WRITE(numout,*) ' ii, ij, jl :', ii, ij, jl
-               WRITE(numout,*) ' ht_i_b       : ', ht_i_b(ji)
-               WRITE(numout,*) ' z_f_surf     : ', z_f_surf(ji)
-               WRITE(numout,*) ' zdq_i        : ', zdq_i(ji)
-               WRITE(numout,*) ' ht_i_b       : ', ht_i_b(ji)
-               WRITE(numout,*) ' fc_bo_i      : ', fc_bo_i(ji)
-               WRITE(numout,*) ' fbif_1d      : ', fbif_1d(ji)
-               WRITE(numout,*) ' qlbbq_1d     : ', qlbbq_1d(ji)
-               WRITE(numout,*) ' s_i_new      : ', s_i_new(ji)
-               WRITE(numout,*) ' sss_m        : ', sss_m(ii,ij)
-            ENDIF
-         END DO
-         !
-         IF( numce_dh > 0 )   meance_dh = meance_dh / numce_dh
-         WRITE(numout,*) ' Error report - Category : ', jl
-         WRITE(numout,*) ' ~~~~~~~~~~~~ '
-         WRITE(numout,*) ' Number of points where there is sur. me. error : ', numce_dh
-         WRITE(numout,*) ' Mean basal growth error on error points : ', meance_dh
-         !
-      ENDIF
-
-      !----------------------
-      ! 3.3 Snow sublimation
-      !----------------------
-
-      DO ji = kideb, kiut
-         ! qla_ice is always >=0 (upwards), heat goes to the atmosphere, therefore snow sublimates
-#if defined key_coupled
-         zdh_s_sub(ji)    =  0._wp      ! coupled mode: sublimation already included in emp_ice (to do in limsbc_ice)
-#else
-         !                              ! forced  mode: snow thickness change due to sublimation
-         zdh_s_sub(ji)    =  - parsub * qla_ice_1d(ji) / ( rhosn * lsub ) * rdt_ice
-#endif
-         dh_s_tot (ji)    =  dh_s_tot(ji) + zdh_s_sub(ji)
-         zdhcf            =  ht_s_b(ji) + zdh_s_sub(ji) 
-         ht_s_b   (ji)    =  MAX( zzero , zdhcf )
-         ! we recompute dh_s_tot 
-         dh_s_tot (ji)    =  ht_s_b(ji) - zhsold(ji)
-         qt_s_in  (ji,jl) =  qt_s_in(ji,jl) + zdh_s_sub(ji)*q_s_b(ji,1)
-      END DO
-
-      zqt_dummy(:) = 0.e0
-      DO jk = 1, nlay_s
-         DO ji = kideb,kiut
-            q_s_b    (ji,jk) = rhosn * ( cpic * ( rtt - t_s_b(ji,jk) ) + lfus )
-            zqt_dummy(ji)    =  zqt_dummy(ji) + q_s_b(ji,jk) * ht_s_b(ji) / REAL( nlay_s )            ! heat conservation
-         END DO
-      END DO
-
-      DO jk = 1, nlay_s
-         DO ji = kideb, kiut
-            ! In case of disparition of the snow, we have to update the snow temperatures
-            zhisn  =  MAX(  zzero , SIGN( zone, - ht_s_b(ji) )  )
-            t_s_b(ji,jk) = ( 1.0 - zhisn ) * t_s_b(ji,jk) + zhisn * rtt
-            q_s_b(ji,jk) = ( 1.0 - zhisn ) * q_s_b(ji,jk)
-         END DO
+      ! update ice thickness
+      DO ji = kideb, kiut
+         ht_i_1d(ji) =  MAX( 0._wp , ht_i_1d(ji) + dh_i_surf(ji) )
       END DO
 
@@ -364,302 +394,250 @@
       !------------------------------------------------------------------------------!
       !
-      ! Ice basal growth / melt is given by the ratio of heat budget over basal
-      ! ice heat content.  Basal heat budget is given by the difference between
-      ! the inner conductive flux  (fc_bo_i), from the open water heat flux 
-      ! (qlbbqb) and the turbulent ocean flux (fbif). 
-      ! fc_bo_i is positive downwards. fbif and qlbbq are positive to the ice 
-
-      !-----------------------------------------------------
-      ! 4.1 Basal growth - (a) salinity not varying in time 
-      !-----------------------------------------------------
-      IF(  num_sal /= 2  ) THEN   ! ice salinity constant in time
+      !------------------
+      ! 4.1 Basal growth 
+      !------------------
+      ! Basal growth is driven by heat imbalance at the ice-ocean interface,
+      ! between the inner conductive flux  (fc_bo_i), from the open water heat flux 
+      ! (fhld) and the turbulent ocean flux (fhtur). 
+      ! fc_bo_i is positive downwards. fhtur and fhld are positive to the ice 
+
+      ! If salinity varies in time, an iterative procedure is required, because
+      ! the involved quantities are inter-dependent.
+      ! Basal growth (dh_i_bott) depends upon new ice specific enthalpy (zEi),
+      ! which depends on forming ice salinity (s_i_new), which depends on dh/dt (dh_i_bott)
+      ! -> need for an iterative procedure, which converges quickly
+
+      IF ( num_sal == 2 ) THEN
+         num_iter_max = 5
+      ELSE
+         num_iter_max = 1
+      ENDIF
+
+      !clem debug. Just to be sure that enthalpy at nlay_i+1 is null
+      DO ji = kideb, kiut
+         q_i_1d(ji,nlay_i+1) = 0._wp
+      END DO
+
+      ! Iterative procedure
+      DO iter = 1, num_iter_max
          DO ji = kideb, kiut
-            IF(  ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) ) < 0._wp  ) THEN
-               s_i_new(ji)         =  sm_i_b(ji)
-               ! Melting point in K
-               ztmelts             =  - tmut * s_i_new(ji) + rtt 
-               ! New ice heat content (Bitz and Lipscomb, 1999)
-               ztform              =  t_i_b(ji,nlay_i)  ! t_bo_b crashes in the
-               ! Baltic
-               q_i_b(ji,nlay_i+1)  = rhoic * (  cpic * ( ztmelts - ztform )                                &
-                  &                           + lfus * (  1.0 - ( ztmelts - rtt ) / ( ztform - rtt )  )    &
-                  &                           - rcp  * ( ztmelts - rtt )                                 )
-               ! Basal growth rate = - F*dt / q
-               dh_i_bott(ji)       =  - rdt_ice * ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) ) / q_i_b(ji,nlay_i+1) 
-               sfx_thd_1d(ji) = sfx_thd_1d(ji) - s_i_new(ji) * a_i_b(ji) * dh_i_bott(ji) * rhoic * r1_rdtice
-            ENDIF
-         END DO
-      ENDIF
-
-      !-------------------------------------------------
-      ! 4.1 Basal growth - (b) salinity varying in time 
-      !-------------------------------------------------
-      IF(  num_sal == 2  ) THEN
-         ! the growth rate (dh_i_bott) is function of the new ice heat content (q_i_b(nlay_i+1)). 
-         ! q_i_b depends on the new ice salinity (snewice). 
-         ! snewice depends on dh_i_bott ; it converges quickly, so, no problem
-         ! See Vancoppenolle et al., OM08 for more info on this
-
-         ! Initial value (tested 1D, can be anything between 1 and 20)
-         num_iter_max = 4
-         s_i_new(:)   = 4.0
-
-         ! Iterative procedure
-         DO iter = 1, num_iter_max
-            DO ji = kideb, kiut
-               IF(  fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) < 0.e0  ) THEN
-                  ii = MOD( npb(ji) - 1, jpi ) + 1
-                  ij = ( npb(ji) - 1 ) / jpi + 1
-                  ! Melting point in K
-                  ztmelts             =   - tmut * s_i_new(ji) + rtt 
-                  ! New ice heat content (Bitz and Lipscomb, 1999)
-                  q_i_b(ji,nlay_i+1)  =  rhoic * (  cpic * ( ztmelts - t_bo_b(ji) )                             &
-                     &                            + lfus * ( 1.0 - ( ztmelts - rtt ) / ( t_bo_b(ji) - rtt ) )   &
-                     &                            - rcp * ( ztmelts-rtt )                                     )
-                  ! Bottom growth rate = - F*dt / q
-                  dh_i_bott(ji) =  - rdt_ice * ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) ) / q_i_b(ji,nlay_i+1)
-                  ! New ice salinity ( Cox and Weeks, JGR, 1988 )
-                  ! zswi2  (1) if dh_i_bott/rdt .GT. 3.6e-7
-                  ! zswi12 (1) if dh_i_bott/rdt .LT. 3.6e-7 and .GT. 2.0e-8
-                  ! zswi1  (1) if dh_i_bott/rdt .LT. 2.0e-8
-                  zgrr   = MIN( 1.0e-3, MAX ( dh_i_bott(ji) * r1_rdtice , epsi13 ) )
-                  zswi2  = MAX( zzero , SIGN( zone , zgrr - 3.6e-7 ) ) 
-                  zswi12 = MAX( zzero , SIGN( zone , zgrr - 2.0e-8 ) ) * ( 1.0 - zswi2 )
-                  zswi1  = 1. - zswi2 * zswi12 
-                  zfracs = zswi1  * 0.12 + zswi12 * ( 0.8925 + 0.0568 * LOG( 100.0 * zgrr ) )   &
-                     &                   + zswi2  * 0.26 / ( 0.26 + 0.74 * EXP ( - 724300.0 * zgrr ) ) 
-                  zfracs = MIN( 0.5 , zfracs )
-                  s_i_new(ji) = zfracs * sss_m(ii,ij)
-               ENDIF ! fc_bo_i
-            END DO ! ji
-         END DO ! iter
-
-         ! Final values
-         DO ji = kideb, kiut
-            IF( ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) ) .LT. 0.0  ) THEN
-               ! New ice salinity must not exceed 20 psu
-               s_i_new(ji) = MIN( s_i_new(ji), s_i_max )
-               ! Metling point in K
-               ztmelts     =   - tmut * s_i_new(ji) + rtt 
-               ! New ice heat content (Bitz and Lipscomb, 1999)
-               q_i_b(ji,nlay_i+1)  =  rhoic * (  cpic * ( ztmelts - t_bo_b(ji) )                              &
-                  &                            + lfus * ( 1.0 - ( ztmelts - rtt ) / ( t_bo_b(ji) - rtt ) )    &
-                  &                            - rcp * ( ztmelts - rtt )                                    )
-               ! Basal growth rate = - F*dt / q
-               dh_i_bott(ji)       =  - rdt_ice * ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) ) / q_i_b(ji,nlay_i+1)
-               ! Salinity update
-               ! entrapment during bottom growth
-               sfx_thd_1d(ji) = sfx_thd_1d(ji) - s_i_new(ji) * a_i_b(ji) * dh_i_bott(ji) * rhoic * r1_rdtice
-            ENDIF ! heat budget
-         END DO
-      ENDIF
+            IF(  zf_tt(ji) < 0._wp  ) THEN
+
+               ! New bottom ice salinity (Cox & Weeks, JGR88 )
+               !--- zswi1  if dh/dt < 2.0e-8
+               !--- zswi12 if 2.0e-8 < dh/dt < 3.6e-7 
+               !--- zswi2  if dh/dt > 3.6e-7
+               zgrr               = MIN( 1.0e-3, MAX ( dh_i_bott(ji) * r1_rdtice , epsi10 ) )
+               zswi2              = MAX( 0._wp , SIGN( 1._wp , zgrr - 3.6e-7 ) )
+               zswi12             = MAX( 0._wp , SIGN( 1._wp , zgrr - 2.0e-8 ) ) * ( 1.0 - zswi2 )
+               zswi1              = 1. - zswi2 * zswi12
+               zfracs             = MIN ( zswi1  * 0.12 + zswi12 * ( 0.8925 + 0.0568 * LOG( 100.0 * zgrr ) )   &
+                  &               + zswi2  * 0.26 / ( 0.26 + 0.74 * EXP ( - 724300.0 * zgrr ) )  , 0.5 )
+
+               ii = MOD( npb(ji) - 1, jpi ) + 1 ; ij = ( npb(ji) - 1 ) / jpi + 1
+
+               s_i_new(ji)        = zswitch_sal * zfracs * sss_m(ii,ij)  &  ! New ice salinity
+                                  + ( 1. - zswitch_sal ) * sm_i_1d(ji) 
+               ! New ice growth
+               ztmelts            = - tmut * s_i_new(ji) + rtt          ! New ice melting point (K)
+
+               zt_i_new           = zswitch_sal * t_bo_1d(ji) + ( 1. - zswitch_sal) * t_i_1d(ji, nlay_i)
+               
+               zEi                = cpic * ( zt_i_new - ztmelts ) &     ! Specific enthalpy of forming ice (J/kg, <0)      
+                  &               - lfus * ( 1.0 - ( ztmelts - rtt ) / ( zt_i_new - rtt ) )   &
+                  &               + rcp  * ( ztmelts-rtt )          
+
+               zEw                = rcp  * ( t_bo_1d(ji) - rt0 )         ! Specific enthalpy of seawater (J/kg, < 0)
+
+               zdE                = zEi - zEw                           ! Specific enthalpy difference (J/kg, <0)
+
+               dh_i_bott(ji)      = rdt_ice * MAX( 0._wp , zf_tt(ji) / ( zdE * rhoic ) )
+
+               q_i_1d(ji,nlay_i+1) = -zEi * rhoic                        ! New ice energy of melting (J/m3, >0)
+               
+            ENDIF ! fc_bo_i
+         END DO ! ji
+      END DO ! iter
+
+      ! Contribution to Energy and Salt Fluxes
+      DO ji = kideb, kiut
+         IF(  zf_tt(ji) < 0._wp  ) THEN
+            ! New ice growth
+                                    
+            zfmdt          = - rhoic * dh_i_bott(ji)             ! Mass flux x time step (kg/m2, < 0)
+
+            ztmelts        = - tmut * s_i_new(ji) + rtt          ! New ice melting point (K)
+            
+            zt_i_new       = zswitch_sal * t_bo_1d(ji) + ( 1. - zswitch_sal) * t_i_1d(ji, nlay_i)
+            
+            zEi            = cpic * ( zt_i_new - ztmelts ) &     ! Specific enthalpy of forming ice (J/kg, <0)      
+               &               - lfus * ( 1.0 - ( ztmelts - rtt ) / ( zt_i_new - rtt ) )   &
+               &               + rcp  * ( ztmelts-rtt )          
+            
+            zEw            = rcp  * ( t_bo_1d(ji) - rt0 )         ! Specific enthalpy of seawater (J/kg, < 0)
+            
+            zdE            = zEi - zEw                           ! Specific enthalpy difference (J/kg, <0)
+            
+            ! Contribution to heat flux to the ocean [W.m-2], >0  
+            hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_rdtice
+
+            ! Total heat flux used in this process [W.m-2], <0  
+            hfx_bog_1d(ji) = hfx_bog_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_rdtice
+            
+            ! Contribution to salt flux, <0
+            sfx_bog_1d(ji) = sfx_bog_1d(ji) + s_i_new(ji) * a_i_1d(ji) * zfmdt * r1_rdtice
+
+            ! Contribution to mass flux, <0
+            wfx_bog_1d(ji) =  wfx_bog_1d(ji) - rhoic * a_i_1d(ji) * dh_i_bott(ji) * r1_rdtice
+
+            ! update heat content (J.m-2) and layer thickness
+            qh_i_old(ji,nlay_i+1) = qh_i_old(ji,nlay_i+1) + dh_i_bott(ji) * q_i_1d(ji,nlay_i+1)
+            h_i_old (ji,nlay_i+1) = h_i_old (ji,nlay_i+1) + dh_i_bott(ji)
+         ENDIF
+      END DO
 
       !----------------
       ! 4.2 Basal melt
       !----------------
-      meance_dh = 0._wp
-      numce_dh  = 0
-      zinnermelt(:) = 0._wp
-
-      DO ji = kideb, kiut
-         ! heat convergence at the surface > 0
-         IF(  ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) ) >= 0._wp  ) THEN
-            s_i_new(ji)   =  s_i_b(ji,nlay_i)
-            zqfont_bo(ji) =  rdt_ice * ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) )
-            zfbase(ji)    =  zqfont_bo(ji) * r1_rdtice     ! heat conservation test
-            zdq_i(ji)     =  0._wp
-            dh_i_bott(ji) =  0._wp
-         ENDIF
-      END DO
-
+      zdeltah(:,:) = 0._wp ! important
       DO jk = nlay_i, 1, -1
          DO ji = kideb, kiut
-            IF(  fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji)  >=  0._wp  ) THEN
-               ztmelts = - tmut * s_i_b(ji,jk) + rtt 
-               IF( t_i_b(ji,jk) >= ztmelts ) THEN   !!gm : a comment is needed
-                  zdeltah   (ji,jk) = - zh_i(ji)
-                  dh_i_bott (ji   ) = dh_i_bott(ji) + zdeltah(ji,jk)
-                  zinnermelt(ji   ) = 1._wp
-               ELSE                                  ! normal ablation
-                  zdeltah  (ji,jk) = - zqfont_bo(ji) / q_i_b(ji,jk)
-                  zqfont_bo(ji   ) = MAX( 0.0 , - zh_i(ji) - zdeltah(ji,jk) ) * q_i_b(ji,jk)
-                  zdeltah  (ji,jk) = MAX(zdeltah(ji,jk), - zh_i(ji) )
-                  dh_i_bott(ji   ) = dh_i_bott(ji) + zdeltah(ji,jk)
-                  zdq_i    (ji   ) = zdq_i(ji) + zdeltah(ji,jk) * q_i_b(ji,jk) * r1_rdtice
+            IF(  zf_tt(ji)  >=  0._wp  .AND. jk > icount(ji) ) THEN   ! do not calculate where layer has already disappeared from surface melting 
+
+               ztmelts = - tmut * s_i_1d(ji,jk) + rtt  ! Melting point of layer jk (K)
+
+               IF( t_i_1d(ji,jk) >= ztmelts ) THEN !!! Internal melting
+
+                  zEi               = - q_i_1d(ji,jk) / rhoic        ! Specific enthalpy of melting ice (J/kg, <0)
+
+                  !!zEw               = rcp * ( t_i_1d(ji,jk) - rtt )  ! Specific enthalpy of meltwater at T = t_i_1d (J/kg, <0)
+
+                  zdE               = 0._wp                         ! Specific enthalpy difference   (J/kg, <0)
+                                                                    ! set up at 0 since no energy is needed to melt water...(it is already melted)
+
+                  zdeltah   (ji,jk) = MIN( 0._wp , - zh_i(ji,jk) ) ! internal melting occurs when the internal temperature is above freezing     
+                                                                   ! this should normally not happen, but sometimes, heat diffusion leads to this
+
+                  dh_i_bott (ji)    = dh_i_bott(ji) + zdeltah(ji,jk)
+
+                  zfmdt             = - zdeltah(ji,jk) * rhoic          ! Mass flux x time step > 0
+
+                  ! Contribution to heat flux to the ocean [W.m-2], <0 (ice enthalpy zEi is "sent" to the ocean) 
+                  hfx_res_1d(ji) = hfx_res_1d(ji) + zfmdt * a_i_1d(ji) * zEi * r1_rdtice
+
+                  ! Contribution to salt flux (clem: using sm_i_1d and not s_i_1d(jk) is ok)
+                  sfx_res_1d(ji) = sfx_res_1d(ji) - sm_i_1d(ji) * a_i_1d(ji) * zdeltah(ji,jk) * rhoic * r1_rdtice
+                                    
+                  ! Contribution to mass flux
+                  wfx_res_1d(ji) =  wfx_res_1d(ji) - rhoic * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice
+
+                  ! update heat content (J.m-2) and layer thickness
+                  qh_i_old(ji,jk) = qh_i_old(ji,jk) + zdeltah(ji,jk) * q_i_1d(ji,jk)
+                  h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
+
+               ELSE                               !!! Basal melting
+
+                  zEi               = - q_i_1d(ji,jk) / rhoic ! Specific enthalpy of melting ice (J/kg, <0)
+
+                  zEw               = rcp * ( ztmelts - rtt )! Specific enthalpy of meltwater (J/kg, <0)
+
+                  zdE               = zEi - zEw              ! Specific enthalpy difference   (J/kg, <0)
+
+                  zfmdt             = - zq_bo(ji) / zdE  ! Mass flux x time step (kg/m2, >0)
+
+                  zdeltah(ji,jk)    = - zfmdt / rhoic        ! Gross thickness change
+
+                  zdeltah(ji,jk)    = MIN( 0._wp , MAX( zdeltah(ji,jk), - zh_i(ji,jk) ) ) ! bound thickness change
+                  
+                  zq_bo(ji)         = MAX( 0._wp , zq_bo(ji) - zdeltah(ji,jk) * rhoic * zdE ) ! update available heat. MAX is necessary for roundup errors
+
+                  dh_i_bott(ji)     = dh_i_bott(ji) + zdeltah(ji,jk)    ! Update basal melt
+
+                  zfmdt             = - zdeltah(ji,jk) * rhoic          ! Mass flux x time step > 0
+
+                  zQm               = zfmdt * zEw         ! Heat exchanged with ocean
+
+                  ! Contribution to heat flux to the ocean [W.m-2], <0  
+                  hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_rdtice
+
+                  ! Contribution to salt flux (clem: using sm_i_1d and not s_i_1d(jk) is ok)
+                  sfx_bom_1d(ji) = sfx_bom_1d(ji) - sm_i_1d(ji) * a_i_1d(ji) * zdeltah(ji,jk) * rhoic * r1_rdtice
+                  
+                  ! Total heat flux used in this process [W.m-2], >0  
+                  hfx_bom_1d(ji) = hfx_bom_1d(ji) - zfmdt * a_i_1d(ji) * zdE * r1_rdtice
+                  
+                  ! Contribution to mass flux
+                  wfx_bom_1d(ji) =  wfx_bom_1d(ji) - rhoic * a_i_1d(ji) * zdeltah(ji,jk) * r1_rdtice
+
+                  ! update heat content (J.m-2) and layer thickness
+                  qh_i_old(ji,jk) = qh_i_old(ji,jk) + zdeltah(ji,jk) * q_i_1d(ji,jk)
+                  h_i_old (ji,jk) = h_i_old (ji,jk) + zdeltah(ji,jk)
                ENDIF
-               ! clem: contribution to salt flux
-               sfx_thd_1d(ji) = sfx_thd_1d(ji) - sm_i_b(ji) * a_i_b(ji)    &
-                    &                              * MIN( zdeltah(ji,jk) , 0._wp ) * rhoic * r1_rdtice
+           
             ENDIF
          END DO ! ji
       END DO ! jk
 
-      !                                          !-------------------
-      IF( con_i .AND. jiindex_1d > 0 ) THEN      ! Conservation test
-      !                                          !-------------------
-         DO ji = kideb, kiut
-            IF(  ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) ) >= 0.e0  ) THEN
-               IF( ( zfbase(ji) + zdq_i(ji) ) >= 1.e-3 ) THEN
-                  numce_dh  = numce_dh + 1
-                  meance_dh = meance_dh + zfbase(ji) + zdq_i(ji)
-               ENDIF
-               IF ( zfbase(ji) + zdq_i(ji) .GE. 1.0e-3  ) THEN
-                  WRITE(numout,*) ' ALERTE heat loss for basal melt : ii, ij, jl :', ii, ij, jl
-                  WRITE(numout,*) ' ht_i_b    : ', ht_i_b(ji)
-                  WRITE(numout,*) ' zfbase    : ', zfbase(ji)
-                  WRITE(numout,*) ' zdq_i     : ', zdq_i(ji)
-                  WRITE(numout,*) ' ht_i_b    : ', ht_i_b(ji)
-                  WRITE(numout,*) ' fc_bo_i   : ', fc_bo_i(ji)
-                  WRITE(numout,*) ' fbif_1d   : ', fbif_1d(ji)
-                  WRITE(numout,*) ' qlbbq_1d  : ', qlbbq_1d(ji)
-                  WRITE(numout,*) ' s_i_new   : ', s_i_new(ji)
-                  WRITE(numout,*) ' sss_m     : ', sss_m(ii,ij)
-                  WRITE(numout,*) ' dh_i_bott : ', dh_i_bott(ji)
-                  WRITE(numout,*) ' innermelt : ', INT( zinnermelt(ji) )
-               ENDIF
-            ENDIF
-         END DO
-         IF( numce_dh > 0 )   meance_dh = meance_dh / numce_dh
-         WRITE(numout,*) ' Number of points where there is bas. me. error : ', numce_dh
-         WRITE(numout,*) ' Mean basal melt error on error points : ', meance_dh
-         WRITE(numout,*) ' Remaining bottom heat : ', zqfont_bo(jiindex_1d)
-         !
-      ENDIF
-
-      !
       !------------------------------------------------------------------------------!
-      !  5) Pathological cases                                                       !
+      ! Excessive ablation in a 1-category model
+      !     in a 1-category sea ice model, bottom ablation must not exceed hmelt (-0.15)
       !------------------------------------------------------------------------------!
-      !
-      !----------------------------------------------
-      ! 5.1 Excessive ablation in a 1-category model
-      !----------------------------------------------
-
-      DO ji = kideb, kiut
-         !                     ! in a 1-category sea ice model, bottom ablation must not exceed hmelt (-0.15)
-         IF( jpl == 1 ) THEN   ;   zdhbf = MAX( hmelt , dh_i_bott(ji) )
-         ELSE                  ;   zdhbf =              dh_i_bott(ji) 
-         ENDIF
-         zdvres        = zdhbf - dh_i_bott(ji)
-         dh_i_bott(ji) = zdhbf
-         sfx_thd_1d(ji)  = sfx_thd_1d(ji) - sm_i_b(ji) * a_i_b(ji) * zdvres * rhoic * r1_rdtice
-         !                     ! excessive energy is sent to lateral ablation
-         zinda = MAX( 0._wp, SIGN( 1._wp , 1.0 - at_i_b(ji) - epsi10 ) )
-         fsup(ji) =  zinda * rhoic * lfus * at_i_b(ji) / MAX( 1.0 - at_i_b(ji) , epsi10 ) * zdvres * r1_rdtice
-      END DO
-
-      !-----------------------------------
-      ! 5.2 More than available ice melts
-      !-----------------------------------
-      ! then heat applied minus heat content at previous time step should equal heat remaining 
-      !
-      DO ji = kideb, kiut
-         ! Adapt the remaining energy if too much ice melts
-         !--------------------------------------------------
-         zdvres     = MAX( 0._wp, - ht_i_b(ji) - dh_i_surf(ji) - dh_i_bott(ji) )
-         zdvsur     = MIN( 0._wp, dh_i_surf(ji) + zdvres ) - dh_i_surf(ji) ! fill the surface first
-         zdvbot     = MAX( 0._wp, zdvres - zdvsur ) ! then the bottom
-         dh_i_surf (ji) = dh_i_surf(ji) + zdvsur ! clem
-         dh_i_bott (ji) = dh_i_bott(ji) + zdvbot ! clem
-
-         ! new ice thickness (clem)
-         zhgnew(ji) = ht_i_b(ji) + dh_i_surf(ji) + dh_i_bott(ji)
-         zihgnew    = 1.0 - MAX( zzero , SIGN( zone , - zhgnew(ji) ) ) !1 if ice
-         zhgnew(ji) = zihgnew * zhgnew(ji)      ! ice thickness is put to 0
- 
-         !                     !since ice volume is only used for outputs, we keep it global for all categories
-         dvbbq_1d (ji) = a_i_b(ji) * dh_i_bott(ji)
-
-        ! remaining heat
-         zfdt_final(ji) = ( 1.0 - zihgnew ) * ( zqfont_su(ji) +  zqfont_bo(ji) ) 
-
-         ! If snow remains, energy is used to melt snow
-         zhni =  ht_s_b(ji)      ! snow depth at previous time step
-         zihg =  MAX(  zzero , SIGN ( zone , - ht_s_b(ji) )  )   ! =0 if snow 
-
-         ! energy of melting of remaining snow
-         zinda = MAX( 0._wp, SIGN( 1._wp , zhni - epsi10 ) )
-         zqt_s(ji) =    ( 1. - zihg ) * zqt_s(ji) / MAX( zhni, epsi10 ) * zinda
-         zdhnm     =  - ( 1. - zihg ) * ( 1. - zihgnew ) * zfdt_final(ji) / MAX( zqt_s(ji) , epsi13 )
-         zhnfi     =  zhni + zdhnm
-         zfdt_final(ji) =  MAX( zfdt_final(ji) + zqt_s(ji) * zdhnm , 0.0 )
-         ht_s_b(ji)     =  MAX( zzero , zhnfi )
-         zqt_s(ji)      =  zqt_s(ji) * ht_s_b(ji)
-         ! we recompute dh_s_tot (clem)
-         dh_s_tot (ji)  =  ht_s_b(ji) - zhsold(ji)
-
-         ! Mass variations of ice and snow
-         !---------------------------------
-         !                                              ! mass variation of the jl category
-         zzfmass_s = - a_i_b(ji) * ( zhni       - ht_s_b(ji) ) * rhosn   ! snow
-         zzfmass_i =   a_i_b(ji) * ( zhgnew(ji) - ht_i_b(ji) ) * rhoic   ! ice  
-         !
-         zfmass_i(ji) = zzfmass_i                       ! ice variation saved to compute salt flux (see below)
-         !
-         !                                              ! mass variation cumulated over category
-         !clem rdm_snw_1d(ji) = rdm_snw_1d(ji) + zzfmass_s                     ! snow 
-         !clem rdm_ice_1d(ji) = rdm_ice_1d(ji) + zzfmass_i                     ! ice 
-
-         ! Remaining heat to the ocean 
-         !---------------------------------
-         focea(ji)  = - zfdt_final(ji) * r1_rdtice         ! focea is in W.m-2 * dt
-
-         ! residual salt flux (clem)
-         !--------------------------
-         ! surface
-         sfx_thd_1d(ji)    = sfx_thd_1d(ji) - sm_i_b(ji)  * a_i_b(ji) * zdvsur * rhoic * r1_rdtice
-         ! bottom
-         IF ( fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji) >= 0._wp ) THEN ! melting
-            sfx_thd_1d(ji) = sfx_thd_1d(ji) - sm_i_b(ji)  * a_i_b(ji) * zdvbot * rhoic * r1_rdtice
-         ELSE                                                          ! growth
-            sfx_thd_1d(ji) = sfx_thd_1d(ji) - s_i_new(ji) * a_i_b(ji) * zdvbot * rhoic * r1_rdtice
-         ENDIF
-         !
-         ! diagnostic 
-         ii = MOD( npb(ji) - 1, jpi ) + 1
-         ij = ( npb(ji) - 1 ) / jpi + 1
-         diag_bot_gr(ii,ij) = diag_bot_gr(ii,ij) + MAX(dh_i_bott(ji),0.0)*a_i_b(ji) * r1_rdtice
-         diag_sur_me(ii,ij) = diag_sur_me(ii,ij) + MIN(dh_i_surf(ji),0.0)*a_i_b(ji) * r1_rdtice
-         diag_bot_me(ii,ij) = diag_bot_me(ii,ij) + MIN(dh_i_bott(ji),0.0)*a_i_b(ji) * r1_rdtice
-      END DO
-
-      ftotal_fin (:) = zfdt_final(:)  * r1_rdtice
-
-      !---------------------------
-      ! heat fluxes                    
-      !---------------------------
-      DO ji = kideb, kiut
-         zihgnew    =  1.0 - MAX( zzero , SIGN( zone , - zhgnew(ji) ) )   ! =1 if ice
-         !
-         ! Heat flux
-         ! excessive bottom ablation energy (fsup) - 0 except if jpl = 1
-         ! excessive total  ablation energy (focea) sent to the ocean
-         qfvbq_1d(ji)  = qfvbq_1d(ji) + fsup(ji) + ( 1.0 - zihgnew ) * focea(ji) * a_i_b(ji) * rdt_ice
-
-         zihic   = 1.0 - MAX(  zzero , SIGN( zone , -ht_i_b(ji) )  )      ! equals 0 if ht_i = 0, 1 if ht_i gt 0
-         fscbq_1d(ji) =  a_i_b(ji) * fstbif_1d(ji)
-         qldif_1d(ji)  = qldif_1d(ji) + fsup(ji) + ( 1.0 - zihgnew ) * focea   (ji) * a_i_b(ji) * rdt_ice   &
-            &                                    + ( 1.0 - zihic   ) * fscbq_1d(ji)             * rdt_ice
-      END DO  ! ji
-
-      !-------------------------------------------
-      ! Correct temperature, energy and thickness
-      !-------------------------------------------
-      DO ji = kideb, kiut
-         zihgnew    =  1.0 - MAX( zzero , SIGN( zone , - zhgnew(ji) ) ) 
-         t_su_b(ji) =  zihgnew * t_su_b(ji) + ( 1.0 - zihgnew ) * rtt
-      END DO  ! ji
-
-      DO jk = 1, nlay_i
-         DO ji = kideb, kiut
-            zihgnew      =  1.0 - MAX( zzero , SIGN( zone , - zhgnew(ji) ) ) 
-            t_i_b(ji,jk) =  zihgnew * t_i_b(ji,jk) + ( 1.0 - zihgnew ) * rtt
-            q_i_b(ji,jk) =  zihgnew * q_i_b(ji,jk)
-         END DO
-      END DO  ! ji
-
-      DO ji = kideb, kiut
-         ht_i_b(ji) = zhgnew(ji)
-      END DO  ! ji
+      ! ??? keep ???
+      ! clem bug: I think this should be included above, so we would not have to 
+      !           track heat/salt/mass fluxes backwards
+!      IF( jpl == 1 ) THEN
+!         DO ji = kideb, kiut
+!            IF(  zf_tt(ji)  >=  0._wp  ) THEN
+!               zdh            = MAX( hmelt , dh_i_bott(ji) )
+!               zdvres         = zdh - dh_i_bott(ji) ! >=0
+!               dh_i_bott(ji)  = zdh
+!
+!               ! excessive energy is sent to lateral ablation
+!               rswitch = MAX( 0._wp, SIGN( 1._wp , 1._wp - at_i_1d(ji) - epsi20 ) )
+!               zq_1cat(ji) =  rswitch * rhoic * lfus * at_i_1d(ji) / MAX( 1._wp - at_i_1d(ji) , epsi20 ) * zdvres ! J.m-2 >=0
+!
+!               ! correct salt and mass fluxes
+!               sfx_bom_1d(ji) = sfx_bom_1d(ji) - sm_i_1d(ji) * a_i_1d(ji) * zdvres * rhoic * r1_rdtice ! this is only a raw approximation
+!               wfx_bom_1d(ji) = wfx_bom_1d(ji) - rhoic * a_i_1d(ji) * zdvres * r1_rdtice
+!            ENDIF
+!         END DO
+!      ENDIF
+
+      !-------------------------------------------
+      ! Update temperature, energy
+      !-------------------------------------------
+      DO ji = kideb, kiut
+         ht_i_1d(ji) =  MAX( 0._wp , ht_i_1d(ji) + dh_i_bott(ji) )
+      END DO  
+
+      !-------------------------------------------
+      ! 5. What to do with remaining energy
+      !-------------------------------------------
+      ! If heat still available for melting and snow remains, then melt more snow
+      !-------------------------------------------
+      zdeltah(:,:) = 0._wp ! important
+      DO ji = kideb, kiut
+         zq_rema(ji)     = zq_su(ji) + zq_bo(ji) 
+!         zindh           = 1._wp - MAX( 0._wp, SIGN( 1._wp, - ht_s_1d(ji) ) )   ! =1 if snow
+!         zindq           = 1._wp - MAX( 0._wp, SIGN( 1._wp, - zq_s(ji) + epsi20 ) )
+!         zdeltah  (ji,1) = - zindh * zindq * zq_rema(ji) / MAX( zq_s(ji), epsi20 )
+!         zdeltah  (ji,1) = MIN( 0._wp , MAX( zdeltah(ji,1) , - ht_s_1d(ji) ) ) ! bound melting
+!         zdh_s_mel(ji)   = zdh_s_mel(ji) + zdeltah(ji,1)    
+!         dh_s_tot (ji)   = dh_s_tot(ji) + zdeltah(ji,1)
+!         ht_s_1d   (ji)   = ht_s_1d(ji)   + zdeltah(ji,1)
+!        
+!         zq_rema(ji)     = zq_rema(ji) + zdeltah(ji,1) * zq_s(ji)                ! update available heat (J.m-2)
+!         ! heat used to melt snow
+!         hfx_snw_1d(ji)  = hfx_snw_1d(ji) - zdeltah(ji,1) * a_i_1d(ji) * zq_s(ji) * r1_rdtice ! W.m-2 (>0)
+!         ! Contribution to mass flux
+!         wfx_snw_1d(ji)  =  wfx_snw_1d(ji) - rhosn * a_i_1d(ji) * zdeltah(ji,1) * r1_rdtice
+!    
+         ii = MOD( npb(ji) - 1, jpi ) + 1 ; ij = ( npb(ji) - 1 ) / jpi + 1
+         ! Remaining heat flux (W.m-2) is sent to the ocean heat budget
+         hfx_out(ii,ij)  = hfx_out(ii,ij) + ( zq_1cat(ji) + zq_rema(ji) * a_i_1d(ji) ) * r1_rdtice
+
+         IF( ln_nicep .AND. zq_rema(ji) < 0. .AND. lwp ) WRITE(numout,*) 'ALERTE zq_rema <0 = ', zq_rema(ji)
+      END DO
+      
       !
       !------------------------------------------------------------------------------|
@@ -670,63 +648,77 @@
       DO ji = kideb, kiut
          !
-         dh_snowice(ji) = MAX(  zzero , ( rhosn * ht_s_b(ji) + (rhoic-rau0) * ht_i_b(ji) ) / ( rhosn+rau0-rhoic )  )
-         zhgnew(ji)     = MAX(  zhgnew(ji) , zhgnew(ji) + dh_snowice(ji)  )
-         zhnnew         = MIN(  ht_s_b(ji) , ht_s_b(ji) - dh_snowice(ji)  )
-
-         !  Changes in ice volume and ice mass.
-         dvnbq_1d  (ji) =                a_i_b(ji) * ( zhgnew(ji)-ht_i_b(ji) )
-         dmgwi_1d  (ji) = dmgwi_1d(ji) + a_i_b(ji) * ( ht_s_b(ji) - zhnnew ) * rhosn
-
-         !clem rdm_ice_1d(ji) = rdm_ice_1d(ji) + a_i_b(ji) * ( zhgnew(ji) - ht_i_b(ji) ) * rhoic 
-         !clem rdm_snw_1d(ji) = rdm_snw_1d(ji) + a_i_b(ji) * ( zhnnew     - ht_s_b(ji) ) * rhosn 
-
-         !        Equivalent salt flux (1) Snow-ice formation component
-         !        -----------------------------------------------------
-         ii = MOD( npb(ji) - 1, jpi ) + 1
-         ij =    ( npb(ji) - 1 ) / jpi + 1
-
-         IF( num_sal == 2 ) THEN   ;   zsm_snowice = sss_m(ii,ij) * ( rhoic - rhosn ) / rhoic
-         ELSE                      ;   zsm_snowice = sm_i_b(ji)   
-         ENDIF
+         dh_snowice(ji) = MAX(  0._wp , ( rhosn * ht_s_1d(ji) + (rhoic-rau0) * ht_i_1d(ji) ) / ( rhosn+rau0-rhoic )  )
+
+         ht_i_1d(ji)     = ht_i_1d(ji) + dh_snowice(ji)
+         ht_s_1d(ji)     = ht_s_1d(ji) - dh_snowice(ji)
+
+         ! Salinity of snow ice
+         ii = MOD( npb(ji) - 1, jpi ) + 1 ; ij = ( npb(ji) - 1 ) / jpi + 1
+         zs_snic = zswitch_sal * sss_m(ii,ij) * ( rhoic - rhosn ) / rhoic + ( 1. - zswitch_sal ) * sm_i_1d(ji)
+
          ! entrapment during snow ice formation
-         ! clem: new salinity difference stored (to be used in limthd_ent.F90)
+         ! new salinity difference stored (to be used in limthd_ent.F90)
          IF (  num_sal == 2  ) THEN
-            i_ice_switch = MAX( 0._wp , SIGN( 1._wp , zhgnew(ji) - epsi10 ) )
+            rswitch = MAX( 0._wp , SIGN( 1._wp , ht_i_1d(ji) - epsi10 ) )
             ! salinity dif due to snow-ice formation
-            dsm_i_si_1d(ji) = ( zsm_snowice - sm_i_b(ji) ) * dh_snowice(ji) / MAX( zhgnew(ji), epsi10 ) * i_ice_switch     
+            dsm_i_si_1d(ji) = ( zs_snic - sm_i_1d(ji) ) * dh_snowice(ji) / MAX( ht_i_1d(ji), epsi10 ) * rswitch     
             ! salinity dif due to bottom growth 
-            IF (  fc_bo_i(ji) + fbif_1d(ji) + qlbbq_1d(ji)  < 0._wp ) THEN
-               dsm_i_se_1d(ji) = ( s_i_new(ji) - sm_i_b(ji) ) * dh_i_bott(ji) / MAX( zhgnew(ji), epsi10 ) * i_ice_switch
+            IF (  zf_tt(ji)  < 0._wp ) THEN
+               dsm_i_se_1d(ji) = ( s_i_new(ji) - sm_i_1d(ji) ) * dh_i_bott(ji) / MAX( ht_i_1d(ji), epsi10 ) * rswitch
             ENDIF
          ENDIF
 
-         !  Actualize new snow and ice thickness.
-         ht_s_b(ji)  = zhnnew
-         ht_i_b(ji)  = zhgnew(ji)
-
-         ! Total ablation ! new lines added to debug
-         IF( ht_i_b(ji) <= 0._wp )   a_i_b(ji) = 0._wp
-
-         ! diagnostic ( snow ice growth )
-         ii = MOD( npb(ji) - 1, jpi ) + 1
-         ij =    ( npb(ji) - 1 ) / jpi + 1
-         diag_sni_gr(ii,ij)  = diag_sni_gr(ii,ij) + dh_snowice(ji)*a_i_b(ji) * r1_rdtice
-         !
-         ! salt flux
-         sfx_thd_1d(ji) = sfx_thd_1d(ji) - zsm_snowice * a_i_b(ji) * dh_snowice(ji) * rhoic * r1_rdtice
-         !--------------------------------
-         ! Update mass fluxes (clem)
-         !--------------------------------
-         rdm_ice_1d(ji) = rdm_ice_1d(ji) + ( a_i_b(ji) * ht_i_b(ji) - zviold(ji) ) * rhoic 
-         rdm_snw_1d(ji) = rdm_snw_1d(ji) + ( a_i_b(ji) * ht_s_b(ji) - zvsold(ji) ) * rhosn 
+         ! Contribution to energy flux to the ocean [J/m2], >0 (if sst<0)
+         ii = MOD( npb(ji) - 1, jpi ) + 1 ; ij = ( npb(ji) - 1 ) / jpi + 1
+         zfmdt          = ( rhosn - rhoic ) * MAX( dh_snowice(ji), 0._wp )    ! <0
+         zsstK          = sst_m(ii,ij) + rt0                                
+         zEw            = rcp * ( zsstK - rt0 )
+         zQm            = zfmdt * zEw 
+         
+         ! Contribution to heat flux
+         hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * a_i_1d(ji) * zEw * r1_rdtice 
+
+         ! Contribution to salt flux
+         sfx_sni_1d(ji) = sfx_sni_1d(ji) + sss_m(ii,ij) * a_i_1d(ji) * zfmdt * r1_rdtice 
+          
+         ! Contribution to mass flux
+         ! All snow is thrown in the ocean, and seawater is taken to replace the volume
+         wfx_sni_1d(ji) = wfx_sni_1d(ji) - a_i_1d(ji) * dh_snowice(ji) * rhoic * r1_rdtice
+         wfx_snw_1d(ji) = wfx_snw_1d(ji) + a_i_1d(ji) * dh_snowice(ji) * rhosn * r1_rdtice
+
+         ! update heat content (J.m-2) and layer thickness
+         qh_i_old(ji,0) = qh_i_old(ji,0) + dh_snowice(ji) * q_s_1d(ji,1) + zfmdt * zEw
+         h_i_old (ji,0) = h_i_old (ji,0) + dh_snowice(ji)
+         
+         ! Total ablation (to debug)
+         IF( ht_i_1d(ji) <= 0._wp )   a_i_1d(ji) = 0._wp
 
       END DO !ji
-      !
-      CALL wrk_dealloc( jpij, zh_i, zh_s, ztfs, zhsold, zqprec, zqfont_su, zqfont_bo, z_f_surf, zhgnew, zfmass_i )
-      CALL wrk_dealloc( jpij, zdh_s_mel, zdh_s_pre, zdh_s_sub, zfdt_init, zfdt_final, zqt_i, zqt_s, zqt_dummy )
-      CALL wrk_dealloc( jpij, zinnermelt, zfbase, zdq_i )
-      CALL wrk_dealloc( jpij, jkmax, zdeltah, zqt_i_lay )
-      !
-      CALL wrk_dealloc( jpij, zviold, zvsold ) ! clem
+
+      !
+      !-------------------------------------------
+      ! Update temperature, energy
+      !-------------------------------------------
+      !clem bug: we should take snow into account here
+      DO ji = kideb, kiut
+         rswitch     =  1.0 - MAX( 0._wp , SIGN( 1._wp , - ht_i_1d(ji) ) ) 
+         t_su_1d(ji) =  rswitch * t_su_1d(ji) + ( 1.0 - rswitch ) * rtt
+      END DO  ! ji
+
+      DO jk = 1, nlay_s
+         DO ji = kideb,kiut
+            ! mask enthalpy
+            rswitch       =  MAX(  0._wp , SIGN( 1._wp, - ht_s_1d(ji) )  )
+            q_s_1d(ji,jk) = ( 1.0 - rswitch ) * q_s_1d(ji,jk)
+            ! recalculate t_s_1d from q_s_1d
+            t_s_1d(ji,jk) = rtt + ( 1._wp - rswitch ) * ( - q_s_1d(ji,jk) / ( rhosn * cpic ) + lfus / cpic )
+         END DO
+      END DO
+
+      CALL wrk_dealloc( jpij, zh_s, zqprec, zq_su, zq_bo, zf_tt, zq_1cat, zq_rema )
+      CALL wrk_dealloc( jpij, zdh_s_mel, zdh_s_pre, zdh_s_sub, zqh_i, zqh_s, zq_s )
+      CALL wrk_dealloc( jpij, nlay_i+1, zdeltah, zh_i )
+      CALL wrk_dealloc( jpij, icount )
+      !
       !
    END SUBROUTINE lim_thd_dh
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_dif.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_dif.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_dif.F90	(revision 5075)
@@ -25,4 +25,5 @@
    USE wrk_nemo       ! work arrays
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+   USE sbc_oce, ONLY : lk_cpl
 
    IMPLICIT NONE
@@ -31,5 +32,4 @@
    PUBLIC   lim_thd_dif   ! called by lim_thd
 
-   REAL(wp) ::   epsi10      =  1.e-10_wp    !
    !!----------------------------------------------------------------------
    !! NEMO/LIM3 4.0 , UCL - NEMO Consortium (2011)
@@ -39,5 +39,5 @@
 CONTAINS
 
-   SUBROUTINE lim_thd_dif( kideb , kiut , jl )
+   SUBROUTINE lim_thd_dif( kideb , kiut )
       !!------------------------------------------------------------------
       !!                ***  ROUTINE lim_thd_dif  ***
@@ -74,10 +74,10 @@
       !!
       !! ** Inputs / Ouputs : (global commons)
-      !!           surface temperature : t_su_b
-      !!           ice/snow temperatures   : t_i_b, t_s_b
-      !!           ice salinities          : s_i_b
+      !!           surface temperature : t_su_1d
+      !!           ice/snow temperatures   : t_i_1d, t_s_1d
+      !!           ice salinities          : s_i_1d
       !!           number of layers in the ice/snow: nlay_i, nlay_s
       !!           profile of the ice/snow layers : z_i, z_s
-      !!           total ice/snow thickness : ht_i_b, ht_s_b
+      !!           total ice/snow thickness : ht_i_1d, ht_s_1d
       !!
       !! ** External : 
@@ -91,7 +91,5 @@
       !!           (04-2007) Energy conservation tested by M. Vancoppenolle
       !!------------------------------------------------------------------
-      INTEGER , INTENT (in) ::   kideb   ! Start point on which the  the computation is applied
-      INTEGER , INTENT (in) ::   kiut    ! End point on which the  the computation is applied
-      INTEGER , INTENT (in) ::   jl      ! Category number
+      INTEGER , INTENT(in) ::   kideb, kiut   ! Start/End point on which the  the computation is applied
 
       !! * Local variables
@@ -99,65 +97,84 @@
       INTEGER ::   ii, ij      ! temporary dummy loop index
       INTEGER ::   numeq       ! current reference number of equation
-      INTEGER ::   layer       ! vertical dummy loop index 
+      INTEGER ::   jk       ! vertical dummy loop index 
       INTEGER ::   nconv       ! number of iterations in iterative procedure
       INTEGER ::   minnumeqmin, maxnumeqmax
-      INTEGER, DIMENSION(kiut) ::   numeqmin   ! reference number of top equation
-      INTEGER, DIMENSION(kiut) ::   numeqmax   ! reference number of bottom equation
-      INTEGER, DIMENSION(kiut) ::   isnow      ! switch for presence (1) or absence (0) of snow
+      INTEGER, POINTER, DIMENSION(:) ::   numeqmin   ! reference number of top equation
+      INTEGER, POINTER, DIMENSION(:) ::   numeqmax   ! reference number of bottom equation
+      INTEGER, POINTER, DIMENSION(:) ::   isnow      ! switch for presence (1) or absence (0) of snow
       REAL(wp) ::   zg1s      =  2._wp        ! for the tridiagonal system
       REAL(wp) ::   zg1       =  2._wp        !
       REAL(wp) ::   zgamma    =  18009._wp    ! for specific heat
       REAL(wp) ::   zbeta     =  0.117_wp     ! for thermal conductivity (could be 0.13)
-      REAL(wp) ::   zraext_s  =  1.e+8_wp     ! extinction coefficient of radiation in the snow
+      REAL(wp) ::   zraext_s  =  10._wp       ! extinction coefficient of radiation in the snow
       REAL(wp) ::   zkimin    =  0.10_wp      ! minimum ice thermal conductivity
+      REAL(wp) ::   ztsu_err  =  1.e-5_wp     ! range around which t_su is considered as 0°C 
       REAL(wp) ::   ztmelt_i    ! ice melting temperature
       REAL(wp) ::   zerritmax   ! current maximal error on temperature 
-      REAL(wp), DIMENSION(kiut) ::   ztfs        ! ice melting point
-      REAL(wp), DIMENSION(kiut) ::   ztsuold     ! old surface temperature (before the iterative procedure )
-      REAL(wp), DIMENSION(kiut) ::   ztsuoldit   ! surface temperature at previous iteration
-      REAL(wp), DIMENSION(kiut) ::   zh_i        ! ice layer thickness
-      REAL(wp), DIMENSION(kiut) ::   zh_s        ! snow layer thickness
-      REAL(wp), DIMENSION(kiut) ::   zfsw        ! solar radiation absorbed at the surface
-      REAL(wp), DIMENSION(kiut) ::   zf          ! surface flux function
-      REAL(wp), DIMENSION(kiut) ::   dzf         ! derivative of the surface flux function
-      REAL(wp), DIMENSION(kiut) ::   zerrit      ! current error on temperature
-      REAL(wp), DIMENSION(kiut) ::   zdifcase    ! case of the equation resolution (1->4)
-      REAL(wp), DIMENSION(kiut) ::   zftrice     ! solar radiation transmitted through the ice
-      REAL(wp), DIMENSION(kiut) ::   zihic, zhsu
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   ztcond_i    ! Ice thermal conductivity
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   zradtr_i    ! Radiation transmitted through the ice
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   zradab_i    ! Radiation absorbed in the ice
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   zkappa_i    ! Kappa factor in the ice
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   ztiold      ! Old temperature in the ice
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   zeta_i      ! Eta factor in the ice
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   ztitemp     ! Temporary temperature in the ice to check the convergence
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   zspeche_i   ! Ice specific heat
-      REAL(wp), DIMENSION(kiut,0:nlay_i) ::   z_i         ! Vertical cotes of the layers in the ice
-      REAL(wp), DIMENSION(kiut,0:nlay_s) ::   zradtr_s    ! Radiation transmited through the snow
-      REAL(wp), DIMENSION(kiut,0:nlay_s) ::   zradab_s    ! Radiation absorbed in the snow
-      REAL(wp), DIMENSION(kiut,0:nlay_s) ::   zkappa_s    ! Kappa factor in the snow
-      REAL(wp), DIMENSION(kiut,0:nlay_s) ::   zeta_s       ! Eta factor in the snow
-      REAL(wp), DIMENSION(kiut,0:nlay_s) ::   ztstemp      ! Temporary temperature in the snow to check the convergence
-      REAL(wp), DIMENSION(kiut,0:nlay_s) ::   ztsold       ! Temporary temperature in the snow
-      REAL(wp), DIMENSION(kiut,0:nlay_s) ::   z_s          ! Vertical cotes of the layers in the snow
-      REAL(wp), DIMENSION(kiut,jkmax+2) ::   zindterm   ! Independent term
-      REAL(wp), DIMENSION(kiut,jkmax+2) ::   zindtbis   ! temporary independent term
-      REAL(wp), DIMENSION(kiut,jkmax+2) ::   zdiagbis
-      REAL(wp), DIMENSION(kiut,jkmax+2,3) ::   ztrid   ! tridiagonal system terms
+      REAL(wp), POINTER, DIMENSION(:) ::   ztfs        ! ice melting point
+      REAL(wp), POINTER, DIMENSION(:) ::   ztsub       ! old surface temperature (before the iterative procedure )
+      REAL(wp), POINTER, DIMENSION(:) ::   ztsubit     ! surface temperature at previous iteration
+      REAL(wp), POINTER, DIMENSION(:) ::   zh_i        ! ice layer thickness
+      REAL(wp), POINTER, DIMENSION(:) ::   zh_s        ! snow layer thickness
+      REAL(wp), POINTER, DIMENSION(:) ::   zfsw        ! solar radiation absorbed at the surface
+      REAL(wp), POINTER, DIMENSION(:) ::   zf          ! surface flux function
+      REAL(wp), POINTER, DIMENSION(:) ::   dzf         ! derivative of the surface flux function
+      REAL(wp), POINTER, DIMENSION(:) ::   zerrit      ! current error on temperature
+      REAL(wp), POINTER, DIMENSION(:) ::   zdifcase    ! case of the equation resolution (1->4)
+      REAL(wp), POINTER, DIMENSION(:) ::   zftrice     ! solar radiation transmitted through the ice
+      REAL(wp), POINTER, DIMENSION(:) ::   zihic, zhsu
+      REAL(wp), POINTER, DIMENSION(:,:) ::   ztcond_i    ! Ice thermal conductivity
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zradtr_i    ! Radiation transmitted through the ice
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zradab_i    ! Radiation absorbed in the ice
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zkappa_i    ! Kappa factor in the ice
+      REAL(wp), POINTER, DIMENSION(:,:) ::   ztib        ! Old temperature in the ice
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zeta_i      ! Eta factor in the ice
+      REAL(wp), POINTER, DIMENSION(:,:) ::   ztitemp     ! Temporary temperature in the ice to check the convergence
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zspeche_i   ! Ice specific heat
+      REAL(wp), POINTER, DIMENSION(:,:) ::   z_i         ! Vertical cotes of the layers in the ice
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zradtr_s    ! Radiation transmited through the snow
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zradab_s    ! Radiation absorbed in the snow
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zkappa_s    ! Kappa factor in the snow
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zeta_s      ! Eta factor in the snow
+      REAL(wp), POINTER, DIMENSION(:,:) ::   ztstemp     ! Temporary temperature in the snow to check the convergence
+      REAL(wp), POINTER, DIMENSION(:,:) ::   ztsb        ! Temporary temperature in the snow
+      REAL(wp), POINTER, DIMENSION(:,:) ::   z_s         ! Vertical cotes of the layers in the snow
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zswiterm    ! Independent term
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zswitbis    ! temporary independent term
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zdiagbis
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztrid     ! tridiagonal system terms
+      ! diag errors on heat
+      REAL(wp), POINTER, DIMENSION(:) :: zdq, zq_ini, zhfx_err
       !!------------------------------------------------------------------     
       ! 
+      CALL wrk_alloc( jpij, numeqmin, numeqmax, isnow )
+      CALL wrk_alloc( jpij, ztfs, ztsub, ztsubit, zh_i, zh_s, zfsw )
+      CALL wrk_alloc( jpij, zf, dzf, zerrit, zdifcase, zftrice, zihic, zhsu )
+      CALL wrk_alloc( jpij, nlay_i+1, ztcond_i, zradtr_i, zradab_i, zkappa_i, ztib, zeta_i, ztitemp, z_i, zspeche_i, kjstart=0)
+      CALL wrk_alloc( jpij, nlay_s+1,           zradtr_s, zradab_s, zkappa_s, ztsb, zeta_s, ztstemp, z_s, kjstart=0)
+      CALL wrk_alloc( jpij, nlay_i+3, zswiterm, zswitbis, zdiagbis  )
+      CALL wrk_alloc( jpij, nlay_i+3, 3, ztrid )
+
+      CALL wrk_alloc( jpij, zdq, zq_ini, zhfx_err )
+
+      ! --- diag error on heat diffusion - PART 1 --- !
+      zdq(:) = 0._wp ; zq_ini(:) = 0._wp      
+      DO ji = kideb, kiut
+         zq_ini(ji) = ( SUM( q_i_1d(ji,1:nlay_i) ) * ht_i_1d(ji) / REAL( nlay_i ) +  &
+            &           SUM( q_s_1d(ji,1:nlay_s) ) * ht_s_1d(ji) / REAL( nlay_s ) ) 
+      END DO
+
       !------------------------------------------------------------------------------!
       ! 1) Initialization                                                            !
       !------------------------------------------------------------------------------!
-      !
+      ! clem clean: replace just ztfs by rtt
       DO ji = kideb , kiut
          ! is there snow or not
-         isnow(ji)= NINT(  1._wp - MAX( 0._wp , SIGN(1._wp, - ht_s_b(ji) ) )  )
+         isnow(ji)= NINT(  1._wp - MAX( 0._wp , SIGN(1._wp, - ht_s_1d(ji) ) )  )
          ! surface temperature of fusion
-!!gm ???  ztfs(ji) = rtt !!!????
          ztfs(ji) = REAL( isnow(ji) ) * rtt + REAL( 1 - isnow(ji) ) * rtt
          ! layer thickness
-         zh_i(ji) = ht_i_b(ji) / REAL( nlay_i )
-         zh_s(ji) = ht_s_b(ji) / REAL( nlay_s )
+         zh_i(ji) = ht_i_1d(ji) / REAL( nlay_i )
+         zh_s(ji) = ht_s_1d(ji) / REAL( nlay_s )
       END DO
 
@@ -169,13 +186,13 @@
       z_i(:,0) = 0._wp   ! vert. coord. of the up. lim. of the 1st ice layer
 
-      DO layer = 1, nlay_s            ! vert. coord of the up. lim. of the layer-th snow layer
-         DO ji = kideb , kiut
-            z_s(ji,layer) = z_s(ji,layer-1) + ht_s_b(ji) / REAL( nlay_s )
-         END DO
-      END DO
-
-      DO layer = 1, nlay_i            ! vert. coord of the up. lim. of the layer-th ice layer
-         DO ji = kideb , kiut
-            z_i(ji,layer) = z_i(ji,layer-1) + ht_i_b(ji) / REAL( nlay_i )
+      DO jk = 1, nlay_s            ! vert. coord of the up. lim. of the layer-th snow layer
+         DO ji = kideb , kiut
+            z_s(ji,jk) = z_s(ji,jk-1) + ht_s_1d(ji) / REAL( nlay_s )
+         END DO
+      END DO
+
+      DO jk = 1, nlay_i            ! vert. coord of the up. lim. of the layer-th ice layer
+         DO ji = kideb , kiut
+            z_i(ji,jk) = z_i(ji,jk-1) + ht_i_1d(ji) / REAL( nlay_i )
          END DO
       END DO
@@ -194,12 +211,12 @@
       ! zfsw    = (1-i0).qsr_ice   is absorbed at the surface 
       ! zftrice = io.qsr_ice       is below the surface 
-      ! fstbif  = io.qsr_ice.exp(-k(h_i)) transmitted below the ice 
+      ! ftr_ice = io.qsr_ice.exp(-k(h_i)) transmitted below the ice 
 
       DO ji = kideb , kiut
          ! switches
-         isnow(ji) = NINT(  1._wp - MAX( 0._wp , SIGN( 1._wp , - ht_s_b(ji) ) )  ) 
+         isnow(ji) = NINT(  1._wp - MAX( 0._wp , SIGN( 1._wp , - ht_s_1d(ji) ) )  ) 
          ! hs > 0, isnow = 1
          zhsu (ji) = hnzst  ! threshold for the computation of i0
-         zihic(ji) = MAX( 0._wp , 1._wp - ( ht_i_b(ji) / zhsu(ji) ) )     
+         zihic(ji) = MAX( 0._wp , 1._wp - ( ht_i_1d(ji) / zhsu(ji) ) )     
 
          i0(ji)    = REAL( 1 - isnow(ji) ) * ( fr1_i0_1d(ji) + zihic(ji) * fr2_i0_1d(ji) )
@@ -208,5 +225,5 @@
          !            a function of the cloud cover
          !
-         !i0(ji)     =  (1.0-FLOAT(isnow(ji)))*3.0/(100*ht_s_b(ji)+10.0)
+         !i0(ji)     =  (1.0-FLOAT(isnow(ji)))*3.0/(100*ht_s_1d(ji)+10.0)
          !formula used in Cice
       END DO
@@ -230,10 +247,10 @@
       END DO
 
-      DO layer = 1, nlay_s          ! Radiation through snow
+      DO jk = 1, nlay_s          ! Radiation through snow
          DO ji = kideb, kiut
             !                             ! radiation transmitted below the layer-th snow layer
-            zradtr_s(ji,layer) = zradtr_s(ji,0) * EXP( - zraext_s * ( MAX ( 0._wp , z_s(ji,layer) ) ) )
+            zradtr_s(ji,jk) = zradtr_s(ji,0) * EXP( - zraext_s * ( MAX ( 0._wp , z_s(ji,jk) ) ) )
             !                             ! radiation absorbed by the layer-th snow layer
-            zradab_s(ji,layer) = zradtr_s(ji,layer-1) - zradtr_s(ji,layer)
+            zradab_s(ji,jk) = zradtr_s(ji,jk-1) - zradtr_s(ji,jk)
          END DO
       END DO
@@ -243,30 +260,15 @@
       END DO
 
-      DO layer = 1, nlay_i          ! Radiation through ice
+      DO jk = 1, nlay_i          ! Radiation through ice
          DO ji = kideb, kiut
             !                             ! radiation transmitted below the layer-th ice layer
-            zradtr_i(ji,layer) = zradtr_i(ji,0) * EXP( - kappa_i * ( MAX ( 0._wp , z_i(ji,layer) ) ) )
+            zradtr_i(ji,jk) = zradtr_i(ji,0) * EXP( - kappa_i * ( MAX ( 0._wp , z_i(ji,jk) ) ) )
             !                             ! radiation absorbed by the layer-th ice layer
-            zradab_i(ji,layer) = zradtr_i(ji,layer-1) - zradtr_i(ji,layer)
+            zradab_i(ji,jk) = zradtr_i(ji,jk-1) - zradtr_i(ji,jk)
          END DO
       END DO
 
       DO ji = kideb, kiut           ! Radiation transmitted below the ice
-         fstbif_1d(ji) = fstbif_1d(ji) + iatte_1d(ji) * zradtr_i(ji,nlay_i) * a_i_b(ji) / at_i_b(ji) ! clem modif
-      END DO
-
-      ! +++++
-      ! just to check energy conservation
-      DO ji = kideb, kiut
-         ii = MOD( npb(ji) - 1 , jpi ) + 1
-         ij =    ( npb(ji) - 1 ) / jpi + 1
-         fstroc(ii,ij,jl) = iatte_1d(ji) * zradtr_i(ji,nlay_i) ! clem modif
-      END DO
-      ! +++++
-
-      DO layer = 1, nlay_i
-         DO ji = kideb, kiut
-            radab(ji,layer) = zradab_i(ji,layer)
-         END DO
+         ftr_ice_1d(ji) = zradtr_i(ji,nlay_i) 
       END DO
 
@@ -277,19 +279,19 @@
       !
       DO ji = kideb, kiut        ! Old surface temperature
-         ztsuold  (ji) =  t_su_b(ji)                              ! temperature at the beg of iter pr.
-         ztsuoldit(ji) =  t_su_b(ji)                              ! temperature at the previous iter
-         t_su_b   (ji) =  MIN( t_su_b(ji), ztfs(ji)-0.00001 )     ! necessary
+         ztsub  (ji) =  t_su_1d(ji)                              ! temperature at the beg of iter pr.
+         ztsubit(ji) =  t_su_1d(ji)                              ! temperature at the previous iter
+         t_su_1d   (ji) =  MIN( t_su_1d(ji), ztfs(ji) - ztsu_err )  ! necessary
          zerrit   (ji) =  1000._wp                                ! initial value of error
       END DO
 
-      DO layer = 1, nlay_s       ! Old snow temperature
-         DO ji = kideb , kiut
-            ztsold(ji,layer) =  t_s_b(ji,layer)
-         END DO
-      END DO
-
-      DO layer = 1, nlay_i       ! Old ice temperature
-         DO ji = kideb , kiut
-            ztiold(ji,layer) =  t_i_b(ji,layer)
+      DO jk = 1, nlay_s       ! Old snow temperature
+         DO ji = kideb , kiut
+            ztsb(ji,jk) =  t_s_1d(ji,jk)
+         END DO
+      END DO
+
+      DO jk = 1, nlay_i       ! Old ice temperature
+         DO ji = kideb , kiut
+            ztib(ji,jk) =  t_i_1d(ji,jk)
          END DO
       END DO
@@ -308,12 +310,12 @@
          IF( thcon_i_swi == 0 ) THEN      ! Untersteiner (1964) formula
             DO ji = kideb , kiut
-               ztcond_i(ji,0)        = rcdic + zbeta*s_i_b(ji,1) / MIN(-epsi10,t_i_b(ji,1)-rtt)
+               ztcond_i(ji,0)        = rcdic + zbeta*s_i_1d(ji,1) / MIN(-epsi10,t_i_1d(ji,1)-rtt)
                ztcond_i(ji,0)        = MAX(ztcond_i(ji,0),zkimin)
             END DO
-            DO layer = 1, nlay_i-1
+            DO jk = 1, nlay_i-1
                DO ji = kideb , kiut
-                  ztcond_i(ji,layer) = rcdic + zbeta*( s_i_b(ji,layer) + s_i_b(ji,layer+1) ) /  &
-                     MIN(-2.0_wp * epsi10, t_i_b(ji,layer)+t_i_b(ji,layer+1) - 2.0_wp * rtt)
-                  ztcond_i(ji,layer) = MAX(ztcond_i(ji,layer),zkimin)
+                  ztcond_i(ji,jk) = rcdic + zbeta*( s_i_1d(ji,jk) + s_i_1d(ji,jk+1) ) /  &
+                     MIN(-2.0_wp * epsi10, t_i_1d(ji,jk)+t_i_1d(ji,jk+1) - 2.0_wp * rtt)
+                  ztcond_i(ji,jk) = MAX(ztcond_i(ji,jk),zkimin)
                END DO
             END DO
@@ -322,19 +324,20 @@
          IF( thcon_i_swi == 1 ) THEN      ! Pringle et al formula included: 2.11 + 0.09 S/T - 0.011.T
             DO ji = kideb , kiut
-               ztcond_i(ji,0) = rcdic + 0.090_wp * s_i_b(ji,1) / MIN( -epsi10, t_i_b(ji,1)-rtt )   &
-                  &                   - 0.011_wp * ( t_i_b(ji,1) - rtt )  
+               ztcond_i(ji,0) = rcdic + 0.090_wp * s_i_1d(ji,1) / MIN( -epsi10, t_i_1d(ji,1)-rtt )   &
+                  &                   - 0.011_wp * ( t_i_1d(ji,1) - rtt )  
                ztcond_i(ji,0) = MAX( ztcond_i(ji,0), zkimin )
             END DO
-            DO layer = 1, nlay_i-1
+            DO jk = 1, nlay_i-1
                DO ji = kideb , kiut
-                  ztcond_i(ji,layer) = rcdic + 0.090_wp * ( s_i_b(ji,layer) + s_i_b(ji,layer+1) )   &
-                     &                                  / MIN(-2.0_wp * epsi10, t_i_b(ji,layer)+t_i_b(ji,layer+1) - 2.0_wp * rtt)   &
-                     &                       - 0.0055_wp* ( t_i_b(ji,layer) + t_i_b(ji,layer+1) - 2.0*rtt )  
-                  ztcond_i(ji,layer) = MAX( ztcond_i(ji,layer), zkimin )
+                  ztcond_i(ji,jk) = rcdic +                                                                     & 
+                     &                 0.090_wp * ( s_i_1d(ji,jk) + s_i_1d(ji,jk+1) )                          &
+                     &                 / MIN(-2.0_wp * epsi10, t_i_1d(ji,jk)+t_i_1d(ji,jk+1) - 2.0_wp * rtt)   &
+                     &               - 0.0055_wp* ( t_i_1d(ji,jk) + t_i_1d(ji,jk+1) - 2.0*rtt )  
+                  ztcond_i(ji,jk) = MAX( ztcond_i(ji,jk), zkimin )
                END DO
             END DO
             DO ji = kideb , kiut
-               ztcond_i(ji,nlay_i) = rcdic + 0.090_wp * s_i_b(ji,nlay_i) / MIN(-epsi10,t_bo_b(ji)-rtt)   &
-                  &                        - 0.011_wp * ( t_bo_b(ji) - rtt )  
+               ztcond_i(ji,nlay_i) = rcdic + 0.090_wp * s_i_1d(ji,nlay_i) / MIN(-epsi10,t_bo_1d(ji)-rtt)   &
+                  &                        - 0.011_wp * ( t_bo_1d(ji) - rtt )  
                ztcond_i(ji,nlay_i) = MAX( ztcond_i(ji,nlay_i), zkimin )
             END DO
@@ -352,15 +355,15 @@
          END DO
 
-         DO layer = 1, nlay_s-1
-            DO ji = kideb , kiut
-               zkappa_s(ji,layer)  = 2.0 * rcdsn / &
+         DO jk = 1, nlay_s-1
+            DO ji = kideb , kiut
+               zkappa_s(ji,jk)  = 2.0 * rcdsn / &
                   MAX(epsi10,2.0*zh_s(ji))
             END DO
          END DO
 
-         DO layer = 1, nlay_i-1
+         DO jk = 1, nlay_i-1
             DO ji = kideb , kiut
                !-- Ice kappa factors
-               zkappa_i(ji,layer)  = 2.0*ztcond_i(ji,layer)/ &
+               zkappa_i(ji,jk)  = 2.0*ztcond_i(ji,jk)/ &
                   MAX(epsi10,2.0*zh_i(ji)) 
             END DO
@@ -381,18 +384,18 @@
          !------------------------------------------------------------------------------|
          !
-         DO layer = 1, nlay_i
-            DO ji = kideb , kiut
-               ztitemp(ji,layer)   = t_i_b(ji,layer)
-               zspeche_i(ji,layer) = cpic + zgamma*s_i_b(ji,layer)/ &
-                  MAX((t_i_b(ji,layer)-rtt)*(ztiold(ji,layer)-rtt),epsi10)
-               zeta_i(ji,layer)    = rdt_ice / MAX(rhoic*zspeche_i(ji,layer)*zh_i(ji), &
+         DO jk = 1, nlay_i
+            DO ji = kideb , kiut
+               ztitemp(ji,jk)   = t_i_1d(ji,jk)
+               zspeche_i(ji,jk) = cpic + zgamma*s_i_1d(ji,jk)/ &
+                  MAX((t_i_1d(ji,jk)-rtt)*(ztib(ji,jk)-rtt),epsi10)
+               zeta_i(ji,jk)    = rdt_ice / MAX(rhoic*zspeche_i(ji,jk)*zh_i(ji), &
                   epsi10)
             END DO
          END DO
 
-         DO layer = 1, nlay_s
-            DO ji = kideb , kiut
-               ztstemp(ji,layer) = t_s_b(ji,layer)
-               zeta_s(ji,layer)  = rdt_ice / MAX(rhosn*cpic*zh_s(ji),epsi10)
+         DO jk = 1, nlay_s
+            DO ji = kideb , kiut
+               ztstemp(ji,jk) = t_s_1d(ji,jk)
+               zeta_s(ji,jk)  = rdt_ice / MAX(rhosn*cpic*zh_s(ji),epsi10)
             END DO
          END DO
@@ -402,15 +405,17 @@
          !------------------------------------------------------------------------------|
          !
-         DO ji = kideb , kiut
-
-            ! update of the non solar flux according to the update in T_su
-            qnsr_ice_1d(ji) = qnsr_ice_1d(ji) + dqns_ice_1d(ji) * & 
-               ( t_su_b(ji) - ztsuoldit(ji) )
-
+         IF( .NOT. lk_cpl ) THEN   !--- forced atmosphere case
+            DO ji = kideb , kiut
+               ! update of the non solar flux according to the update in T_su
+               qns_ice_1d(ji) = qns_ice_1d(ji) + dqns_ice_1d(ji) * ( t_su_1d(ji) - ztsubit(ji) )
+            END DO
+         ENDIF
+
+         ! Update incoming flux
+         DO ji = kideb , kiut
             ! update incoming flux
             zf(ji)    =   zfsw(ji)              & ! net absorbed solar radiation
-               + qnsr_ice_1d(ji)           ! non solar total flux 
+               + qns_ice_1d(ji)                   ! non solar total flux 
             ! (LWup, LWdw, SH, LH)
-
          END DO
 
@@ -427,11 +432,11 @@
          !!ice interior terms (top equation has the same form as the others)
 
-         DO numeq=1,jkmax+2
+         DO numeq=1,nlay_i+3
             DO ji = kideb , kiut
                ztrid(ji,numeq,1) = 0.
                ztrid(ji,numeq,2) = 0.
                ztrid(ji,numeq,3) = 0.
-               zindterm(ji,numeq)= 0.
-               zindtbis(ji,numeq)= 0.
+               zswiterm(ji,numeq)= 0.
+               zswitbis(ji,numeq)= 0.
                zdiagbis(ji,numeq)= 0.
             ENDDO
@@ -440,11 +445,11 @@
          DO numeq = nlay_s + 2, nlay_s + nlay_i 
             DO ji = kideb , kiut
-               layer              = numeq - nlay_s - 1
-               ztrid(ji,numeq,1)  =  - zeta_i(ji,layer)*zkappa_i(ji,layer-1)
-               ztrid(ji,numeq,2)  =  1.0 + zeta_i(ji,layer)*(zkappa_i(ji,layer-1) + &
-                  zkappa_i(ji,layer))
-               ztrid(ji,numeq,3)  =  - zeta_i(ji,layer)*zkappa_i(ji,layer)
-               zindterm(ji,numeq) =  ztiold(ji,layer) + zeta_i(ji,layer)* &
-                  zradab_i(ji,layer)
+               jk              = numeq - nlay_s - 1
+               ztrid(ji,numeq,1)  =  - zeta_i(ji,jk)*zkappa_i(ji,jk-1)
+               ztrid(ji,numeq,2)  =  1.0 + zeta_i(ji,jk)*(zkappa_i(ji,jk-1) + &
+                  zkappa_i(ji,jk))
+               ztrid(ji,numeq,3)  =  - zeta_i(ji,jk)*zkappa_i(ji,jk)
+               zswiterm(ji,numeq) =  ztib(ji,jk) + zeta_i(ji,jk)* &
+                  zradab_i(ji,jk)
             END DO
          ENDDO
@@ -457,12 +462,12 @@
                +  zkappa_i(ji,nlay_i-1) )
             ztrid(ji,numeq,3)  =  0.0
-            zindterm(ji,numeq) =  ztiold(ji,nlay_i) + zeta_i(ji,nlay_i)* &
+            zswiterm(ji,numeq) =  ztib(ji,nlay_i) + zeta_i(ji,nlay_i)* &
                ( zradab_i(ji,nlay_i) + zkappa_i(ji,nlay_i)*zg1 &
-               *  t_bo_b(ji) ) 
+               *  t_bo_1d(ji) ) 
          ENDDO
 
 
          DO ji = kideb , kiut
-            IF ( ht_s_b(ji).gt.0.0 ) THEN
+            IF ( ht_s_1d(ji).gt.0.0 ) THEN
                !
                !------------------------------------------------------------------------------|
@@ -472,11 +477,11 @@
                !!snow interior terms (bottom equation has the same form as the others)
                DO numeq = 3, nlay_s + 1
-                  layer =  numeq - 1
-                  ztrid(ji,numeq,1)   =  - zeta_s(ji,layer)*zkappa_s(ji,layer-1)
-                  ztrid(ji,numeq,2)   =  1.0 + zeta_s(ji,layer)*( zkappa_s(ji,layer-1) + &
-                     zkappa_s(ji,layer) )
-                  ztrid(ji,numeq,3)   =  - zeta_s(ji,layer)*zkappa_s(ji,layer)
-                  zindterm(ji,numeq)  =  ztsold(ji,layer) + zeta_s(ji,layer)* &
-                     zradab_s(ji,layer)
+                  jk =  numeq - 1
+                  ztrid(ji,numeq,1)   =  - zeta_s(ji,jk)*zkappa_s(ji,jk-1)
+                  ztrid(ji,numeq,2)   =  1.0 + zeta_s(ji,jk)*( zkappa_s(ji,jk-1) + &
+                     zkappa_s(ji,jk) )
+                  ztrid(ji,numeq,3)   =  - zeta_s(ji,jk)*zkappa_s(ji,jk)
+                  zswiterm(ji,numeq)  =  ztsb(ji,jk) + zeta_s(ji,jk)* &
+                     zradab_s(ji,jk)
                END DO
 
@@ -484,9 +489,9 @@
                IF ( nlay_i.eq.1 ) THEN
                   ztrid(ji,nlay_s+2,3)    =  0.0
-                  zindterm(ji,nlay_s+2)   =  zindterm(ji,nlay_s+2) + zkappa_i(ji,1)* &
-                     t_bo_b(ji) 
+                  zswiterm(ji,nlay_s+2)   =  zswiterm(ji,nlay_s+2) + zkappa_i(ji,1)* &
+                     t_bo_1d(ji) 
                ENDIF
 
-               IF ( t_su_b(ji) .LT. rtt ) THEN
+               IF ( t_su_1d(ji) .LT. rtt ) THEN
 
                   !------------------------------------------------------------------------------|
@@ -501,5 +506,5 @@
                   ztrid(ji,1,2) = dzf(ji) - zg1s*zkappa_s(ji,0)
                   ztrid(ji,1,3) = zg1s*zkappa_s(ji,0)
-                  zindterm(ji,1) = dzf(ji)*t_su_b(ji)   - zf(ji)
+                  zswiterm(ji,1) = dzf(ji)*t_su_1d(ji)   - zf(ji)
 
                   !!first layer of snow equation
@@ -507,5 +512,5 @@
                   ztrid(ji,2,2)  =  1.0 + zeta_s(ji,1)*(zkappa_s(ji,1) + zkappa_s(ji,0)*zg1s)
                   ztrid(ji,2,3)  =  - zeta_s(ji,1)* zkappa_s(ji,1)
-                  zindterm(ji,2) =  ztsold(ji,1) + zeta_s(ji,1)*zradab_s(ji,1)
+                  zswiterm(ji,2) =  ztsb(ji,1) + zeta_s(ji,1)*zradab_s(ji,1)
 
                ELSE 
@@ -524,7 +529,7 @@
                      zkappa_s(ji,0) * zg1s )
                   ztrid(ji,2,3)  =  - zeta_s(ji,1)*zkappa_s(ji,1) 
-                  zindterm(ji,2) = ztsold(ji,1) + zeta_s(ji,1) *            &
+                  zswiterm(ji,2) = ztsb(ji,1) + zeta_s(ji,1) *            &
                      ( zradab_s(ji,1) +                         &
-                     zkappa_s(ji,0) * zg1s * t_su_b(ji) ) 
+                     zkappa_s(ji,0) * zg1s * t_su_1d(ji) ) 
                ENDIF
             ELSE
@@ -534,5 +539,5 @@
                !------------------------------------------------------------------------------|
                !
-               IF (t_su_b(ji) .LT. rtt) THEN
+               IF (t_su_1d(ji) .LT. rtt) THEN
                   !
                   !------------------------------------------------------------------------------|
@@ -548,5 +553,5 @@
                   ztrid(ji,numeqmin(ji),2)   =  dzf(ji) - zkappa_i(ji,0)*zg1    
                   ztrid(ji,numeqmin(ji),3)   =  zkappa_i(ji,0)*zg1
-                  zindterm(ji,numeqmin(ji))  =  dzf(ji)*t_su_b(ji) - zf(ji)
+                  zswiterm(ji,numeqmin(ji))  =  dzf(ji)*t_su_1d(ji) - zf(ji)
 
                   !!first layer of ice equation
@@ -555,5 +560,5 @@
                      + zkappa_i(ji,0) * zg1 )
                   ztrid(ji,numeqmin(ji)+1,3) =  - zeta_i(ji,1)*zkappa_i(ji,1)  
-                  zindterm(ji,numeqmin(ji)+1)=  ztiold(ji,1) + zeta_i(ji,1)*zradab_i(ji,1)  
+                  zswiterm(ji,numeqmin(ji)+1)=  ztib(ji,1) + zeta_i(ji,1)*zradab_i(ji,1)  
 
                   !!case of only one layer in the ice (surface & ice equations are altered)
@@ -568,6 +573,6 @@
                      ztrid(ji,numeqmin(ji)+1,3)  =  0.0
 
-                     zindterm(ji,numeqmin(ji)+1) =  ztiold(ji,1) + zeta_i(ji,1)* &
-                        ( zradab_i(ji,1) + zkappa_i(ji,1)*t_bo_b(ji) )
+                     zswiterm(ji,numeqmin(ji)+1) =  ztib(ji,1) + zeta_i(ji,1)* &
+                        ( zradab_i(ji,1) + zkappa_i(ji,1)*t_bo_1d(ji) )
                   ENDIF
 
@@ -588,6 +593,6 @@
                      zg1)  
                   ztrid(ji,numeqmin(ji),3)      =  - zeta_i(ji,1) * zkappa_i(ji,1)
-                  zindterm(ji,numeqmin(ji))     =  ztiold(ji,1) + zeta_i(ji,1)*( zradab_i(ji,1) + &
-                     zkappa_i(ji,0) * zg1 * t_su_b(ji) ) 
+                  zswiterm(ji,numeqmin(ji))     =  ztib(ji,1) + zeta_i(ji,1)*( zradab_i(ji,1) + &
+                     zkappa_i(ji,0) * zg1 * t_su_1d(ji) ) 
 
                   !!case of only one layer in the ice (surface & ice equations are altered)
@@ -597,7 +602,7 @@
                         zkappa_i(ji,1))
                      ztrid(ji,numeqmin(ji),3)  =  0.0
-                     zindterm(ji,numeqmin(ji)) =  ztiold(ji,1) + zeta_i(ji,1)* &
-                        (zradab_i(ji,1) + zkappa_i(ji,1)*t_bo_b(ji)) &
-                        + t_su_b(ji)*zeta_i(ji,1)*zkappa_i(ji,0)*2.0
+                     zswiterm(ji,numeqmin(ji)) =  ztib(ji,1) + zeta_i(ji,1)* &
+                        (zradab_i(ji,1) + zkappa_i(ji,1)*t_bo_1d(ji)) &
+                        + t_su_1d(ji)*zeta_i(ji,1)*zkappa_i(ji,0)*2.0
                   ENDIF
 
@@ -618,8 +623,8 @@
 
          maxnumeqmax = 0
-         minnumeqmin = jkmax+4
-
-         DO ji = kideb , kiut
-            zindtbis(ji,numeqmin(ji)) =  zindterm(ji,numeqmin(ji))
+         minnumeqmin = nlay_i+5
+
+         DO ji = kideb , kiut
+            zswitbis(ji,numeqmin(ji)) =  zswiterm(ji,numeqmin(ji))
             zdiagbis(ji,numeqmin(ji)) =  ztrid(ji,numeqmin(ji),2)
             minnumeqmin               =  MIN(numeqmin(ji),minnumeqmin)
@@ -627,11 +632,11 @@
          END DO
 
-         DO layer = minnumeqmin+1, maxnumeqmax
-            DO ji = kideb , kiut
-               numeq               =  min(max(numeqmin(ji)+1,layer),numeqmax(ji))
+         DO jk = minnumeqmin+1, maxnumeqmax
+            DO ji = kideb , kiut
+               numeq               =  min(max(numeqmin(ji)+1,jk),numeqmax(ji))
                zdiagbis(ji,numeq)  =  ztrid(ji,numeq,2) - ztrid(ji,numeq,1)* &
                   ztrid(ji,numeq-1,3)/zdiagbis(ji,numeq-1)
-               zindtbis(ji,numeq)  =  zindterm(ji,numeq) - ztrid(ji,numeq,1)* &
-                  zindtbis(ji,numeq-1)/zdiagbis(ji,numeq-1)
+               zswitbis(ji,numeq)  =  zswiterm(ji,numeq) - ztrid(ji,numeq,1)* &
+                  zswitbis(ji,numeq-1)/zdiagbis(ji,numeq-1)
             END DO
          END DO
@@ -639,12 +644,12 @@
          DO ji = kideb , kiut
             ! ice temperatures
-            t_i_b(ji,nlay_i)    =  zindtbis(ji,numeqmax(ji))/zdiagbis(ji,numeqmax(ji))
+            t_i_1d(ji,nlay_i)    =  zswitbis(ji,numeqmax(ji))/zdiagbis(ji,numeqmax(ji))
          END DO
 
          DO numeq = nlay_i + nlay_s + 1, nlay_s + 2, -1
             DO ji = kideb , kiut
-               layer    =  numeq - nlay_s - 1
-               t_i_b(ji,layer)  =  (zindtbis(ji,numeq) - ztrid(ji,numeq,3)* &
-                  t_i_b(ji,layer+1))/zdiagbis(ji,numeq)
+               jk    =  numeq - nlay_s - 1
+               t_i_1d(ji,jk)  =  (zswitbis(ji,numeq) - ztrid(ji,numeq,3)* &
+                  t_i_1d(ji,jk+1))/zdiagbis(ji,numeq)
             END DO
          END DO
@@ -652,15 +657,15 @@
          DO ji = kideb , kiut
             ! snow temperatures      
-            IF (ht_s_b(ji).GT.0._wp) &
-               t_s_b(ji,nlay_s)     =  (zindtbis(ji,nlay_s+1) - ztrid(ji,nlay_s+1,3) &
-               *  t_i_b(ji,1))/zdiagbis(ji,nlay_s+1) &
-               *        MAX(0.0,SIGN(1.0,ht_s_b(ji))) 
+            IF (ht_s_1d(ji).GT.0._wp) &
+               t_s_1d(ji,nlay_s)     =  (zswitbis(ji,nlay_s+1) - ztrid(ji,nlay_s+1,3) &
+               *  t_i_1d(ji,1))/zdiagbis(ji,nlay_s+1) &
+               *        MAX(0.0,SIGN(1.0,ht_s_1d(ji))) 
 
             ! surface temperature
-            isnow(ji)     = NINT(  1.0 - MAX( 0.0 , SIGN( 1.0 , -ht_s_b(ji) )  )  )
-            ztsuoldit(ji) = t_su_b(ji)
-            IF( t_su_b(ji) < ztfs(ji) ) &
-               t_su_b(ji) = ( zindtbis(ji,numeqmin(ji)) - ztrid(ji,numeqmin(ji),3)* ( REAL( isnow(ji) )*t_s_b(ji,1)   &
-               &          + REAL( 1 - isnow(ji) )*t_i_b(ji,1) ) ) / zdiagbis(ji,numeqmin(ji))  
+            isnow(ji)     = NINT(  1.0 - MAX( 0.0 , SIGN( 1.0 , -ht_s_1d(ji) )  )  )
+            ztsubit(ji) = t_su_1d(ji)
+            IF( t_su_1d(ji) < ztfs(ji) ) &
+               t_su_1d(ji) = ( zswitbis(ji,numeqmin(ji)) - ztrid(ji,numeqmin(ji),3)* ( REAL( isnow(ji) )*t_s_1d(ji,1)   &
+               &          + REAL( 1 - isnow(ji) )*t_i_1d(ji,1) ) ) / zdiagbis(ji,numeqmin(ji))  
          END DO
          !
@@ -672,22 +677,20 @@
          ! zerrit(ji) is a measure of error, it has to be under maxer_i_thd
          DO ji = kideb , kiut
-            t_su_b(ji) =  MAX(  MIN( t_su_b(ji) , ztfs(ji) ) , 190._wp  )
-            zerrit(ji) =  ABS( t_su_b(ji) - ztsuoldit(ji) )     
-         END DO
-
-         DO layer  =  1, nlay_s
-            DO ji = kideb , kiut
-               ii = MOD( npb(ji) - 1, jpi ) + 1
-               ij = ( npb(ji) - 1 ) / jpi + 1
-               t_s_b(ji,layer) = MAX(  MIN( t_s_b(ji,layer), rtt ), 190._wp  )
-               zerrit(ji)      = MAX(zerrit(ji),ABS(t_s_b(ji,layer) - ztstemp(ji,layer)))
-            END DO
-         END DO
-
-         DO layer  =  1, nlay_i
-            DO ji = kideb , kiut
-               ztmelt_i        = -tmut * s_i_b(ji,layer) + rtt 
-               t_i_b(ji,layer) =  MAX(MIN(t_i_b(ji,layer),ztmelt_i), 190._wp)
-               zerrit(ji)      =  MAX(zerrit(ji),ABS(t_i_b(ji,layer) - ztitemp(ji,layer)))
+            t_su_1d(ji) =  MAX(  MIN( t_su_1d(ji) , ztfs(ji) ) , 190._wp  )
+            zerrit(ji) =  ABS( t_su_1d(ji) - ztsubit(ji) )     
+         END DO
+
+         DO jk  =  1, nlay_s
+            DO ji = kideb , kiut
+               t_s_1d(ji,jk) = MAX(  MIN( t_s_1d(ji,jk), rtt ), 190._wp  )
+               zerrit(ji)      = MAX(zerrit(ji),ABS(t_s_1d(ji,jk) - ztstemp(ji,jk)))
+            END DO
+         END DO
+
+         DO jk  =  1, nlay_i
+            DO ji = kideb , kiut
+               ztmelt_i        = -tmut * s_i_1d(ji,jk) + rtt 
+               t_i_1d(ji,jk) =  MAX(MIN(t_i_1d(ji,jk),ztmelt_i), 190._wp)
+               zerrit(ji)      =  MAX(zerrit(ji),ABS(t_i_1d(ji,jk) - ztitemp(ji,jk)))
             END DO
          END DO
@@ -713,45 +716,103 @@
       !-------------------------------------------------------------------------!
       DO ji = kideb, kiut
-#if ! defined key_coupled
          ! forced mode only : update of latent heat fluxes (sublimation) (always >=0, upward flux) 
-         qla_ice_1d (ji) = MAX( 0._wp, qla_ice_1d (ji) + dqla_ice_1d(ji) * ( t_su_b(ji) - ztsuold(ji) ) )
-#endif
+         IF( .NOT. lk_cpl) qla_ice_1d (ji) = MAX( 0._wp, qla_ice_1d (ji) + dqla_ice_1d(ji) * ( t_su_1d(ji) - ztsub(ji) ) )
          !                                ! surface ice conduction flux
-         isnow(ji)       = NINT(  1._wp - MAX( 0._wp, SIGN( 1._wp, -ht_s_b(ji) ) )  )
-         fc_su(ji)       =  -     REAL( isnow(ji) ) * zkappa_s(ji,0) * zg1s * (t_s_b(ji,1) - t_su_b(ji))   &
-            &               - REAL( 1 - isnow(ji) ) * zkappa_i(ji,0) * zg1  * (t_i_b(ji,1) - t_su_b(ji))
+         isnow(ji)       = NINT(  1._wp - MAX( 0._wp, SIGN( 1._wp, -ht_s_1d(ji) ) )  )
+         fc_su(ji)       =  -     REAL( isnow(ji) ) * zkappa_s(ji,0) * zg1s * (t_s_1d(ji,1) - t_su_1d(ji))   &
+            &               - REAL( 1 - isnow(ji) ) * zkappa_i(ji,0) * zg1  * (t_i_1d(ji,1) - t_su_1d(ji))
          !                                ! bottom ice conduction flux
-         fc_bo_i(ji)     =  - zkappa_i(ji,nlay_i) * ( zg1*(t_bo_b(ji) - t_i_b(ji,nlay_i)) )
-      END DO
-
-      !-------------------------!
-      ! Heat conservation       !
-      !-------------------------!
-      IF( con_i .AND. jiindex_1d > 0 ) THEN
+         fc_bo_i(ji)     =  - zkappa_i(ji,nlay_i) * ( zg1*(t_bo_1d(ji) - t_i_1d(ji,nlay_i)) )
+      END DO
+
+      !-----------------------------------------
+      ! Heat flux used to warm/cool ice in W.m-2
+      !-----------------------------------------
+      DO ji = kideb, kiut
+         IF( t_su_1d(ji) < rtt ) THEN  ! case T_su < 0degC
+            hfx_dif_1d(ji) = hfx_dif_1d(ji)  +   &
+               &            ( qns_ice_1d(ji) + qsr_ice_1d(ji) - zradtr_i(ji,nlay_i) - fc_bo_i(ji) ) * a_i_1d(ji)
+         ELSE                         ! case T_su = 0degC
+            hfx_dif_1d(ji) = hfx_dif_1d(ji) +    &
+               &             ( fc_su(ji) + i0(ji) * qsr_ice_1d(ji) - zradtr_i(ji,nlay_i) - fc_bo_i(ji) ) * a_i_1d(ji)
+         ENDIF
+      END DO
+
+      ! --- computes sea ice energy of melting compulsory for limthd_dh --- !
+      CALL lim_thd_enmelt( kideb, kiut )
+
+      ! --- diag conservation imbalance on heat diffusion - PART 2 --- !
+      DO ji = kideb, kiut
+         zdq(ji)        = - zq_ini(ji) + ( SUM( q_i_1d(ji,1:nlay_i) ) * ht_i_1d(ji) / REAL( nlay_i ) +  &
+            &                              SUM( q_s_1d(ji,1:nlay_s) ) * ht_s_1d(ji) / REAL( nlay_s ) )
+         zhfx_err(ji)   = ( fc_su(ji) + i0(ji) * qsr_ice_1d(ji) - zradtr_i(ji,nlay_i) - fc_bo_i(ji) + zdq(ji) * r1_rdtice ) 
+         hfx_err_1d(ji) = hfx_err_1d(ji) + zhfx_err(ji) * a_i_1d(ji)
+      END DO 
+
+      ! diagnose external surface (forced case) or bottom (forced case) from heat conservation
+      IF( .NOT. lk_cpl ) THEN   ! --- forced case: qns_ice and fc_su are diagnosed
+         !
          DO ji = kideb, kiut
-            ! Upper snow value
-            fc_s(ji,0) = - REAL( isnow(ji) ) * zkappa_s(ji,0) * zg1s * ( t_s_b(ji,1) - t_su_b(ji) ) 
-            ! Bott. snow value
-            fc_s(ji,1) = - REAL( isnow(ji) ) * zkappa_s(ji,1) * ( t_i_b(ji,1) - t_s_b(ji,1) ) 
-         END DO
-         DO ji = kideb, kiut         ! Upper ice layer
-            fc_i(ji,0) = - REAL( isnow(ji) ) * &  ! interface flux if there is snow
-               ( zkappa_i(ji,0)  * ( t_i_b(ji,1) - t_s_b(ji,nlay_s ) ) ) &
-               - REAL( 1 - isnow(ji) ) * ( zkappa_i(ji,0) * & 
-               zg1 * ( t_i_b(ji,1) - t_su_b(ji) ) ) ! upper flux if not
-         END DO
-         DO layer = 1, nlay_i - 1         ! Internal ice layers
-            DO ji = kideb, kiut
-               fc_i(ji,layer) = - zkappa_i(ji,layer) * ( t_i_b(ji,layer+1) - t_i_b(ji,layer) )
-               ii = MOD( npb(ji) - 1, jpi ) + 1
-               ij = ( npb(ji) - 1 ) / jpi + 1
-            END DO
-         END DO
-         DO ji = kideb, kiut         ! Bottom ice layers
-            fc_i(ji,nlay_i) = - zkappa_i(ji,nlay_i) * ( zg1*(t_bo_b(ji) - t_i_b(ji,nlay_i)) )
-         END DO
+            qns_ice_1d(ji) = qns_ice_1d(ji) - zhfx_err(ji)
+            fc_su     (ji) = fc_su(ji)      - zhfx_err(ji)
+         END DO
+         !
+      ELSE                      ! --- coupled case: ocean turbulent heat flux is diagnosed
+         !
+         DO ji = kideb, kiut
+            fhtur_1d  (ji) = fhtur_1d(ji)   - zhfx_err(ji)
+         END DO
+         !
       ENDIF
+
+      ! --- compute diagnostic net heat flux at the surface of the snow-ice system (W.m2)
+      DO ji = kideb, kiut
+         ii = MOD( npb(ji) - 1, jpi ) + 1 ; ij = ( npb(ji) - 1 ) / jpi + 1
+         hfx_in (ii,ij) = hfx_in (ii,ij) + a_i_1d(ji) * ( qsr_ice_1d(ji) + qns_ice_1d(ji) )
+      END DO
+   
       !
+      CALL wrk_dealloc( jpij, numeqmin, numeqmax, isnow )
+      CALL wrk_dealloc( jpij, ztfs, ztsub, ztsubit, zh_i, zh_s, zfsw )
+      CALL wrk_dealloc( jpij, zf, dzf, zerrit, zdifcase, zftrice, zihic, zhsu )
+      CALL wrk_dealloc( jpij, nlay_i+1, ztcond_i, zradtr_i, zradab_i, zkappa_i,   &
+         &              ztib, zeta_i, ztitemp, z_i, zspeche_i, kjstart = 0 )
+      CALL wrk_dealloc( jpij, nlay_s+1,           zradtr_s, zradab_s, zkappa_s, ztsb, zeta_s, ztstemp, z_s, kjstart = 0 )
+      CALL wrk_dealloc( jpij, nlay_i+3, zswiterm, zswitbis, zdiagbis )
+      CALL wrk_dealloc( jpij, nlay_i+3, 3, ztrid )
+      CALL wrk_dealloc( jpij, zdq, zq_ini, zhfx_err )
+
    END SUBROUTINE lim_thd_dif
+
+   SUBROUTINE lim_thd_enmelt( kideb, kiut )
+      !!-----------------------------------------------------------------------
+      !!                   ***  ROUTINE lim_thd_enmelt *** 
+      !!                 
+      !! ** Purpose :   Computes sea ice energy of melting q_i (J.m-3) from temperature
+      !!
+      !! ** Method  :   Formula (Bitz and Lipscomb, 1999)
+      !!-------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kideb, kiut   ! bounds for the spatial loop
+      !
+      INTEGER  ::   ji, jk   ! dummy loop indices
+      REAL(wp) ::   ztmelts  ! local scalar 
+      !!-------------------------------------------------------------------
+      !
+      DO jk = 1, nlay_i             ! Sea ice energy of melting
+         DO ji = kideb, kiut
+            ztmelts      = - tmut  * s_i_1d(ji,jk) + rtt 
+            rswitch      = MAX( 0._wp , SIGN( 1._wp , -(t_i_1d(ji,jk) - rtt) - epsi10 ) )
+            q_i_1d(ji,jk) = rhoic * ( cpic * ( ztmelts - t_i_1d(ji,jk) )                                             &
+               &                   + lfus * ( 1.0 - rswitch * ( ztmelts-rtt ) / MIN( t_i_1d(ji,jk)-rtt, -epsi10 ) )   &
+               &                   - rcp  *                 ( ztmelts-rtt )  ) 
+         END DO
+      END DO
+      DO jk = 1, nlay_s             ! Snow energy of melting
+         DO ji = kideb, kiut
+            q_s_1d(ji,jk) = rhosn * ( cpic * ( rtt - t_s_1d(ji,jk) ) + lfus )
+         END DO
+      END DO
+      !
+   END SUBROUTINE lim_thd_enmelt
 
 #else
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_ent.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_ent.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_ent.F90	(revision 5075)
@@ -10,5 +10,6 @@
    !!                 ! 2006-11 (X. Fettweis) Vectorized 
    !!            3.0  ! 2008-03 (M. Vancoppenolle) Energy conservation and clean code
-   !!            4.0  ! 2011-02 (G. Madec) dynamical allocation
+   !!            3.4  ! 2011-02 (G. Madec) dynamical allocation
+   !!             -   ! 2014-05 (C. Rousset) complete rewriting
    !!----------------------------------------------------------------------
 #if defined key_lim3
@@ -22,4 +23,5 @@
    USE domain         !
    USE phycst         ! physical constants
+   USE sbc_oce        ! Surface boundary condition: ocean fields
    USE ice            ! LIM variables
    USE par_ice        ! LIM parameters
@@ -34,10 +36,5 @@
    PRIVATE
 
-   PUBLIC   lim_thd_ent         ! called by lim_thd
-
-   REAL(wp) ::   epsi20 = 1.e-20_wp   ! constant values
-   REAL(wp) ::   epsi10 = 1.e-10_wp   !
-   REAL(wp) ::   zzero  = 0._wp      !
-   REAL(wp) ::   zone   = 1._wp      !
+   PUBLIC   lim_thd_ent         ! called by limthd and limthd_lac
 
    !!----------------------------------------------------------------------
@@ -48,12 +45,11 @@
 CONTAINS
  
-   SUBROUTINE lim_thd_ent( kideb, kiut, jl )
+   SUBROUTINE lim_thd_ent( kideb, kiut, qnew )
       !!-------------------------------------------------------------------
       !!               ***   ROUTINE lim_thd_ent  ***
       !!
       !! ** Purpose :
-      !!           This routine computes new vertical grids 
-      !!           in the ice and in the snow, and consistently redistributes 
-      !!           temperatures in the snow / ice. 
+      !!           This routine computes new vertical grids in the ice, 
+      !!           and consistently redistributes temperatures. 
       !!           Redistribution is made so as to ensure to energy conservation
       !!
@@ -61,633 +57,97 @@
       !! ** Method  : linear conservative remapping
       !!           
-      !! ** Steps : 1) Grid
-      !!            2) Switches
-      !!            3) Snow redistribution
-      !!            4) Ice enthalpy redistribution
-      !!            5) Ice salinity, recover temperature
+      !! ** Steps : 1) cumulative integrals of old enthalpies/thicknesses
+      !!            2) linear remapping on the new layers
+      !!
+      !! ------------ cum0(0)                        ------------- cum1(0)
+      !!                                    NEW      -------------
+      !! ------------ cum0(1)               ==>      -------------
+      !!     ...                                     -------------
+      !! ------------                                -------------
+      !! ------------ cum0(nlay_i+2)                 ------------- cum1(nlay_i)
+      !!
       !!
       !! References : Bitz & Lipscomb, JGR 99; Vancoppenolle et al., GRL, 2005
       !!-------------------------------------------------------------------
       INTEGER , INTENT(in) ::   kideb, kiut   ! Start/End point on which the  the computation is applied
-      INTEGER , INTENT(in) ::   jl            ! Thickness cateogry number
 
-      INTEGER ::   ji,jk   !  dummy loop indices
-      INTEGER ::   ii, ij       ,   &  !  dummy indices
-         ntop0          ,   &  !  old layer top index
-         nbot1          ,   &  !  new layer bottom index
-         ntop1          ,   &  !  new layer top index
-         limsum         ,   &  !  temporary loop index
-         nlayi0,nlays0  ,   &  !  old number of layers
-         maxnbot0       ,   &  !  old layer bottom index
-         layer0, layer1        !  old/new layer indexes
+      REAL(wp), INTENT(inout), DIMENSION(:,:) :: qnew          ! new enthlapies (J.m-3, remapped)
 
-
-      REAL(wp) :: &
-         ztmelts        ,   &  ! ice melting point
-         zqsnic         ,   &  ! enthalpy of snow ice layer
-         zhsnow         ,   &  ! temporary snow thickness variable
-         zswitch        ,   &  ! dummy switch argument
-         zfac1          ,   &  ! dummy factor
-         zfac2          ,   &  ! dummy factor
-         ztform         ,   &  !: bottom formation temperature
-         zaaa           ,   &  !: dummy factor
-         zbbb           ,   &  !: dummy factor
-         zccc           ,   &  !: dummy factor
-         zdiscrim              !: dummy factor
-
-      INTEGER, POINTER, DIMENSION(:) ::   snswi     !  snow switch
-      INTEGER, POINTER, DIMENSION(:) ::   nbot0     !  old layer bottom index
-      INTEGER, POINTER, DIMENSION(:) ::   icsuind   !  ice surface index
-      INTEGER, POINTER, DIMENSION(:) ::   icsuswi   !  ice surface switch
-      INTEGER, POINTER, DIMENSION(:) ::   icboind   !  ice bottom index
-      INTEGER, POINTER, DIMENSION(:) ::   icboswi   !  ice bottom switch
-      INTEGER, POINTER, DIMENSION(:) ::   snicind   !  snow ice index
-      INTEGER, POINTER, DIMENSION(:) ::   snicswi   !  snow ice switch
-      INTEGER, POINTER, DIMENSION(:) ::   snind     !  snow index
+      INTEGER  :: ji         !  dummy loop indices
+      INTEGER  :: jk0, jk1   !  old/new layer indices
       !
-      REAL(wp), POINTER, DIMENSION(:) ::   zh_i   ! thickness of an ice layer
-      REAL(wp), POINTER, DIMENSION(:) ::   zh_s          ! thickness of a snow layer
-      REAL(wp), POINTER, DIMENSION(:) ::   zqsnow        ! enthalpy of the snow put in snow ice 	
-      REAL(wp), POINTER, DIMENSION(:) ::   zdeltah       ! temporary variable
-      REAL(wp), POINTER, DIMENSION(:) ::   zqti_in, zqts_in
-      REAL(wp), POINTER, DIMENSION(:) ::   zqti_fin, zqts_fin
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zm0       !  old layer-system vertical cotes 
-      REAL(wp), POINTER, DIMENSION(:,:) ::   qm0       !  old layer-system heat content 
-      REAL(wp), POINTER, DIMENSION(:,:) ::   z_s       !  new snow system vertical cotes 
-      REAL(wp), POINTER, DIMENSION(:,:) ::   z_i       !  new ice system vertical cotes 
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zthick0   !  old ice thickness 
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zhl0      ! old and new layer thicknesses 
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zrl01
-
-      REAL(wp) ::   zinda 
+      REAL(wp), POINTER, DIMENSION(:,:) :: zqh_cum0, zh_cum0   ! old cumulative enthlapies and layers interfaces
+      REAL(wp), POINTER, DIMENSION(:,:) :: zqh_cum1, zh_cum1   ! new cumulative enthlapies and layers interfaces
+      REAL(wp), POINTER, DIMENSION(:)   :: zhnew               ! new layers thicknesses
       !!-------------------------------------------------------------------
 
-      CALL wrk_alloc( jpij, snswi, nbot0, icsuind, icsuswi, icboind, icboswi, snicind, snicswi, snind )   ! integer
-      CALL wrk_alloc( jpij, zh_i, zh_s, zqsnow, zdeltah, zqti_in, zqts_in, zqti_fin, zqts_fin )           ! real
-      CALL wrk_alloc( jpij,jkmax+4, zm0, qm0, z_s, z_i, zthick0, zhl0, kjstart = 0 )
-      CALL wrk_alloc( jkmax+4,jkmax+4, zrl01, kistart = 0, kjstart = 0 )
+      CALL wrk_alloc( jpij, nlay_i+3, zqh_cum0, zh_cum0, kjstart = 0 )
+      CALL wrk_alloc( jpij, nlay_i+1, zqh_cum1, zh_cum1, kjstart = 0 )
+      CALL wrk_alloc( jpij, zhnew )
 
-      zthick0(:,:) = 0._wp
-      zm0    (:,:) = 0._wp
-      qm0    (:,:) = 0._wp
-      zrl01  (:,:) = 0._wp
-      zhl0   (:,:) = 0._wp
-      z_i    (:,:) = 0._wp
-      z_s    (:,:) = 0._wp
-
-      !
-      !------------------------------------------------------------------------------|
-      !  1) Grid                                                                     |
-      !------------------------------------------------------------------------------|
-      nlays0 = nlay_s
-      nlayi0 = nlay_i
-
-      DO ji = kideb, kiut
-         zh_i(ji) = old_ht_i_b(ji) / REAL( nlay_i ) 
-         zh_s(ji) = old_ht_s_b(ji) / REAL( nlay_s )
-      END DO
-
-      !
-      !------------------------------------------------------------------------------|
-      !  2) Switches                                                                 |
-      !------------------------------------------------------------------------------|
-      ! 2.1 snind(ji), snswi(ji)
-      ! snow surface behaviour : computation of snind(ji)-snswi(ji)
-      ! snind(ji) : index which equals 
-      ! 	 0 if snow is accumulating
-      ! 	 1 if 1st layer is melting
-      ! 	 2 if 2nd layer is melting ...
-      DO ji = kideb, kiut
-         snind  (ji) = 0
-         zdeltah(ji) = 0._wp
-      ENDDO !ji
-
-      DO jk = 1, nlays0
+      !--------------------------------------------------------------------------
+      !  1) Cumulative integral of old enthalpy * thicnkess and layers interfaces
+      !--------------------------------------------------------------------------
+      zqh_cum0(:,0:nlay_i+2) = 0._wp 
+      zh_cum0 (:,0:nlay_i+2) = 0._wp
+      DO jk0 = 1, nlay_i+2
          DO ji = kideb, kiut
-            snind(ji)  = jk        *      NINT(MAX(0.0,SIGN(1.0,-dh_s_tot(ji)-zdeltah(ji)))) &
-               + snind(ji) * (1 - NINT(MAX(0.0,SIGN(1.0,-dh_s_tot(ji)-zdeltah(ji)))))
-            zdeltah(ji)= zdeltah(ji) + zh_s(ji)
-         END DO ! ji
-      END DO ! jk
-
-      ! snswi(ji) : switch which value equals 1 if snow melts
-      !				   0 if not
-      DO ji = kideb, kiut
-         snswi(ji)     = MAX(0,NINT(-dh_s_tot(ji)/MAX(epsi20,ABS(dh_s_tot(ji)))))
-      END DO ! ji
-
-      ! 2.2 icsuind(ji), icsuswi(ji)
-      ! ice surface behaviour : computation of icsuind(ji)-icsuswi(ji)
-      ! icsuind(ji) : index which equals
-      !	   0 if nothing happens at the surface
-      !	   1 if first layer is melting
-      !	   2 if 2nd layer is reached by melt ...
-      DO ji = kideb, kiut
-         icsuind(ji) = 0
-         zdeltah(ji) = 0._wp
-      END DO !ji
-      DO jk = 1, nlayi0
-         DO ji = kideb, kiut
-            icsuind(ji) = jk          *      NINT(MAX(0.0,SIGN(1.0,-dh_i_surf(ji)-zdeltah(ji)))) &
-               + icsuind(ji) * (1 - NINT(MAX(0.0,SIGN(1.0,-dh_i_surf(ji)-zdeltah(ji)))))
-            zdeltah(ji) = zdeltah(ji) + zh_i(ji)
-         END DO ! ji
-      ENDDO !jk
-
-      ! icsuswi(ji) : switch which equals 
-      ! 	   1 if ice melts at the surface
-      ! 	   0 if not
-      DO ji = kideb, kiut
-         icsuswi(ji)  = MAX(0,NINT(-dh_i_surf(ji)/MAX(epsi20 , ABS(dh_i_surf(ji)) ) ) )
+            zqh_cum0(ji,jk0) = zqh_cum0(ji,jk0-1) + qh_i_old(ji,jk0-1)
+            zh_cum0 (ji,jk0) = zh_cum0 (ji,jk0-1) + h_i_old (ji,jk0-1)
+         ENDDO
       ENDDO
 
-      ! 2.3 icboind(ji), icboswi(ji)
-      ! ice bottom behaviour : computation of icboind(ji)-icboswi(ji)
-      ! icboind(ji) : index which equals
-      ! 	   0 if accretion is on the way
-      ! 	   1 if last layer has started to melt
-      ! 	   2 if penultiem layer is melting ... and so on
-      !            N+1 if all layers melt and that snow transforms into ice
-      DO ji = kideb, kiut 
-         icboind(ji) = 0
-         zdeltah(ji) = 0._wp
-      END DO
-      DO jk = nlayi0, 1, -1
-         DO ji = kideb, kiut
-            icboind(ji) = (nlayi0+1-jk) *      NINT(MAX(0.0,SIGN(1.0,-dh_i_bott(ji)-zdeltah(ji)))) &
-               &          + icboind(ji) * (1 - NINT(MAX(0.0,SIGN(1.0,-dh_i_bott(ji)-zdeltah(ji))))) 
-            zdeltah(ji) = zdeltah(ji) + zh_i(ji)
-         END DO
-      END DO
-
+      !------------------------------------
+      !  2) Interpolation on the new layers
+      !------------------------------------
+      ! new layer thickesses
       DO ji = kideb, kiut
-         ! case of total ablation with remaining snow
-         IF ( ( ht_i_b(ji) .GT. epsi20 ) .AND. &
-            ( ht_i_b(ji) - dh_snowice(ji) .LT. epsi20 ) ) icboind(ji) = nlay_i + 1
-      END DO
-
-      ! icboswi(ji) : switch which equals 
-      ! 	   1 if ice accretion is on the way
-      ! 	   0 if ablation is on the way
-      DO ji = kideb, kiut 
-         icboswi(ji) = MAX(0,NINT(dh_i_bott(ji) / MAX(epsi20,ABS(dh_i_bott(ji)))))
-      END DO
-
-      ! 2.4 snicind(ji), snicswi(ji)
-      ! snow ice formation : calcul de snicind(ji)-snicswi(ji)
-      ! snicind(ji) : index which equals 
-      ! 	   0 if no snow-ice forms
-      ! 	   1 if last layer of snow has started to melt
-      ! 	   2 if penultiem layer ...
-      DO ji = kideb, kiut
-         snicind(ji) = 0
-         zdeltah(ji) = 0._wp
-      END DO
-      DO jk = nlays0, 1, -1
-         DO ji = kideb, kiut
-            snicind(ji) = (nlays0+1-jk) &
-               *      NINT(MAX(0.0,SIGN(1.0,dh_snowice(ji)-zdeltah(ji)))) + snicind(ji)   &
-               * (1 - NINT(MAX(0.0,SIGN(1.0,dh_snowice(ji)-zdeltah(ji)))))
-            zdeltah(ji) = zdeltah(ji) + zh_s(ji)
-         END DO
-      END DO
-
-      ! snicswi(ji) : switch which equals 
-      ! 	   1 if snow-ice forms
-      ! 	   0 if not
-      DO ji = kideb, kiut
-         snicswi(ji)   = MAX(0,NINT(dh_snowice(ji)/MAX(epsi20,ABS(dh_snowice(ji)))))
+         zhnew(ji) = SUM( h_i_old(ji,0:nlay_i+1) ) / REAL( nlay_i )  
       ENDDO
 
-      !
-      !------------------------------------------------------------------------------|
-      !  3) Snow redistribution                                                      |
-      !------------------------------------------------------------------------------|
-      !
-      !-------------
-      ! Old profile
-      !-------------
-
-      ! by 'old', it is meant that layers coming from accretion are included, 
-      ! and that interfacial layers which were partly melted are reduced 
-
-      ! indexes of the vectors
-      !------------------------
-      ntop0    =  1
-      maxnbot0 =  0
-
-      DO ji = kideb, kiut
-         nbot0(ji) =  nlays0  + 1 - snind(ji) + ( 1 - snicind(ji) ) * snicswi(ji)
-         ! cotes of the top of the layers
-         zm0(ji,0) =  0._wp
-         maxnbot0 =  MAX ( maxnbot0 , nbot0(ji) )
-      END DO
-      IF( lk_mpp )   CALL mpp_max( maxnbot0, kcom=ncomm_ice )
-
-      DO jk = 1, maxnbot0
+      ! new layers interfaces
+      zh_cum1(:,0:nlay_i) = 0._wp
+      DO jk1 = 1, nlay_i
          DO ji = kideb, kiut
-            !change
-            limsum = ( 1 - snswi(ji) ) * ( jk - 1 ) + snswi(ji) * ( jk + snind(ji) - 1 )
-            limsum = MIN( limsum , nlay_s )
-            zm0(ji,jk) =  dh_s_tot(ji) + zh_s(ji) * REAL( limsum )
-         END DO
-      END DO
-
-      DO ji = kideb, kiut
-         zm0(ji,nbot0(ji)) =  dh_s_tot(ji) - REAL( snicswi(ji) ) * dh_snowice(ji) + zh_s(ji) * REAL( nlays0 )
-         zm0(ji,1)         =  dh_s_tot(ji) * REAL( 1 - snswi(ji) ) + REAL( snswi(ji) ) * zm0(ji,1)
-      END DO
-
-      DO jk = ntop0, maxnbot0
-         DO ji = kideb, kiut
-            zthick0(ji,jk)  =  zm0(ji,jk) - zm0(ji,jk-1)            ! layer thickness
-         END DO
-      END DO
-
-      zqts_in(:) = 0._wp
-
-      DO ji = kideb, kiut         ! layer heat content
-         qm0    (ji,1) =  rhosn * (  cpic * ( rtt - REAL( 1 - snswi(ji) ) * tatm_ice_1d(ji)        &
-            &                                         - REAL( snswi(ji) ) * t_s_b      (ji,1)  )   &
-            &                      + lfus  ) * zthick0(ji,1)
-         zqts_in(ji)   =  zqts_in(ji) + qm0(ji,1) 
-      END DO
-
-      DO jk = 2, maxnbot0
-         DO ji = kideb, kiut
-            limsum      = ( 1 - snswi(ji) ) * ( jk - 1 ) + snswi(ji) * ( jk + snind(ji) - 1 )
-            limsum      = MIN( limsum , nlay_s )
-            qm0(ji,jk)  = rhosn * ( cpic * ( rtt - t_s_b(ji,limsum) ) + lfus ) * zthick0(ji,jk)
-            zswitch = 1.0 - MAX (0.0, SIGN ( 1.0, - ht_s_b(ji) ) )
-            zqts_in(ji) = zqts_in(ji) + REAL( 1 - snswi(ji) ) * qm0(ji,jk) * zswitch
-         END DO ! jk
-      END DO ! ji
-
-      !------------------------------------------------
-      ! Energy given by the snow in snow-ice formation
-      !------------------------------------------------
-      ! zqsnow, enthalpy of the flooded snow
-      DO ji = kideb, kiut
-         zqsnow (ji) =  rhosn * lfus
-         zdeltah(ji) =  0._wp
-      END DO
-
-      DO jk =  nlays0, 1, -1
-         DO ji = kideb, kiut
-            zhsnow =  MAX( 0._wp , dh_snowice(ji)-zdeltah(ji) )
-            zqsnow (ji) =  zqsnow (ji) + rhosn*cpic*(rtt-t_s_b(ji,jk))
-            zdeltah(ji) =  zdeltah(ji) + zh_s(ji)
-         END DO
-      END DO
-
-      DO ji = kideb, kiut
-         zqsnow(ji) = zqsnow(ji) * dh_snowice(ji)
-      END DO
-
-      !------------------
-      ! new snow profile
-      !------------------
-
-      !--------------
-      ! Vector index   
-      !--------------
-      ntop1 =  1
-      nbot1 =  nlay_s
-
-      !-------------------
-      ! Layer coordinates 
-      !-------------------
-      DO ji = kideb, kiut
-         zh_s(ji)  = ht_s_b(ji) / REAL( nlay_s )
-         z_s(ji,0) =  0._wp
+            zh_cum1(ji,jk1) = zh_cum1(ji,jk1-1) + zhnew(ji)
+         ENDDO
       ENDDO
 
-      DO jk = 1, nlay_s
+      zqh_cum1(:,0:nlay_i) = 0._wp 
+      ! new cumulative q*h => linear interpolation
+      DO jk0 = 1, nlay_i+1
+         DO jk1 = 1, nlay_i-1
+            DO ji = kideb, kiut
+               IF( zh_cum1(ji,jk1) <= zh_cum0(ji,jk0) .AND. zh_cum1(ji,jk1) > zh_cum0(ji,jk0-1) ) THEN
+                  zqh_cum1(ji,jk1) = ( zqh_cum0(ji,jk0-1) * ( zh_cum0(ji,jk0) - zh_cum1(ji,jk1  ) ) +  &
+                     &                 zqh_cum0(ji,jk0  ) * ( zh_cum1(ji,jk1) - zh_cum0(ji,jk0-1) ) )  &
+                     &             / ( zh_cum0(ji,jk0) - zh_cum0(ji,jk0-1) )
+               ENDIF
+            ENDDO
+         ENDDO
+      ENDDO
+      ! to ensure that total heat content is strictly conserved, set:
+      zqh_cum1(:,nlay_i) = zqh_cum0(:,nlay_i+2) 
+
+      ! new enthalpies
+      DO jk1 = 1, nlay_i
          DO ji = kideb, kiut
-            z_s(ji,jk) =  zh_s(ji) * REAL( jk )
-         END DO
-      END DO
-
-      !-----------------
-      ! Layer thickness
-      !-----------------
-      DO layer0 = ntop0, maxnbot0
-         DO ji = kideb, kiut
-            zhl0(ji,layer0) = zm0(ji,layer0) - zm0(ji,layer0-1)
-         END DO
-      END DO
-
-      DO layer1 = ntop1, nbot1
-         DO ji = kideb, kiut
-            q_s_b(ji,layer1) = 0._wp
-         END DO
-      END DO
-
-      !----------------
-      ! Weight factors
-      !----------------
-      DO layer0 = ntop0, maxnbot0
-         DO layer1 = ntop1, nbot1
-            DO ji = kideb, kiut
-               zinda = MAX( 0._wp, SIGN( 1._wp , zhl0(ji,layer0) - epsi10 ) )
-               zrl01(layer1,layer0) = zinda * MAX(0.0,( MIN(zm0(ji,layer0),z_s(ji,layer1))   &
-                  &                 - MAX(zm0(ji,layer0-1), z_s(ji,layer1-1))) / MAX(zhl0(ji,layer0),epsi10)) 
-               q_s_b(ji,layer1) = q_s_b(ji,layer1) + zrl01(layer1,layer0)*qm0(ji,layer0)   &
-                  &                                * MAX(0.0,SIGN(1.0,REAL(nbot0(ji)-layer0)))
-            END DO
-         END DO
-      END DO
-
-      ! Heat conservation
-      zqts_fin(:) = 0._wp
-      DO jk = 1, nlay_s
-         DO ji = kideb, kiut
-            zqts_fin(ji) = zqts_fin(ji) + q_s_b(ji,jk)
-         END DO
-      END DO
-
-      IF ( con_i .AND. jiindex_1d > 0 ) THEN
-         DO ji = kideb, kiut
-            IF ( ABS ( zqts_in(ji) - zqts_fin(ji) ) * r1_rdtice  >  1.0e-6 ) THEN
-               ii                 = MOD( npb(ji) - 1, jpi ) + 1
-               ij                 = ( npb(ji) - 1 ) / jpi + 1
-               WRITE(numout,*) ' violation of heat conservation : ', ABS ( zqts_in(ji) - zqts_fin(ji) ) * r1_rdtice
-               WRITE(numout,*) ' ji, jj   : ', ii, ij
-               WRITE(numout,*) ' ht_s_b   : ', ht_s_b(ji)
-               WRITE(numout,*) ' zqts_in  : ', zqts_in (ji) * r1_rdtice
-               WRITE(numout,*) ' zqts_fin : ', zqts_fin(ji) * r1_rdtice
-               WRITE(numout,*) ' dh_snowice : ', dh_snowice(ji)
-               WRITE(numout,*) ' dh_s_tot : ', dh_s_tot(ji)
-               WRITE(numout,*) ' snswi    : ', snswi(ji)
-            ENDIF
-         END DO
-      ENDIF
-
-      !---------------------
-      ! Recover heat content
-      !---------------------
-      DO jk = 1, nlay_s
-         DO ji = kideb, kiut
-            zinda = MAX( 0._wp, SIGN( 1._wp , zh_s(ji) - epsi10 ) )        
-            q_s_b(ji,jk) = zinda * q_s_b(ji,jk) / MAX( zh_s(ji) , epsi10 )
-         END DO !ji
-      END DO !jk  
-
-      !---------------------
-      ! Recover temperature
-      !---------------------
-      zfac1 = 1. / ( rhosn * cpic )
-      zfac2 = lfus / cpic  
-      DO jk = 1, nlay_s
-         DO ji = kideb, kiut
-            zswitch = MAX ( 0.0 , SIGN ( 1.0, - ht_s_b(ji) ) )
-            t_s_b(ji,jk) = rtt + ( 1.0 - zswitch ) * ( - zfac1 * q_s_b(ji,jk) + zfac2 )
-         END DO
-      END DO
-      !
-      !------------------------------------------------------------------------------|
-      !  4) Ice redistribution                                                       |
-      !------------------------------------------------------------------------------|
-      !
-      !-------------
-      ! OLD PROFILE 
-      !-------------
-
-      !----------------
-      ! Vector indexes
-      !----------------
-      ntop0    =  1
-      maxnbot0 =  0
-
-      DO ji = kideb, kiut
-         ! reference number of the bottommost layer
-         nbot0(ji) =  MAX( 1 ,  MIN( nlayi0 + ( 1 - icboind(ji) ) +        &
-            &                           ( 1 - icsuind(ji) ) * icsuswi(ji) + snicswi(ji) , nlay_i + 2 ) )
-         ! maximum reference number of the bottommost layer over all domain
-         maxnbot0 =  MAX( maxnbot0 , nbot0(ji) )
-      END DO
-
-      !-------------------------
-      ! Cotes of old ice layers
-      !-------------------------
-      zm0(:,0) =  0._wp
-
-      DO jk = 1, maxnbot0
-         DO ji = kideb, kiut
-            ! jk goes from 1 to nbot0
-            ! the ice layer number goes from 1 to nlay_i
-            ! limsum is the real ice layer number corresponding to present jk
-            limsum    =  ( (icsuswi(ji)*(icsuind(ji)+jk-1) + & 
-               (1-icsuswi(ji))*jk))*(1-snicswi(ji)) + (jk-1)*snicswi(ji)
-            zm0(ji,jk)=  REAL(icsuswi(ji))*dh_i_surf(ji) + REAL(snicswi(ji))*dh_snowice(ji) &
-               +  REAL(limsum) * zh_i(ji)
-         END DO
-      END DO
-
-      DO ji = kideb, kiut
-         zm0(ji,nbot0(ji)) =  REAL(icsuswi(ji))*dh_i_surf(ji) + REAL(snicswi(ji))*dh_snowice(ji) + dh_i_bott(ji) &
-            +  zh_i(ji) * REAL(nlayi0)
-         zm0(ji,1)         =  REAL(snicswi(ji))*dh_snowice(ji) + REAL(1-snicswi(ji))*zm0(ji,1)
-      END DO
-
-      !-----------------------------
-      ! Thickness of old ice layers
-      !-----------------------------
-      DO jk = ntop0, maxnbot0
-         DO ji = kideb, kiut
-            zthick0(ji,jk) =  zm0(ji,jk) - zm0(ji,jk-1)
-         END DO
-      END DO
-
-      !---------------------------
-      ! Inner layers heat content
-      !---------------------------
-      qm0(:,:) =  0.0
-      zqti_in(:) = 0.0
-
-      DO jk = ntop0, maxnbot0
-         DO ji = kideb, kiut
-            limsum =  MAX(1,MIN(snicswi(ji)*(jk-1) + icsuswi(ji)*(jk-1+icsuind(ji)) + &
-               (1-icsuswi(ji))*(1-snicswi(ji))*jk,nlay_i))
-            ztmelts = -tmut * s_i_b(ji,limsum) + rtt
-            qm0(ji,jk) = rhoic * ( cpic * (ztmelts-t_i_b(ji,limsum)) + lfus * ( 1.0-(ztmelts-rtt)/ &
-               MIN((t_i_b(ji,limsum)-rtt),-epsi20) ) - rcp*(ztmelts-rtt) ) &
-               * zthick0(ji,jk)
-         END DO
-      END DO
-
-      !----------------------------
-      ! Bottom layers heat content
-      !----------------------------
-      DO ji = kideb, kiut        
-         ztmelts    = REAL( 1 - icboswi(ji) ) * (-tmut * s_i_b  (ji,nlayi0) )   &   ! case of melting ice
-            &       +     REAL( icboswi(ji) ) * (-tmut * s_i_new(ji)        )   &   ! case of forming ice
-            &       + rtt                                                         ! in Kelvin
-
-         ! bottom formation temperature
-         ztform = t_i_b(ji,nlay_i)
-         IF(  num_sal == 2  )   ztform = t_bo_b(ji)
-         qm0(ji,nbot0(ji)) = REAL( 1 - icboswi(ji) )*qm0(ji,nbot0(ji))             &   ! case of melting ice
-            &              + REAL( icboswi(ji) ) * rhoic * ( cpic*(ztmelts-ztform)       &   ! case of forming ice
-            + lfus *( 1.0-(ztmelts-rtt) / MIN ( (ztform-rtt) , - epsi10 ) )      & 
-            - rcp*(ztmelts-rtt) ) * zthick0(ji,nbot0(ji)  )
-      END DO
-
-      !-----------------------------
-      ! Snow ice layer heat content
-      !-----------------------------
-      DO ji = kideb, kiut
-         ! energy of the flooding seawater
-         zqsnic = rau0 * rcp * ( rtt - t_bo_b(ji) ) * dh_snowice(ji) * &
-            (rhoic - rhosn) / rhoic * REAL(snicswi(ji)) ! generally positive
-         ! Heat conservation diagnostic
-         qt_i_in(ji,jl) = qt_i_in(ji,jl) + zqsnic 
-
-         qldif_1d(ji)   = qldif_1d(ji) + zqsnic * a_i_b(ji)
-
-         ! enthalpy of the newly formed snow-ice layer
-         ! = enthalpy of snow + enthalpy of frozen water
-         zqsnic         =  zqsnow(ji) + zqsnic
-         qm0(ji,1)      =  REAL(snicswi(ji)) * zqsnic + REAL( 1 - snicswi(ji) ) * qm0(ji,1)
-
-      END DO ! ji
-
-      DO jk = ntop0, maxnbot0
-         DO ji = kideb, kiut
-            ! Heat conservation
-            zqti_in(ji) = zqti_in(ji) + qm0(ji,jk) * MAX( 0.0 , SIGN(1.0,ht_i_b(ji)-epsi10) ) &
-               &                                   * MAX( 0.0 , SIGN( 1. , REAL(nbot0(ji) - jk) ) )
-         END DO
-      END DO
-
-      !-------------
-      ! NEW PROFILE
-      !-------------
-
-      !---------------
-      ! Vectors index
-      !---------------
-      ntop1 =  1 
-      nbot1 =  nlay_i
-
-      !------------------
-      ! Layers thickness 
-      !------------------
-      DO ji = kideb, kiut
-         zh_i(ji) = ht_i_b(ji) / REAL( nlay_i )
+            rswitch      = 1._wp - MAX( 0._wp , SIGN( 1._wp , - zhnew(ji) + epsi10 ) ) 
+            qnew(ji,jk1) = rswitch * ( zqh_cum1(ji,jk1) - zqh_cum1(ji,jk1-1) ) / MAX( zhnew(ji), epsi10 )
+         ENDDO
       ENDDO
 
-      !-------------
-      ! Layer cotes      
-      !-------------
-      z_i(:,0) =  0._wp
-      DO jk = 1, nlay_i
-         DO ji = kideb, kiut
-            z_i(ji,jk) =  zh_i(ji) * jk
-         END DO
+      ! --- diag error on heat remapping --- !
+      ! comment: if input h_i_old and qh_i_old are already multiplied by a_i (as in limthd_lac), 
+      ! then we should not (* a_i) again but not important since this is just to check that remap error is ~0
+      DO ji = kideb, kiut
+         hfx_err_rem_1d(ji) = hfx_err_rem_1d(ji) + a_i_1d(ji) * r1_rdtice *  &
+            &               ( SUM( qnew(ji,1:nlay_i) ) * zhnew(ji) - SUM( qh_i_old(ji,0:nlay_i+1) ) ) 
       END DO
-
-      !--thicknesses of the layers
-      DO layer0 = ntop0, maxnbot0
-         DO ji = kideb, kiut
-            zhl0(ji,layer0) = zm0(ji,layer0) - zm0(ji,layer0-1)   ! thicknesses of the layers
-         END DO
-      END DO
-
-      !------------------------
-      ! Weights for relayering
-      !------------------------
-      q_i_b(:,:) = 0._wp
-      DO layer0 = ntop0, maxnbot0
-         DO layer1 = ntop1, nbot1
-            DO ji = kideb, kiut
-               zinda = MAX( 0._wp, SIGN( 1._wp , zhl0(ji,layer0) - epsi10 ) )
-               zrl01(layer1,layer0) = zinda * MAX(0.0,( MIN(zm0(ji,layer0),z_i(ji,layer1)) &
-                  - MAX(zm0(ji,layer0-1), z_i(ji,layer1-1)))/MAX(zhl0(ji,layer0),epsi10))
-               q_i_b(ji,layer1) = q_i_b(ji,layer1) & 
-                  + zrl01(layer1,layer0)*qm0(ji,layer0) &
-                  * MAX(0.0,SIGN(1.0,ht_i_b(ji)-epsi10)) &
-                  * MAX(0.0,SIGN(1.0,REAL(nbot0(ji)-layer0)))
-            END DO
-         END DO
-      END DO
-
-      !-------------------------
-      ! Heat conservation check
-      !-------------------------
-      zqti_fin(:) = 0._wp
-      DO jk = 1, nlay_i
-         DO ji = kideb, kiut
-            zqti_fin(ji) = zqti_fin(ji) + q_i_b(ji,jk)
-         END DO
-      END DO
+      
       !
-      IF ( con_i .AND. jiindex_1d > 0 ) THEN
-         DO ji = kideb, kiut
-            IF ( ABS ( zqti_in(ji) - zqti_fin(ji) ) * r1_rdtice  >  1.0e-6 ) THEN
-               ii                 = MOD( npb(ji) - 1, jpi ) + 1
-               ij                 = ( npb(ji) - 1 ) / jpi + 1
-               WRITE(numout,*) ' violation of heat conservation : ', ABS ( zqti_in(ji) - zqti_fin(ji) ) * r1_rdtice
-               WRITE(numout,*) ' ji, jj   : ', ii, ij
-               WRITE(numout,*) ' ht_i_b   : ', ht_i_b(ji)
-               WRITE(numout,*) ' zqti_in  : ', zqti_in (ji) * r1_rdtice
-               WRITE(numout,*) ' zqti_fin : ', zqti_fin(ji) * r1_rdtice
-               WRITE(numout,*) ' dh_i_bott: ', dh_i_bott(ji)
-               WRITE(numout,*) ' dh_i_surf: ', dh_i_surf(ji)
-               WRITE(numout,*) ' dh_snowice:', dh_snowice(ji)
-               WRITE(numout,*) ' icsuswi  : ', icsuswi(ji)
-               WRITE(numout,*) ' icboswi  : ', icboswi(ji)
-               WRITE(numout,*) ' snicswi  : ', snicswi(ji)
-            ENDIF
-         END DO
-      ENDIF
-
-      !----------------------
-      ! Recover heat content 
-      !----------------------
-      DO jk = 1, nlay_i
-         DO ji = kideb, kiut
-            zinda = MAX( 0._wp, SIGN( 1._wp , zh_i(ji) - epsi10 ) )
-            q_i_b(ji,jk) = zinda * q_i_b(ji,jk) / MAX( zh_i(ji) , epsi10 )
-         END DO !ji
-      END DO !jk  
-
-      ! Heat conservation
-      zqti_fin(:) = 0.0
-      DO jk = 1, nlay_i
-         DO ji = kideb, kiut
-            zqti_fin(ji) = zqti_fin(ji) + q_i_b(ji,jk) * zh_i(ji)
-         END DO
-      END DO
-
-      !
-      !------------------------------------------------------------------------------|
-      !  5) Update salinity and recover temperature                                  |
-      !------------------------------------------------------------------------------|
-      !
-      ! Update salinity (basal entrapment, snow ice formation)
-      DO ji = kideb, kiut
-         sm_i_b(ji) = sm_i_b(ji) + dsm_i_se_1d(ji) + dsm_i_si_1d(ji)
-      END DO !ji
-
-      ! Recover temperature
-      DO jk = 1, nlay_i
-         DO ji = kideb, kiut
-            ztmelts    =  -tmut*s_i_b(ji,jk) + rtt
-            !Conversion q(S,T) -> T (second order equation)
-            zaaa         =  cpic
-            zbbb         =  ( rcp - cpic ) * ( ztmelts - rtt ) + q_i_b(ji,jk) / rhoic - lfus
-            zccc         =  lfus * ( ztmelts - rtt )
-            zdiscrim     =  SQRT( MAX(zbbb*zbbb - 4.0*zaaa*zccc,0.0) )
-            t_i_b(ji,jk) =  rtt - ( zbbb + zdiscrim ) / ( 2.0 *zaaa )
-         END DO !ji
-
-      END DO !jk
-      !
-      CALL wrk_dealloc( jpij, snswi, nbot0, icsuind, icsuswi, icboind, icboswi, snicind, snicswi, snind )   ! integer
-      CALL wrk_dealloc( jpij, zh_i, zh_s, zqsnow, zdeltah, zqti_in, zqts_in, zqti_fin, zqts_fin )           ! real
-      CALL wrk_dealloc( jpij,jkmax+4, zm0, qm0, z_s, z_i, zthick0, zhl0, kjstart = 0 )
-      CALL wrk_dealloc( jkmax+4,jkmax+4, zrl01, kistart = 0, kjstart = 0 )
+      CALL wrk_dealloc( jpij, nlay_i+3, zqh_cum0, zh_cum0, kjstart = 0 )
+      CALL wrk_dealloc( jpij, nlay_i+1, zqh_cum1, zh_cum1, kjstart = 0 )
+      CALL wrk_dealloc( jpij, zhnew )
       !
    END SUBROUTINE lim_thd_ent
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_lac.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_lac.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_lac.F90	(revision 5075)
@@ -29,5 +29,7 @@
    USE lib_mpp        ! MPP library
    USE wrk_nemo       ! work arrays
+   USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+   USE limthd_ent
 
    IMPLICIT NONE
@@ -35,8 +37,4 @@
 
    PUBLIC lim_thd_lac     ! called by lim_thd
-
-   REAL(wp) ::   epsi10 = 1.e-10_wp   !
-   REAL(wp) ::   zzero  = 0._wp      !
-   REAL(wp) ::   zone   = 1._wp      !
 
    !!----------------------------------------------------------------------
@@ -71,16 +69,23 @@
       !!             - Computation of variation of ice volume and mass
       !!             - Computation of frldb after lateral accretion and 
-      !!               update ht_s_b, ht_i_b and tbif_1d(:,:)      
+      !!               update ht_s_1d, ht_i_1d and tbif_1d(:,:)      
       !!------------------------------------------------------------------------
-      INTEGER ::   ji,jj,jk,jl,jm   ! dummy loop indices
-      INTEGER ::   layer, nbpac     ! local integers 
-      INTEGER ::   ii, ij, iter   !   -       -
-      REAL(wp)  ::   ztmelts, zdv, zqold, zfrazb, zweight, zalphai, zindb, zinda, zde  ! local scalars
+      INTEGER ::   ji,jj,jk,jl      ! dummy loop indices
+      INTEGER ::   nbpac            ! local integers 
+      INTEGER ::   ii, ij, iter     !   -       -
+      REAL(wp)  ::   ztmelts, zdv, zfrazb, zweight, zde                         ! local scalars
       REAL(wp) ::   zgamafr, zvfrx, zvgx, ztaux, ztwogp, zf , zhicol_new        !   -      -
       REAL(wp) ::   ztenagm, zvfry, zvgy, ztauy, zvrel2, zfp, zsqcd , zhicrit   !   -      -
       LOGICAL  ::   iterate_frazil   ! iterate frazil ice collection thickness
       CHARACTER (len = 15) :: fieldid
-      !
-      INTEGER , POINTER, DIMENSION(:) ::   zcatac      ! indexes of categories where new ice grows
+
+      REAL(wp) ::   zQm          ! enthalpy exchanged with the ocean (J/m2, >0 towards ocean)
+      REAL(wp) ::   zEi          ! sea ice specific enthalpy (J/kg)
+      REAL(wp) ::   zEw          ! seawater specific enthalpy (J/kg)
+      REAL(wp) ::   zfmdt        ! mass flux x time step (kg/m2, >0 towards ocean)
+     
+      REAL(wp) ::   zv_newfra
+  
+      INTEGER , POINTER, DIMENSION(:) ::   jcat        ! indexes of categories where new ice grows
       REAL(wp), POINTER, DIMENSION(:) ::   zswinew     ! switch for new ice or not
 
@@ -93,56 +98,26 @@
       REAL(wp), POINTER, DIMENSION(:) ::   zdv_res     ! residual volume in case of excessive heat budget
       REAL(wp), POINTER, DIMENSION(:) ::   zda_res     ! residual area in case of excessive heat budget
-      REAL(wp), POINTER, DIMENSION(:) ::   zat_i_ac    ! total ice fraction    
-      REAL(wp), POINTER, DIMENSION(:) ::   zat_i_lev   ! total ice fraction for level ice only (type 1)   
-      REAL(wp), POINTER, DIMENSION(:) ::   zdh_frazb   ! accretion of frazil ice at the ice bottom
-      REAL(wp), POINTER, DIMENSION(:) ::   zvrel_ac    ! relative ice / frazil velocity (1D vector)
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zhice_old   ! previous ice thickness
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zdummy      ! dummy thickness of new ice 
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zdhicbot    ! thickness of new ice which is accreted vertically
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zv_old      ! old volume of ice in category jl
-      REAL(wp), POINTER, DIMENSION(:,:) ::   za_old      ! old area of ice in category jl
-      REAL(wp), POINTER, DIMENSION(:,:) ::   za_i_ac     ! 1-D version of a_i
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zv_i_ac     ! 1-D version of v_i
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zoa_i_ac    ! 1-D version of oa_i
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zsmv_i_ac   ! 1-D version of smv_i
-
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ze_i_ac   !: 1-D version of e_i
-
-      REAL(wp), POINTER, DIMENSION(:) ::   zqbgow    ! heat budget of the open water (negative)
-      REAL(wp), POINTER, DIMENSION(:) ::   zdhex     ! excessively thick accreted sea ice (hlead-hice)
-
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zqm0      ! old layer-system heat content
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zthick0   ! old ice thickness
-
-      REAL(wp), POINTER, DIMENSION(:,:) ::   vt_i_init, vt_i_final   ! ice volume summed over categories
-      REAL(wp), POINTER, DIMENSION(:,:) ::   vt_s_init, vt_s_final   !  snow volume summed over categories
-      REAL(wp), POINTER, DIMENSION(:,:) ::   et_i_init, et_i_final   !  ice energy summed over categories
-      REAL(wp), POINTER, DIMENSION(:,:) ::   et_s_init               !  snow energy summed over categories
+      REAL(wp), POINTER, DIMENSION(:) ::   zat_i_1d    ! total ice fraction    
+      REAL(wp), POINTER, DIMENSION(:) ::   zv_frazb    ! accretion of frazil ice at the ice bottom
+      REAL(wp), POINTER, DIMENSION(:) ::   zvrel_1d    ! relative ice / frazil velocity (1D vector)
+
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zv_b      ! old volume of ice in category jl
+      REAL(wp), POINTER, DIMENSION(:,:) ::   za_b      ! old area of ice in category jl
+      REAL(wp), POINTER, DIMENSION(:,:) ::   za_i_1d   ! 1-D version of a_i
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zv_i_1d   ! 1-D version of v_i
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zoa_i_1d  ! 1-D version of oa_i
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zsmv_i_1d ! 1-D version of smv_i
+
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ze_i_1d   !: 1-D version of e_i
+
       REAL(wp), POINTER, DIMENSION(:,:) ::   zvrel                   ! relative ice / frazil velocity
       !!-----------------------------------------------------------------------!
 
-      CALL wrk_alloc( jpij, zcatac )   ! integer
+      CALL wrk_alloc( jpij, jcat )   ! integer
       CALL wrk_alloc( jpij, zswinew, zv_newice, za_newice, zh_newice, ze_newice, zs_newice, zo_newice )
-      CALL wrk_alloc( jpij, zdv_res, zda_res, zat_i_ac, zat_i_lev, zdh_frazb, zvrel_ac, zqbgow, zdhex )
-      CALL wrk_alloc( jpij,jpl, zhice_old, zdummy, zdhicbot, zv_old, za_old, za_i_ac, zv_i_ac, zoa_i_ac, zsmv_i_ac )
-      CALL wrk_alloc( jpij,jkmax,jpl, ze_i_ac )
-      CALL wrk_alloc( jpij,jkmax+1,jpl, zqm0, zthick0 )
-      CALL wrk_alloc( jpi,jpj, vt_i_init, vt_i_final, vt_s_init, vt_s_final, et_i_init, et_i_final, et_s_init, zvrel )
-
-      et_i_init(:,:) = 0._wp
-      et_s_init(:,:) = 0._wp
-      vt_i_init(:,:) = 0._wp
-      vt_s_init(:,:) = 0._wp
-
-      !------------------------------------------------------------------------------!
-      ! 1) Conservation check and changes in each ice category
-      !------------------------------------------------------------------------------!
-      IF( con_i ) THEN
-         CALL lim_column_sum        ( jpl, v_i          , vt_i_init)
-         CALL lim_column_sum        ( jpl, v_s          , vt_s_init)
-         CALL lim_column_sum_energy ( jpl, nlay_i , e_i , et_i_init)
-         CALL lim_column_sum        ( jpl, e_s(:,:,1,:) , et_s_init)
-      ENDIF
+      CALL wrk_alloc( jpij, zdv_res, zda_res, zat_i_1d, zv_frazb, zvrel_1d )
+      CALL wrk_alloc( jpij,jpl, zv_b, za_b, za_i_1d, zv_i_1d, zoa_i_1d, zsmv_i_1d )
+      CALL wrk_alloc( jpij,nlay_i+1,jpl, ze_i_1d )
+      CALL wrk_alloc( jpi,jpj, zvrel )
 
       !------------------------------------------------------------------------------|
@@ -154,7 +129,8 @@
                DO ji = 1, jpi
                   !Energy of melting q(S,T) [J.m-3]
-                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) / MAX( area(ji,jj) * v_i(ji,jj,jl) ,  epsi10 ) * REAL( nlay_i )
-                  zindb = 1._wp - MAX(  0._wp , SIGN( 1._wp , -v_i(ji,jj,jl) + epsi10 )  )   !0 if no ice and 1 if yes
-                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * unit_fac * zindb
+                  rswitch          = 1._wp - MAX(  0._wp , SIGN( 1._wp , -v_i(ji,jj,jl) + epsi10 )  )   !0 if no ice and 1 if yes
+                  e_i(ji,jj,jk,jl) = rswitch * e_i(ji,jj,jk,jl) &
+                      &   / ( area(ji,jj) * MAX( v_i(ji,jj,jl) ,  epsi10 ) ) * REAL( nlay_i, wp )
+                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * unit_fac
                END DO
             END DO
@@ -179,7 +155,7 @@
 
       ! Default new ice thickness 
-      hicol(:,:) = hiccrit(1)
-
-      IF( fraz_swi == 1._wp ) THEN
+      hicol(:,:) = hiccrit
+
+      IF( fraz_swi == 1 ) THEN
 
          !--------------------
@@ -193,8 +169,7 @@
          zgamafr = 0.03
 
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-
-               IF ( tms(ji,jj) * ( qcmif(ji,jj) - qldif(ji,jj) ) > 0.e0 ) THEN
+         DO jj = 2, jpj
+            DO ji = 2, jpi
+               IF ( qlead(ji,jj) < 0._wp ) THEN
                   !-------------
                   ! Wind stress
@@ -206,11 +181,12 @@
                      &          +   vtau_ice(ji  ,jj  ) * tmv(ji  ,jj  ) ) * 0.5_wp
                   ! Square root of wind stress
-                  ztenagm       =  SQRT( SQRT( ztaux * ztaux + ztauy * ztauy ) )
+                  ztenagm       =  SQRT( SQRT( ztaux**2 + ztauy**2 ) )
 
                   !---------------------
                   ! Frazil ice velocity
                   !---------------------
-                  zvfrx         = zgamafr * zsqcd * ztaux / MAX(ztenagm,epsi10)
-                  zvfry         = zgamafr * zsqcd * ztauy / MAX(ztenagm,epsi10)
+                  rswitch = MAX( 0._wp, SIGN( 1._wp , ztenagm - epsi10 ) )
+                  zvfrx   = rswitch * zgamafr * zsqcd * ztaux / MAX( ztenagm, epsi10 )
+                  zvfry   = rswitch * zgamafr * zsqcd * ztauy / MAX( ztenagm, epsi10 )
 
                   !-------------------
@@ -218,9 +194,7 @@
                   !-------------------
                   ! C-grid ice velocity
-                  zindb = MAX(  0._wp, SIGN( 1._wp , at_i(ji,jj) )  )
-                  zvgx  = zindb * (  u_ice(ji-1,jj  ) * tmu(ji-1,jj  )    &
-                     &             + u_ice(ji,jj    ) * tmu(ji  ,jj  )  ) * 0.5_wp
-                  zvgy  = zindb * (  v_ice(ji  ,jj-1) * tmv(ji  ,jj-1)    &
-                     &             + v_ice(ji,jj    ) * tmv(ji  ,jj  )  ) * 0.5_wp
+                  rswitch = MAX(  0._wp, SIGN( 1._wp , at_i(ji,jj) )  )
+                  zvgx    = rswitch * ( u_ice(ji-1,jj  ) * tmu(ji-1,jj  )  + u_ice(ji,jj) * tmu(ji,jj) ) * 0.5_wp
+                  zvgy    = rswitch * ( v_ice(ji  ,jj-1) * tmv(ji  ,jj-1)  + v_ice(ji,jj) * tmv(ji,jj) ) * 0.5_wp
 
                   !-----------------------------------
@@ -264,4 +238,7 @@
             END DO ! loop on ji ends
          END DO ! loop on jj ends
+      ! 
+      CALL lbc_lnk( zvrel(:,:), 'T', 1. )
+      CALL lbc_lnk( hicol(:,:), 'T', 1. )
 
       ENDIF ! End of computation of frazil ice collection thickness
@@ -276,7 +253,9 @@
       ! This occurs if open water energy budget is negative
       nbpac = 0
+      npac(:) = 0
+      !
       DO jj = 1, jpj
          DO ji = 1, jpi
-            IF ( tms(ji,jj) * ( qcmif(ji,jj) - qldif(ji,jj) )  >  0._wp ) THEN
+            IF ( qlead(ji,jj)  <  0._wp ) THEN
                nbpac = nbpac + 1
                npac( nbpac ) = (jj - 1) * jpi + ji
@@ -290,5 +269,5 @@
          DO ji = mi0(jiindx), mi1(jiindx)
             DO jj = mj0(jjindx), mj1(jjindx)
-               IF ( tms(ji,jj) * ( qcmif(ji,jj) - qldif(ji,jj) )  >  0._wp ) THEN
+               IF ( qlead(ji,jj)  <  0._wp ) THEN
                   jiindex_1d = (jj - 1) * jpi + ji
                ENDIF
@@ -307,22 +286,24 @@
       IF ( nbpac > 0 ) THEN
 
-         CALL tab_2d_1d( nbpac, zat_i_ac  (1:nbpac)     , at_i         , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, zat_i_1d  (1:nbpac)     , at_i         , jpi, jpj, npac(1:nbpac) )
          DO jl = 1, jpl
-            CALL tab_2d_1d( nbpac, za_i_ac  (1:nbpac,jl), a_i  (:,:,jl), jpi, jpj, npac(1:nbpac) )
-            CALL tab_2d_1d( nbpac, zv_i_ac  (1:nbpac,jl), v_i  (:,:,jl), jpi, jpj, npac(1:nbpac) )
-            CALL tab_2d_1d( nbpac, zoa_i_ac (1:nbpac,jl), oa_i (:,:,jl), jpi, jpj, npac(1:nbpac) )
-            CALL tab_2d_1d( nbpac, zsmv_i_ac(1:nbpac,jl), smv_i(:,:,jl), jpi, jpj, npac(1:nbpac) )
+            CALL tab_2d_1d( nbpac, za_i_1d  (1:nbpac,jl), a_i  (:,:,jl), jpi, jpj, npac(1:nbpac) )
+            CALL tab_2d_1d( nbpac, zv_i_1d  (1:nbpac,jl), v_i  (:,:,jl), jpi, jpj, npac(1:nbpac) )
+            CALL tab_2d_1d( nbpac, zoa_i_1d (1:nbpac,jl), oa_i (:,:,jl), jpi, jpj, npac(1:nbpac) )
+            CALL tab_2d_1d( nbpac, zsmv_i_1d(1:nbpac,jl), smv_i(:,:,jl), jpi, jpj, npac(1:nbpac) )
             DO jk = 1, nlay_i
-               CALL tab_2d_1d( nbpac, ze_i_ac(1:nbpac,jk,jl), e_i(:,:,jk,jl) , jpi, jpj, npac(1:nbpac) )
+               CALL tab_2d_1d( nbpac, ze_i_1d(1:nbpac,jk,jl), e_i(:,:,jk,jl) , jpi, jpj, npac(1:nbpac) )
             END DO ! jk
          END DO ! jl
 
-         CALL tab_2d_1d( nbpac, qldif_1d  (1:nbpac)     , qldif  , jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, qcmif_1d  (1:nbpac)     , qcmif  , jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, t_bo_b    (1:nbpac)     , t_bo   , jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, sfx_thd_1d(1:nbpac)     , sfx_thd, jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, rdm_ice_1d(1:nbpac)     , rdm_ice, jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, hicol_b   (1:nbpac)     , hicol  , jpi, jpj, npac(1:nbpac) )
-         CALL tab_2d_1d( nbpac, zvrel_ac  (1:nbpac)     , zvrel  , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, qlead_1d  (1:nbpac)     , qlead  , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, t_bo_1d   (1:nbpac)     , t_bo   , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, sfx_opw_1d(1:nbpac)     , sfx_opw, jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, wfx_opw_1d(1:nbpac)     , wfx_opw, jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, hicol_1d  (1:nbpac)     , hicol  , jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, zvrel_1d  (1:nbpac)     , zvrel  , jpi, jpj, npac(1:nbpac) )
+
+         CALL tab_2d_1d( nbpac, hfx_thd_1d(1:nbpac)     , hfx_thd, jpi, jpj, npac(1:nbpac) )
+         CALL tab_2d_1d( nbpac, hfx_opw_1d(1:nbpac)     , hfx_opw, jpi, jpj, npac(1:nbpac) )
 
          !------------------------------------------------------------------------------!
@@ -330,19 +311,23 @@
          !------------------------------------------------------------------------------!
 
+         !-----------------------------------------
+         ! Keep old ice areas and volume in memory
+         !-----------------------------------------
+         zv_b(1:nbpac,:) = zv_i_1d(1:nbpac,:) 
+         za_b(1:nbpac,:) = za_i_1d(1:nbpac,:)
          !----------------------
          ! Thickness of new ice
          !----------------------
          DO ji = 1, nbpac
-            zh_newice(ji) = hiccrit(1)
-         END DO
-         IF( fraz_swi == 1.0 )   zh_newice(:) = hicol_b(:)
+            zh_newice(ji) = hiccrit
+         END DO
+         IF( fraz_swi == 1 ) zh_newice(1:nbpac) = hicol_1d(1:nbpac)
 
          !----------------------
          ! Salinity of new ice 
          !----------------------
-
          SELECT CASE ( num_sal )
          CASE ( 1 )                    ! Sice = constant 
-            zs_newice(:) = bulk_sal
+            zs_newice(1:nbpac) = bulk_sal
          CASE ( 2 )                    ! Sice = F(z,t) [Vancoppenolle et al (2005)]
             DO ji = 1, nbpac
@@ -352,7 +337,6 @@
             END DO
          CASE ( 3 )                    ! Sice = F(z) [multiyear ice]
-            zs_newice(:) =   2.3
+            zs_newice(1:nbpac) =   2.3
          END SELECT
-
 
          !-------------------------
@@ -362,10 +346,9 @@
          DO ji = 1, nbpac
             ztmelts       = - tmut * zs_newice(ji) + rtt                  ! Melting point (K)
-            ze_newice(ji) =   rhoic * (  cpic * ( ztmelts - t_bo_b(ji) )                             &
-               &                       + lfus * ( 1.0 - ( ztmelts - rtt ) / ( t_bo_b(ji) - rtt ) )   &
+            ze_newice(ji) =   rhoic * (  cpic * ( ztmelts - t_bo_1d(ji) )                             &
+               &                       + lfus * ( 1.0 - ( ztmelts - rtt ) / MIN( t_bo_1d(ji) - rtt, -epsi10 ) )   &
                &                       - rcp  *         ( ztmelts - rtt )  )
-            ze_newice(ji) =   MAX( ze_newice(ji) , 0._wp )    &
-               &          +   MAX(  0.0 , SIGN( 1.0 , - ze_newice(ji) )  ) * rhoic * lfus
          END DO ! ji
+
          !----------------
          ! Age of new ice
@@ -375,39 +358,37 @@
          END DO ! ji
 
-         !--------------------------
-         ! Open water energy budget 
-         !--------------------------
-         DO ji = 1, nbpac
-            zqbgow(ji) = qldif_1d(ji) - qcmif_1d(ji)     !<0
-         END DO ! ji
-
          !-------------------
          ! Volume of new ice
          !-------------------
          DO ji = 1, nbpac
-            zv_newice(ji) = - zqbgow(ji) / ze_newice(ji)
+
+            zEi           = - ze_newice(ji) / rhoic                ! specific enthalpy of forming ice [J/kg]
+
+            zEw           = rcp * ( t_bo_1d(ji) - rt0 )             ! specific enthalpy of seawater at t_bo_1d [J/kg]
+                                                                   ! clem: we suppose we are already at the freezing point (condition qlead<0 is satisfyied) 
+                                                                   
+            zdE           = zEi - zEw                              ! specific enthalpy difference [J/kg]
+                                              
+            zfmdt         = - qlead_1d(ji) / zdE                   ! Fm.dt [kg/m2] (<0) 
+                                                                   ! clem: we use qlead instead of zqld (limthd) because we suppose we are at the freezing point   
+            zv_newice(ji) = - zfmdt / rhoic
+
+            zQm           = zfmdt * zEw                            ! heat to the ocean >0 associated with mass flux  
+
+            ! Contribution to heat flux to the ocean [W.m-2], >0  
+            hfx_thd_1d(ji) = hfx_thd_1d(ji) + zfmdt * zEw * r1_rdtice
+            ! Total heat flux used in this process [W.m-2]  
+            hfx_opw_1d(ji) = hfx_opw_1d(ji) - zfmdt * zdE * r1_rdtice
+            ! mass flux
+            wfx_opw_1d(ji) = wfx_opw_1d(ji) - zv_newice(ji) * rhoic * r1_rdtice
+            ! salt flux
+            sfx_opw_1d(ji) = sfx_opw_1d(ji) - zv_newice(ji) * rhoic * zs_newice(ji) * r1_rdtice
 
             ! A fraction zfrazb of frazil ice is accreted at the ice bottom
-            zfrazb        = ( TANH ( Cfrazb * ( zvrel_ac(ji) - vfrazb ) ) + 1.0 ) * 0.5 * maxfrazb
-            zdh_frazb(ji) =         zfrazb   * zv_newice(ji)
+            rswitch       = 1._wp - MAX( 0._wp, SIGN( 1._wp , - zat_i_1d(ji) ) )
+            zfrazb        = rswitch * ( TANH ( Cfrazb * ( zvrel_1d(ji) - vfrazb ) ) + 1.0 ) * 0.5 * maxfrazb
+            zv_frazb(ji)  =         zfrazb   * zv_newice(ji)
             zv_newice(ji) = ( 1.0 - zfrazb ) * zv_newice(ji)
          END DO
-
-         !------------------------------------
-         ! Diags for energy conservation test
-         !------------------------------------
-         DO ji = 1, nbpac
-            ii = MOD( npac(ji) - 1 , jpi ) + 1
-            ij =    ( npac(ji) - 1 ) / jpi + 1
-            !
-            zde = ze_newice(ji) / unit_fac * area(ii,ij) * zv_newice(ji)
-            !
-            vt_i_init(ii,ij) = vt_i_init(ii,ij) + zv_newice(ji)             ! volume
-            et_i_init(ii,ij) = et_i_init(ii,ij) + zde                       ! Energy
-
-         END DO
-
-         ! keep new ice volume in memory
-         CALL tab_1d_2d( nbpac, v_newice , npac(1:nbpac), zv_newice(1:nbpac) , jpi, jpj )
 
          !-----------------
@@ -415,9 +396,6 @@
          !-----------------
          DO ji = 1, nbpac
-            ii = MOD( npac(ji) - 1 , jpi ) + 1
-            ij =    ( npac(ji) - 1 ) / jpi + 1
             za_newice(ji) = zv_newice(ji) / zh_newice(ji)
-            diag_lat_gr(ii,ij) = diag_lat_gr(ii,ij) + zv_newice(ji) * r1_rdtice ! clem
-         END DO !ji
+         END DO
 
          !------------------------------------------------------------------------------!
@@ -425,18 +403,12 @@
          !------------------------------------------------------------------------------!
 
-         !-----------------------------------------
-         ! Keep old ice areas and volume in memory
-         !-----------------------------------------
-         zv_old(:,:) = zv_i_ac(:,:) 
-         za_old(:,:) = za_i_ac(:,:)
-
-         !-------------------------------------------
-         ! Compute excessive new ice area and volume
-         !-------------------------------------------
+         !------------------------
+         ! 6.1) lateral ice growth
+         !------------------------
          ! If lateral ice growth gives an ice concentration gt 1, then
          ! we keep the excessive volume in memory and attribute it later to bottom accretion
          DO ji = 1, nbpac
-            IF ( za_newice(ji) >  ( amax - zat_i_ac(ji) ) ) THEN
-               zda_res(ji)   = za_newice(ji) - ( amax - zat_i_ac(ji) )
+            IF ( za_newice(ji) >  ( amax - zat_i_1d(ji) ) ) THEN
+               zda_res(ji)   = za_newice(ji) - ( amax - zat_i_1d(ji) )
                zdv_res(ji)   = zda_res  (ji) * zh_newice(ji) 
                za_newice(ji) = za_newice(ji) - zda_res  (ji)
@@ -446,130 +418,63 @@
                zdv_res(ji) = 0._wp
             ENDIF
-         END DO ! ji
-
-         !------------------------------------------------
-         ! Laterally redistribute new ice volume and area
-         !------------------------------------------------
-         zat_i_ac(:) = 0._wp
+         END DO
+
+         ! find which category to fill
+         zat_i_1d(:) = 0._wp
          DO jl = 1, jpl
             DO ji = 1, nbpac
-               IF(  hi_max   (jl-1)  <   zh_newice(ji)   .AND.   &
-                  & zh_newice(ji)    <=  hi_max   (jl)         ) THEN
-                  za_i_ac (ji,jl) = za_i_ac (ji,jl) + za_newice(ji)
-                  zv_i_ac (ji,jl) = zv_i_ac (ji,jl) + zv_newice(ji)
-                  zat_i_ac(ji)    = zat_i_ac(ji)    + za_i_ac  (ji,jl)
-                  zcatac  (ji)    = jl
+               IF( zh_newice(ji) > hi_max(jl-1) .AND. zh_newice(ji) <= hi_max(jl) ) THEN
+                  za_i_1d (ji,jl) = za_i_1d (ji,jl) + za_newice(ji)
+                  zv_i_1d (ji,jl) = zv_i_1d (ji,jl) + zv_newice(ji)
+                  jcat    (ji)    = jl
                ENDIF
-            END DO
-         END DO
-
-         !----------------------------------
-         ! Heat content - lateral accretion
-         !----------------------------------
-         DO ji = 1, nbpac
-            jl = zcatac(ji)                                                           ! categroy in which new ice is put
-            zindb = 1._wp - MAX( 0._wp , SIGN( 1._wp , -za_old(ji,jl) + epsi10 ) )             ! zindb=1 if ice =0 otherwise
-            zhice_old(ji,jl) = zv_old(ji,jl) / MAX( za_old(ji,jl) , epsi10 ) * zindb  ! old ice thickness
-            zdhex    (ji) = MAX( 0._wp , zh_newice(ji) - zhice_old(ji,jl) )           ! difference in thickness
-            zswinew  (ji) = MAX( 0._wp , SIGN( 1._wp , - za_old(ji,jl) + epsi10 ) )   ! ice totally new in jl category
+               zat_i_1d(ji) = zat_i_1d(ji) + za_i_1d  (ji,jl)
+            END DO
+         END DO
+
+         ! Heat content
+         DO ji = 1, nbpac
+            jl = jcat(ji)                                                    ! categroy in which new ice is put
+            zswinew  (ji) = MAX( 0._wp , SIGN( 1._wp , - za_b(ji,jl) ) )   ! 0 if old ice
          END DO
 
          DO jk = 1, nlay_i
             DO ji = 1, nbpac
-               jl = zcatac(ji)
-               zqold   = ze_i_ac(ji,jk,jl) ! [ J.m-3 ]
-               zalphai = MIN( zhice_old(ji,jl) * REAL( jk )     / REAL( nlay_i ), zh_newice(ji) )   &
-                  &    - MIN( zhice_old(ji,jl) * REAL( jk - 1 ) / REAL( nlay_i ), zh_newice(ji) )
-               ze_i_ac(ji,jk,jl) = zswinew(ji) * ze_newice(ji)                                     &
-                  + ( 1.0 - zswinew(ji) ) * ( za_old(ji,jl)  * zqold * zhice_old(ji,jl) / REAL( nlay_i )  &
-                  + za_newice(ji)  * ze_newice(ji) * zalphai                                       &
-                  + za_newice(ji)  * ze_newice(ji) * zdhex(ji) / REAL( nlay_i ) ) / ( ( zv_i_ac(ji,jl) ) / REAL( nlay_i ) )
-            END DO
-         END DO
-
-         !-----------------------------------------------
-         ! Add excessive volume of new ice at the bottom
-         !-----------------------------------------------
-         ! If the ice concentration exceeds 1, the remaining volume of new ice
-         ! is equally redistributed among all ice categories in which there is
-         ! ice
-
-         ! Fraction of level ice
-         jm = 1
-         zat_i_lev(:) = 0._wp
-
-         DO jl = ice_cat_bounds(jm,1), ice_cat_bounds(jm,2)
-            DO ji = 1, nbpac
-               zat_i_lev(ji) = zat_i_lev(ji) + za_i_ac(ji,jl) 
-            END DO
-         END DO
-
-         IF( ln_nicep .AND. jiindex_1d > 0 ) WRITE(numout,*) ' zv_i_ac : ', zv_i_ac(jiindex_1d, 1:jpl)
-         DO jl = ice_cat_bounds(jm,1), ice_cat_bounds(jm,2)
-            DO ji = 1, nbpac
-               zindb = MAX( 0._wp, SIGN( 1._wp , zdv_res(ji) ) )
-               zinda = MAX( 0._wp, SIGN( 1._wp , zat_i_lev(ji) - epsi10 ) )  ! clem
-               zv_i_ac(ji,jl) = zv_i_ac(ji,jl) + zindb * zinda * zdv_res(ji) * za_i_ac(ji,jl) / MAX( zat_i_lev(ji) , epsi10 )
-            END DO
-         END DO
-         IF( ln_nicep .AND. jiindex_1d > 0 )   WRITE(numout,*) ' zv_i_ac : ', zv_i_ac(jiindex_1d, 1:jpl)
-
-         !---------------------------------
-         ! Heat content - bottom accretion
-         !---------------------------------
-         jm = 1
-         DO jl = ice_cat_bounds(jm,1), ice_cat_bounds(jm,2)
-            DO ji = 1, nbpac
-               zindb =  1._wp - MAX( 0._wp , SIGN( 1._wp , - za_i_ac(ji,jl ) + epsi10 ) )       ! zindb=1 if ice =0 otherwise
-               zhice_old(ji,jl) = zv_i_ac(ji,jl) / MAX( za_i_ac(ji,jl) , epsi10 ) * zindb
-               zdhicbot (ji,jl) = zdv_res(ji)    / MAX( za_i_ac(ji,jl) , epsi10 ) * zindb    &
-                  &             +  zindb * zdh_frazb(ji)                               ! frazil ice may coalesce
-               zdummy(ji,jl)    = zv_i_ac(ji,jl) / MAX( za_i_ac(ji,jl) , epsi10 ) * zindb      ! thickness of residual ice
-            END DO
-         END DO
-
-         ! old layers thicknesses and enthalpies
-         DO jl = ice_cat_bounds(jm,1), ice_cat_bounds(jm,2)
+               jl = jcat(ji)
+               rswitch = MAX( 0._wp, SIGN( 1._wp , zv_i_1d(ji,jl) - epsi20 ) )
+               ze_i_1d(ji,jk,jl) = zswinew(ji)   *   ze_newice(ji) +                                                      &
+                  &        ( 1.0 - zswinew(ji) ) * ( ze_newice(ji) * zv_newice(ji) + ze_i_1d(ji,jk,jl) * zv_b(ji,jl) )  &
+                  &        * rswitch / MAX( zv_i_1d(ji,jl), epsi20 )
+            END DO
+         END DO
+
+         !------------------------------------------------
+         ! 6.2) bottom ice growth + ice enthalpy remapping
+         !------------------------------------------------
+         DO jl = 1, jpl
+
+            ! for remapping
+            h_i_old (1:nbpac,0:nlay_i+1) = 0._wp
+            qh_i_old(1:nbpac,0:nlay_i+1) = 0._wp
             DO jk = 1, nlay_i
                DO ji = 1, nbpac
-                  zthick0(ji,jk,jl) =  zhice_old(ji,jl) / REAL( nlay_i )
-                  zqm0   (ji,jk,jl) =  ze_i_ac(ji,jk,jl) * zthick0(ji,jk,jl)
+                  h_i_old (ji,jk) = zv_i_1d(ji,jl) / REAL( nlay_i )
+                  qh_i_old(ji,jk) = ze_i_1d(ji,jk,jl) * h_i_old(ji,jk)
                END DO
             END DO
-         END DO
-!!gm ???  why the previous do loop  if ocerwriten by the following one ?
-         DO jl = ice_cat_bounds(jm,1), ice_cat_bounds(jm,2)
+
+            ! new volumes including lateral/bottom accretion + residual
             DO ji = 1, nbpac
-               zthick0(ji,nlay_i+1,jl) =  zdhicbot(ji,jl)
-               zqm0   (ji,nlay_i+1,jl) =  ze_newice(ji) * zdhicbot(ji,jl)
-            END DO ! ji
-         END DO ! jl
-
-         ! Redistributing energy on the new grid
-         ze_i_ac(:,:,:) = 0._wp
-         DO jl = ice_cat_bounds(jm,1), ice_cat_bounds(jm,2)
-            DO jk = 1, nlay_i
-               DO layer = 1, nlay_i + 1
-                  DO ji = 1, nbpac
-                     zindb =  1._wp -  MAX( 0._wp , SIGN( 1._wp , - za_i_ac(ji,jl) + epsi10 ) ) 
-                     ! Redistributing energy on the new grid
-                     zweight = MAX (  MIN( zhice_old(ji,jl) * REAL( layer ), zdummy(ji,jl) * REAL( jk ) )   &
-                        &    - MAX( zhice_old(ji,jl) * REAL( layer - 1 ) , zdummy(ji,jl) * REAL( jk - 1 ) ) , 0._wp )   &
-                        &    /( MAX(REAL(nlay_i) * zthick0(ji,layer,jl),epsi10) ) * zindb
-                     ze_i_ac(ji,jk,jl) =  ze_i_ac(ji,jk,jl) + zweight * zqm0(ji,layer,jl)  
-                  END DO ! ji
-               END DO ! layer
-            END DO ! jk
-         END DO ! jl
-
-         DO jl = ice_cat_bounds(jm,1), ice_cat_bounds(jm,2)
-            DO jk = 1, nlay_i
-               DO ji = 1, nbpac
-                  zindb =  1._wp -  MAX( 0._wp , SIGN( 1._wp , - zv_i_ac(ji,jl) + epsi10 ) ) 
-                  ze_i_ac(ji,jk,jl) = ze_i_ac(ji,jk,jl)   &
-                     &              / MAX( zv_i_ac(ji,jl) , epsi10) * za_i_ac(ji,jl) * REAL( nlay_i ) * zindb
-               END DO
-            END DO
-         END DO
+               rswitch        = MAX( 0._wp, SIGN( 1._wp , zat_i_1d(ji) - epsi20 ) )
+               zv_newfra      = rswitch * ( zdv_res(ji) + zv_frazb(ji) ) * za_i_1d(ji,jl) / MAX( zat_i_1d(ji) , epsi20 )
+               za_i_1d(ji,jl) = rswitch * za_i_1d(ji,jl)               
+               zv_i_1d(ji,jl) = zv_i_1d(ji,jl) + zv_newfra
+               ! for remapping
+               h_i_old (ji,nlay_i+1) = zv_newfra
+               qh_i_old(ji,nlay_i+1) = ze_newice(ji) * zv_newfra
+            ENDDO
+            ! --- Ice enthalpy remapping --- !
+            CALL lim_thd_ent( 1, nbpac, ze_i_1d(1:nbpac,:,jl) ) 
+         ENDDO
 
          !------------
@@ -578,6 +483,6 @@
          DO jl = 1, jpl
             DO ji = 1, nbpac
-               zindb = 1._wp - MAX( 0._wp , SIGN( 1._wp , - za_i_ac(ji,jl) + epsi10 ) )  ! 0 if no ice and 1 if yes
-               zoa_i_ac(ji,jl)  = za_old(ji,jl) * zoa_i_ac(ji,jl) / MAX( za_i_ac(ji,jl) , epsi10 ) * zindb   
+               rswitch          = 1._wp - MAX( 0._wp , SIGN( 1._wp , - za_i_1d(ji,jl) + epsi20 ) )  ! 0 if no ice and 1 if yes
+               zoa_i_1d(ji,jl)  = za_b(ji,jl) * zoa_i_1d(ji,jl) / MAX( za_i_1d(ji,jl) , epsi20 ) * rswitch   
             END DO 
          END DO   
@@ -586,92 +491,52 @@
          ! Update salinity
          !-----------------
-         !clem IF(  num_sal == 2  ) THEN
-            DO jl = 1, jpl
-               DO ji = 1, nbpac
-                  zindb = 1._wp - MAX( 0._wp , SIGN( 1._wp , - zv_i_ac(ji,jl) + epsi10 ) )  ! 0 if no ice and 1 if yes
-                  zdv   = zv_i_ac(ji,jl) - zv_old(ji,jl)
-                  zsmv_i_ac(ji,jl) = zsmv_i_ac(ji,jl) + zdv * zs_newice(ji) * zindb ! clem modif
-               END DO
-            END DO   
-         !clem ENDIF
-
-         !--------------------------------
-         ! Update mass/salt fluxes (clem)
-         !--------------------------------
          DO jl = 1, jpl
             DO ji = 1, nbpac
-               zindb = 1._wp - MAX( 0._wp , SIGN( 1._wp , - zv_i_ac(ji,jl) + epsi10 ) )  ! 0 if no ice and 1 if yes
-               zdv   = zv_i_ac(ji,jl) - zv_old(ji,jl)
-               rdm_ice_1d(ji) = rdm_ice_1d(ji) + zdv * rhoic * zindb
-               sfx_thd_1d(ji)   =   sfx_thd_1d(ji) - zdv * rhoic * zs_newice(ji) * r1_rdtice * zindb
-           END DO
+               zdv   = zv_i_1d(ji,jl) - zv_b(ji,jl)
+               zsmv_i_1d(ji,jl) = zsmv_i_1d(ji,jl) + zdv * zs_newice(ji)
+            END DO
          END DO
 
          !------------------------------------------------------------------------------!
-         ! 8) Change 2D vectors to 1D vectors 
+         ! 7) Change 2D vectors to 1D vectors 
          !------------------------------------------------------------------------------!
          DO jl = 1, jpl
-            CALL tab_1d_2d( nbpac, a_i (:,:,jl), npac(1:nbpac), za_i_ac (1:nbpac,jl), jpi, jpj )
-            CALL tab_1d_2d( nbpac, v_i (:,:,jl), npac(1:nbpac), zv_i_ac (1:nbpac,jl), jpi, jpj )
-            CALL tab_1d_2d( nbpac, oa_i(:,:,jl), npac(1:nbpac), zoa_i_ac(1:nbpac,jl), jpi, jpj )
-            !clem IF (  num_sal == 2  )   &
-               CALL tab_1d_2d( nbpac, smv_i (:,:,jl), npac(1:nbpac), zsmv_i_ac(1:nbpac,jl) , jpi, jpj )
+            CALL tab_1d_2d( nbpac, a_i (:,:,jl), npac(1:nbpac), za_i_1d (1:nbpac,jl), jpi, jpj )
+            CALL tab_1d_2d( nbpac, v_i (:,:,jl), npac(1:nbpac), zv_i_1d (1:nbpac,jl), jpi, jpj )
+            CALL tab_1d_2d( nbpac, oa_i(:,:,jl), npac(1:nbpac), zoa_i_1d(1:nbpac,jl), jpi, jpj )
+            CALL tab_1d_2d( nbpac, smv_i (:,:,jl), npac(1:nbpac), zsmv_i_1d(1:nbpac,jl) , jpi, jpj )
             DO jk = 1, nlay_i
-               CALL tab_1d_2d( nbpac, e_i(:,:,jk,jl), npac(1:nbpac), ze_i_ac(1:nbpac,jk,jl), jpi, jpj )
-            END DO
-         END DO
-         CALL tab_1d_2d( nbpac, sfx_thd, npac(1:nbpac), sfx_thd_1d(1:nbpac), jpi, jpj )
-         CALL tab_1d_2d( nbpac, rdm_ice, npac(1:nbpac), rdm_ice_1d(1:nbpac), jpi, jpj )
+               CALL tab_1d_2d( nbpac, e_i(:,:,jk,jl), npac(1:nbpac), ze_i_1d(1:nbpac,jk,jl), jpi, jpj )
+            END DO
+         END DO
+         CALL tab_1d_2d( nbpac, sfx_opw, npac(1:nbpac), sfx_opw_1d(1:nbpac), jpi, jpj )
+         CALL tab_1d_2d( nbpac, wfx_opw, npac(1:nbpac), wfx_opw_1d(1:nbpac), jpi, jpj )
+
+         CALL tab_1d_2d( nbpac, hfx_thd, npac(1:nbpac), hfx_thd_1d(1:nbpac), jpi, jpj )
+         CALL tab_1d_2d( nbpac, hfx_opw, npac(1:nbpac), hfx_opw_1d(1:nbpac), jpi, jpj )
          !
       ENDIF ! nbpac > 0
 
       !------------------------------------------------------------------------------!
-      ! 9) Change units for e_i
+      ! 8) Change units for e_i
       !------------------------------------------------------------------------------!    
       DO jl = 1, jpl
-         DO jk = 1, nlay_i          ! heat content in 10^9 Joules
-            e_i(:,:,jk,jl) = e_i(:,:,jk,jl) * area(:,:) * v_i(:,:,jl) / REAL( nlay_i )  / unit_fac 
+         DO jk = 1, nlay_i
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  ! heat content in Joules
+                  e_i(ji,jj,jk,jl) = e_i(ji,jj,jk,jl) * area(ji,jj) * v_i(ji,jj,jl) / ( REAL( nlay_i ,wp ) * unit_fac ) 
+               END DO
+            END DO
          END DO
       END DO
 
-      !------------------------------------------------------------------------------|
-      ! 10) Conservation check and changes in each ice category
-      !------------------------------------------------------------------------------|
-      IF( con_i ) THEN 
-         CALL lim_column_sum (jpl,   v_i, vt_i_final)
-         fieldid = 'v_i, limthd_lac'
-         CALL lim_cons_check (vt_i_init, vt_i_final, 1.0e-6, fieldid) 
-         !
-         CALL lim_column_sum_energy(jpl, nlay_i, e_i, et_i_final)
-         fieldid = 'e_i, limthd_lac'
-         CALL lim_cons_check (et_i_final, et_i_final, 1.0e-3, fieldid) 
-         !
-         CALL lim_column_sum (jpl,   v_s, vt_s_final)
-         fieldid = 'v_s, limthd_lac'
-         CALL lim_cons_check (vt_s_init, vt_s_final, 1.0e-6, fieldid) 
-         !
-         !     CALL lim_column_sum (jpl,   e_s(:,:,1,:) , et_s_init)
-         !     fieldid = 'e_s, limthd_lac'
-         !     CALL lim_cons_check (et_s_init, et_s_final, 1.0e-3, fieldid) 
-         IF( ln_nicep ) THEN
-            DO ji = mi0(jiindx), mi1(jiindx)
-               DO jj = mj0(jjindx), mj1(jjindx)
-                  WRITE(numout,*) ' vt_i_init : ', vt_i_init (ji,jj)
-                  WRITE(numout,*) ' vt_i_final: ', vt_i_final(ji,jj)
-                  WRITE(numout,*) ' et_i_init : ', et_i_init (ji,jj)
-                  WRITE(numout,*) ' et_i_final: ', et_i_final(ji,jj)
-               END DO
-            END DO
-         ENDIF
-         !
-      ENDIF
       !
-      CALL wrk_dealloc( jpij, zcatac )   ! integer
+      CALL wrk_dealloc( jpij, jcat )   ! integer
       CALL wrk_dealloc( jpij, zswinew, zv_newice, za_newice, zh_newice, ze_newice, zs_newice, zo_newice )
-      CALL wrk_dealloc( jpij, zdv_res, zda_res, zat_i_ac, zat_i_lev, zdh_frazb, zvrel_ac, zqbgow, zdhex )
-      CALL wrk_dealloc( jpij,jpl, zhice_old, zdummy, zdhicbot, zv_old, za_old, za_i_ac, zv_i_ac, zoa_i_ac, zsmv_i_ac )
-      CALL wrk_dealloc( jpij,jkmax,jpl, ze_i_ac )
-      CALL wrk_dealloc( jpij,jkmax+1,jpl, zqm0, zthick0 )
-      CALL wrk_dealloc( jpi,jpj, vt_i_init, vt_i_final, vt_s_init, vt_s_final, et_i_init, et_i_final, et_s_init, zvrel )
+      CALL wrk_dealloc( jpij, zdv_res, zda_res, zat_i_1d, zv_frazb, zvrel_1d )
+      CALL wrk_dealloc( jpij,jpl, zv_b, za_b, za_i_1d, zv_i_1d, zoa_i_1d, zsmv_i_1d )
+      CALL wrk_dealloc( jpij,nlay_i+1,jpl, ze_i_1d )
+      CALL wrk_dealloc( jpi,jpj, zvrel )
       !
    END SUBROUTINE lim_thd_lac
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_sal.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_sal.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limthd_sal.F90	(revision 5075)
@@ -53,19 +53,22 @@
       !
       INTEGER  ::   ji, jk     ! dummy loop indices 
-      REAL(wp) ::   zsold, iflush, iaccrbo, igravdr, isnowic, i_ice_switch,  ztmelts   ! local scalars
-      REAL(wp) ::   zaaa, zbbb, zccc, zdiscrim   ! local scalars
-      REAL(wp), POINTER, DIMENSION(:) ::   ze_init, zhiold, zsiold
+      REAL(wp) ::   iflush, igravdr   ! local scalars
       !!---------------------------------------------------------------------
 
-      CALL wrk_alloc( jpij, ze_init, zhiold, zsiold )
-
+      !---------------------------------------------------------
+      !  0) Update ice salinity from snow-ice and bottom growth
+      !---------------------------------------------------------
+      DO ji = kideb, kiut
+         sm_i_1d(ji) = sm_i_1d(ji) + dsm_i_se_1d(ji) + dsm_i_si_1d(ji)
+      END DO
+ 
       !------------------------------------------------------------------------------|
       ! 1) Constant salinity, constant in time                                       |
       !------------------------------------------------------------------------------|
-!!gm comment: if num_sal = 1 s_i_new, s_i_b and sm_i_b can be set to bulk_sal one for all in the initialisation phase !!
+!!gm comment: if num_sal = 1 s_i_new, s_i_1d and sm_i_1d can be set to bulk_sal one for all in the initialisation phase !!
 !!gm           ===>>>   simplification of almost all test on num_sal value
       IF(  num_sal == 1  ) THEN
-            s_i_b  (kideb:kiut,1:nlay_i) =  bulk_sal
-            sm_i_b (kideb:kiut)          =  bulk_sal 
+            s_i_1d (kideb:kiut,1:nlay_i) =  bulk_sal
+            sm_i_1d(kideb:kiut)          =  bulk_sal 
             s_i_new(kideb:kiut)          =  bulk_sal
       ENDIF
@@ -74,24 +77,5 @@
       !  Module 2 : Constant salinity varying in time                                |
       !------------------------------------------------------------------------------|
-
       IF(  num_sal == 2  ) THEN
-
-         !---------------------------------
-         ! Thickness at previous time step
-         !---------------------------------
-         DO ji = kideb, kiut
-            zhiold(ji) = ht_i_b(ji) - dh_i_bott(ji) - dh_snowice(ji) - dh_i_surf(ji)
-            zsiold(ji) = sm_i_b(ji)
-         END DO
-
-         !---------------------
-         ! Global heat content
-         !---------------------
-         ze_init(:)  =  0._wp
-         DO jk = 1, nlay_i
-            DO ji = kideb, kiut
-               ze_init(ji) = ze_init(ji) + q_i_b(ji,jk) * ht_i_b(ji) / REAL (nlay_i )
-            END DO
-         END DO
 
          DO ji = kideb, kiut
@@ -99,17 +83,14 @@
             ! Switches 
             !----------
-            iflush       =         MAX( 0._wp , SIGN( 1.0 , t_su_b(ji) - rtt )        )    ! =1 if summer 
-            igravdr      =         MAX( 0._wp , SIGN( 1.0 , t_bo_b(ji) - t_su_b(ji) ) )    ! =1 if t_su < t_bo
-            iaccrbo      =         MAX( 0._wp , SIGN( 1.0 , dh_i_bott(ji) )           )    ! =1 if bottom accretion
-            i_ice_switch = 1._wp - MAX ( 0._wp , SIGN( 1._wp , - ht_i_b(ji) + 1.e-2 ) )
-            isnowic      = 1._wp - MAX ( 0._wp , SIGN( 1._wp , - dh_snowice(ji) ) ) * i_ice_switch   ! =1 if snow ice formation
+            iflush  = MAX( 0._wp , SIGN( 1._wp , t_su_1d(ji) - rtt )        )     ! =1 if summer 
+            igravdr = MAX( 0._wp , SIGN( 1._wp , t_bo_1d(ji) - t_su_1d(ji) ) )    ! =1 if t_su < t_bo
 
             !---------------------
             ! Salinity tendencies
             !---------------------
-            !                                   ! drainage by gravity drainage
-            dsm_i_gd_1d(ji) = - igravdr * MAX( sm_i_b(ji) - sal_G , 0._wp ) / time_G * rdt_ice 
-            !                                   ! drainage by flushing  
-            dsm_i_fl_1d(ji) = - iflush  * MAX( sm_i_b(ji) - sal_F , 0._wp ) / time_F * rdt_ice
+            ! drainage by gravity drainage
+            dsm_i_gd_1d(ji) = - igravdr * MAX( sm_i_1d(ji) - sal_G , 0._wp ) / time_G * rdt_ice 
+            ! drainage by flushing  
+            dsm_i_fl_1d(ji) = - iflush  * MAX( sm_i_1d(ji) - sal_F , 0._wp ) / time_F * rdt_ice
 
             !-----------------
@@ -118,19 +99,10 @@
             ! only drainage terms ( gravity drainage and flushing )
             ! snow ice / bottom sources are added in lim_thd_ent to conserve energy
-            sm_i_b(ji) = sm_i_b(ji) + dsm_i_fl_1d(ji) + dsm_i_gd_1d(ji)
-
-            ! if no ice, salinity = 0.1
-            i_ice_switch = 1._wp - MAX ( 0._wp, SIGN( 1._wp , - ht_i_b(ji) ) )
-            sm_i_b(ji)   = i_ice_switch * sm_i_b(ji) + s_i_min * ( 1._wp - i_ice_switch )
-
-            !----------------------------
-            ! Heat flux - brine drainage
-            !----------------------------
-            fhbri_1d(ji) = 0._wp
+            sm_i_1d(ji) = sm_i_1d(ji) + dsm_i_fl_1d(ji) + dsm_i_gd_1d(ji)
 
             !----------------------------
             ! Salt flux - brine drainage
             !----------------------------
-            sfx_bri_1d(ji) = sfx_bri_1d(ji) - i_ice_switch * rhoic * a_i_b(ji) * ht_i_b(ji) * ( sm_i_b(ji) - zsiold(ji) ) * r1_rdtice
+            sfx_bri_1d(ji) = sfx_bri_1d(ji) - rhoic * a_i_1d(ji) * ht_i_1d(ji) * ( dsm_i_fl_1d(ji) + dsm_i_gd_1d(ji) ) * r1_rdtice
 
          END DO
@@ -138,21 +110,4 @@
          ! Salinity profile
          CALL lim_var_salprof1d( kideb, kiut )
-
-
-         ! Only necessary for conservation check since salinity is modified
-         !--------------------
-         ! Temperature update
-         !--------------------
-         DO jk = 1, nlay_i
-            DO ji = kideb, kiut
-               ztmelts    =  -tmut*s_i_b(ji,jk) + rtt
-               !Conversion q(S,T) -> T (second order equation)
-               zaaa         =  cpic
-               zbbb         =  ( rcp - cpic ) * ( ztmelts - rtt ) + q_i_b(ji,jk) / rhoic - lfus
-               zccc         =  lfus * ( ztmelts - rtt )
-               zdiscrim     =  SQRT(  MAX( zbbb*zbbb - 4.0*zaaa*zccc, 0._wp )  )
-               t_i_b(ji,jk) =  rtt - ( zbbb + zdiscrim ) / ( 2.0 *zaaa )
-            END DO
-         END DO
          !
       ENDIF 
@@ -161,9 +116,6 @@
       !  Module 3 : Profile of salinity, constant in time                            |
       !------------------------------------------------------------------------------|
-
       IF(  num_sal == 3  )   CALL lim_var_salprof1d( kideb, kiut )
 
-      !
-      CALL wrk_dealloc( jpij, ze_init, zhiold, zsiold )
       !
    END SUBROUTINE lim_thd_sal
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limtrp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limtrp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limtrp.F90	(revision 5075)
@@ -30,4 +30,5 @@
    USE limvar          ! clem for ice thickness correction
    USE timing          ! Timing
+   USE limcons        ! conservation tests
 
    IMPLICIT NONE
@@ -35,8 +36,4 @@
 
    PUBLIC   lim_trp    ! called by ice_step
-
-   REAL(wp)  ::   epsi10 = 1.e-10_wp  
-   REAL(wp)  ::   rzero  = 0._wp   
-   REAL(wp)  ::   rone   = 1._wp
 
    !! * Substitution
@@ -63,42 +60,25 @@
       INTEGER, INTENT(in) ::   kt   ! number of iteration
       !
-      INTEGER  ::   ji, jj, jk, jl, layer   ! dummy loop indices
+      INTEGER  ::   ji, jj, jk, jl, jn      ! dummy loop indices
       INTEGER  ::   initad                  ! number of sub-timestep for the advection
-      INTEGER  ::   ierr                    ! error status
-      REAL(wp) ::   zindb  , zindsn , zindic, zindh, zinda      ! local scalar
-      REAL(wp) ::   zusvosn, zusvoic, zbigval     !   -      -
-      REAL(wp) ::   zcfl , zusnit                 !   -      -
-      REAL(wp) ::   ze   , zsal   , zage          !   -      -
+      REAL(wp) ::   zcfl , zusnit           !   -      -
       !
       REAL(wp), POINTER, DIMENSION(:,:)      ::   zui_u, zvi_v, zsm, zs0at, zs0ow
       REAL(wp), POINTER, DIMENSION(:,:,:)    ::   zs0ice, zs0sn, zs0a, zs0c0 , zs0sm , zs0oi
       REAL(wp), POINTER, DIMENSION(:,:,:,:)  ::   zs0e
-      REAL(wp) :: zchk_v_i, zchk_smv, zchk_fs, zchk_fw, zchk_v_i_b, zchk_smv_b, zchk_fs_b, zchk_fw_b ! Check conservation (C Rousset)
-      REAL(wp) :: zchk_vmin, zchk_amin, zchk_amax, zchk_umax ! Check errors (C Rousset)
-      ! mass and salt flux (clem)
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zviold   ! old ice volume...
-      ! correct ice thickness (clem)
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zaiold, zhimax   ! old ice concentration and thickness
-      REAL(wp) :: zdv, zda, zvi, zvs, zsmv
+      REAL(wp), POINTER, DIMENSION(:,:,:)    ::   zviold, zvsold   ! old ice volume...
+      REAL(wp), POINTER, DIMENSION(:,:,:)    ::   zaiold, zhimax   ! old ice concentration and thickness
+      REAL(wp), POINTER, DIMENSION(:,:)      ::   zeiold, zesold   ! old enthalpies
+      REAL(wp) :: zdv, zda, zvi, zvs, zsmv, zes, zei
+      !
+      REAL(wp) :: zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b 
       !!---------------------------------------------------------------------
       IF( nn_timing == 1 )  CALL timing_start('limtrp')
 
-      CALL wrk_alloc( jpi, jpj, zui_u, zvi_v, zsm, zs0at, zs0ow )
+      CALL wrk_alloc( jpi, jpj, zui_u, zvi_v, zsm, zs0at, zs0ow, zeiold, zesold )
       CALL wrk_alloc( jpi, jpj, jpl, zs0ice, zs0sn, zs0a, zs0c0 , zs0sm , zs0oi )
-      CALL wrk_alloc( jpi, jpj, jkmax, jpl, zs0e )
-
-      CALL wrk_alloc( jpi,jpj,jpl,zviold )   ! clem
-      CALL wrk_alloc( jpi,jpj,jpl,zaiold, zhimax )   ! clem
-
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF( ln_limdiahsb ) THEN
-         zchk_v_i_b = glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_smv_b = glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_fw_b  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) )
-         zchk_fs_b  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) )
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      CALL wrk_alloc( jpi, jpj, nlay_i+1, jpl, zs0e )
+
+      CALL wrk_alloc( jpi, jpj, jpl, zaiold, zhimax, zviold, zvsold )   ! clem
 
       IF( numit == nstart .AND. lwp ) THEN
@@ -115,6 +95,12 @@
       IF( ln_limdyn ) THEN          !   Advection of sea ice properties   !
          !                          !-------------------------------------!
+
+         ! conservation test
+         IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limtrp', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
+
          ! mass and salt flux init (clem)
          zviold(:,:,:)  = v_i(:,:,:)
+         zeiold(:,:)  = SUM( SUM( e_i(:,:,1:nlay_i,:), dim=4 ), dim=3 ) 
+         zesold(:,:)  = SUM( SUM( e_s(:,:,1:nlay_s,:), dim=4 ), dim=3 ) 
 
          !--- Thickness correction init. (clem) -------------------------------
@@ -167,5 +153,5 @@
 !         ENDIF
 !!gm end
-         initad = 1 + NINT( MAX( rzero, SIGN( rone, zcfl-0.5 ) ) )
+         initad = 1 + NINT( MAX( 0._wp, SIGN( 1._wp, zcfl-0.5 ) ) )
          zusnit = 1.0 / REAL( initad ) 
          IF( zcfl > 0.5 .AND. lwp )   &
@@ -174,83 +160,83 @@
 
          IF( MOD( ( kt - 1) / nn_fsbc , 2 ) == 0 ) THEN       !==  odd ice time step:  adv_x then adv_y  ==!
-            DO jk = 1,initad
-               CALL lim_adv_x( zusnit, u_ice, rone , zsm, zs0ow (:,:), sxopw(:,:),   &             !--- ice open water area
+            DO jn = 1,initad
+               CALL lim_adv_x( zusnit, u_ice, 1._wp , zsm, zs0ow (:,:), sxopw(:,:),   &             !--- ice open water area
                   &                                       sxxopw(:,:), syopw(:,:), syyopw(:,:), sxyopw(:,:)  )
-               CALL lim_adv_y( zusnit, v_ice, rzero, zsm, zs0ow (:,:), sxopw(:,:),   &
+               CALL lim_adv_y( zusnit, v_ice, 0._wp, zsm, zs0ow (:,:), sxopw(:,:),   &
                   &                                       sxxopw(:,:), syopw(:,:), syyopw(:,:), sxyopw(:,:)  )
                DO jl = 1, jpl
-                  CALL lim_adv_x( zusnit, u_ice, rone , zsm, zs0ice(:,:,jl), sxice(:,:,jl),   &    !--- ice volume  ---
+                  CALL lim_adv_x( zusnit, u_ice, 1._wp , zsm, zs0ice(:,:,jl), sxice(:,:,jl),   &    !--- ice volume  ---
                      &                                       sxxice(:,:,jl), syice(:,:,jl), syyice(:,:,jl), sxyice(:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rzero, zsm, zs0ice(:,:,jl), sxice(:,:,jl),   &
+                  CALL lim_adv_y( zusnit, v_ice, 0._wp, zsm, zs0ice(:,:,jl), sxice(:,:,jl),   &
                      &                                       sxxice(:,:,jl), syice(:,:,jl), syyice(:,:,jl), sxyice(:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rone , zsm, zs0sn (:,:,jl), sxsn (:,:,jl),   &    !--- snow volume  ---
+                  CALL lim_adv_x( zusnit, u_ice, 1._wp , zsm, zs0sn (:,:,jl), sxsn (:,:,jl),   &    !--- snow volume  ---
                      &                                       sxxsn (:,:,jl), sysn (:,:,jl), syysn (:,:,jl), sxysn (:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rzero, zsm, zs0sn (:,:,jl), sxsn (:,:,jl),   &
+                  CALL lim_adv_y( zusnit, v_ice, 0._wp, zsm, zs0sn (:,:,jl), sxsn (:,:,jl),   &
                      &                                       sxxsn (:,:,jl), sysn (:,:,jl), syysn (:,:,jl), sxysn (:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rone , zsm, zs0sm (:,:,jl), sxsal(:,:,jl),   &    !--- ice salinity ---
+                  CALL lim_adv_x( zusnit, u_ice, 1._wp , zsm, zs0sm (:,:,jl), sxsal(:,:,jl),   &    !--- ice salinity ---
                      &                                       sxxsal(:,:,jl), sysal(:,:,jl), syysal(:,:,jl), sxysal(:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rzero, zsm, zs0sm (:,:,jl), sxsal(:,:,jl),   &
+                  CALL lim_adv_y( zusnit, v_ice, 0._wp, zsm, zs0sm (:,:,jl), sxsal(:,:,jl),   &
                      &                                       sxxsal(:,:,jl), sysal(:,:,jl), syysal(:,:,jl), sxysal(:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rone , zsm, zs0oi (:,:,jl), sxage(:,:,jl),   &   !--- ice age      ---     
+                  CALL lim_adv_x( zusnit, u_ice, 1._wp , zsm, zs0oi (:,:,jl), sxage(:,:,jl),   &   !--- ice age      ---     
                      &                                       sxxage(:,:,jl), syage(:,:,jl), syyage(:,:,jl), sxyage(:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rzero, zsm, zs0oi (:,:,jl), sxage(:,:,jl),   &
+                  CALL lim_adv_y( zusnit, v_ice, 0._wp, zsm, zs0oi (:,:,jl), sxage(:,:,jl),   &
                      &                                       sxxage(:,:,jl), syage(:,:,jl), syyage(:,:,jl), sxyage(:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rone , zsm, zs0a  (:,:,jl), sxa  (:,:,jl),   &   !--- ice concentrations ---
+                  CALL lim_adv_x( zusnit, u_ice, 1._wp , zsm, zs0a  (:,:,jl), sxa  (:,:,jl),   &   !--- ice concentrations ---
                      &                                       sxxa  (:,:,jl), sya  (:,:,jl), syya  (:,:,jl), sxya  (:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rzero, zsm, zs0a  (:,:,jl), sxa  (:,:,jl),   & 
+                  CALL lim_adv_y( zusnit, v_ice, 0._wp, zsm, zs0a  (:,:,jl), sxa  (:,:,jl),   & 
                      &                                       sxxa  (:,:,jl), sya  (:,:,jl), syya  (:,:,jl), sxya  (:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rone , zsm, zs0c0 (:,:,jl), sxc0 (:,:,jl),   &  !--- snow heat contents ---
+                  CALL lim_adv_x( zusnit, u_ice, 1._wp , zsm, zs0c0 (:,:,jl), sxc0 (:,:,jl),   &  !--- snow heat contents ---
                      &                                       sxxc0 (:,:,jl), syc0 (:,:,jl), syyc0 (:,:,jl), sxyc0 (:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rzero, zsm, zs0c0 (:,:,jl), sxc0 (:,:,jl),   &
+                  CALL lim_adv_y( zusnit, v_ice, 0._wp, zsm, zs0c0 (:,:,jl), sxc0 (:,:,jl),   &
                      &                                       sxxc0 (:,:,jl), syc0 (:,:,jl), syyc0 (:,:,jl), sxyc0 (:,:,jl)  )
-                  DO layer = 1, nlay_i                                                           !--- ice heat contents ---
-                     CALL lim_adv_x( zusnit, u_ice, rone , zsm, zs0e(:,:,layer,jl), sxe (:,:,layer,jl),   & 
-                        &                                       sxxe(:,:,layer,jl), sye (:,:,layer,jl),   &
-                        &                                       syye(:,:,layer,jl), sxye(:,:,layer,jl) )
-                     CALL lim_adv_y( zusnit, v_ice, rzero, zsm, zs0e(:,:,layer,jl), sxe (:,:,layer,jl),   & 
-                        &                                       sxxe(:,:,layer,jl), sye (:,:,layer,jl),   &
-                        &                                       syye(:,:,layer,jl), sxye(:,:,layer,jl) )
+                  DO jk = 1, nlay_i                                                           !--- ice heat contents ---
+                     CALL lim_adv_x( zusnit, u_ice, 1._wp , zsm, zs0e(:,:,jk,jl), sxe (:,:,jk,jl),   & 
+                        &                                       sxxe(:,:,jk,jl), sye (:,:,jk,jl),   &
+                        &                                       syye(:,:,jk,jl), sxye(:,:,jk,jl) )
+                     CALL lim_adv_y( zusnit, v_ice, 0._wp, zsm, zs0e(:,:,jk,jl), sxe (:,:,jk,jl),   & 
+                        &                                       sxxe(:,:,jk,jl), sye (:,:,jk,jl),   &
+                        &                                       syye(:,:,jk,jl), sxye(:,:,jk,jl) )
                   END DO
                END DO
             END DO
          ELSE
-            DO jk = 1, initad
-               CALL lim_adv_y( zusnit, v_ice, rone , zsm, zs0ow (:,:), sxopw(:,:),   &             !--- ice open water area
+            DO jn = 1, initad
+               CALL lim_adv_y( zusnit, v_ice, 1._wp , zsm, zs0ow (:,:), sxopw(:,:),   &             !--- ice open water area
                   &                                       sxxopw(:,:), syopw(:,:), syyopw(:,:), sxyopw(:,:)  )
-               CALL lim_adv_x( zusnit, u_ice, rzero, zsm, zs0ow (:,:), sxopw(:,:),   &
+               CALL lim_adv_x( zusnit, u_ice, 0._wp, zsm, zs0ow (:,:), sxopw(:,:),   &
                   &                                       sxxopw(:,:), syopw(:,:), syyopw(:,:), sxyopw(:,:)  )
                DO jl = 1, jpl
-                  CALL lim_adv_y( zusnit, v_ice, rone , zsm, zs0ice(:,:,jl), sxice(:,:,jl),   &    !--- ice volume  ---
+                  CALL lim_adv_y( zusnit, v_ice, 1._wp , zsm, zs0ice(:,:,jl), sxice(:,:,jl),   &    !--- ice volume  ---
                      &                                       sxxice(:,:,jl), syice(:,:,jl), syyice(:,:,jl), sxyice(:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rzero, zsm, zs0ice(:,:,jl), sxice(:,:,jl),   &
+                  CALL lim_adv_x( zusnit, u_ice, 0._wp, zsm, zs0ice(:,:,jl), sxice(:,:,jl),   &
                      &                                       sxxice(:,:,jl), syice(:,:,jl), syyice(:,:,jl), sxyice(:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rone , zsm, zs0sn (:,:,jl), sxsn (:,:,jl),   &    !--- snow volume  ---
+                  CALL lim_adv_y( zusnit, v_ice, 1._wp , zsm, zs0sn (:,:,jl), sxsn (:,:,jl),   &    !--- snow volume  ---
                      &                                       sxxsn (:,:,jl), sysn (:,:,jl), syysn (:,:,jl), sxysn (:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rzero, zsm, zs0sn (:,:,jl), sxsn (:,:,jl),   &
+                  CALL lim_adv_x( zusnit, u_ice, 0._wp, zsm, zs0sn (:,:,jl), sxsn (:,:,jl),   &
                      &                                       sxxsn (:,:,jl), sysn (:,:,jl), syysn (:,:,jl), sxysn (:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rone , zsm, zs0sm (:,:,jl), sxsal(:,:,jl),   &    !--- ice salinity ---
+                  CALL lim_adv_y( zusnit, v_ice, 1._wp , zsm, zs0sm (:,:,jl), sxsal(:,:,jl),   &    !--- ice salinity ---
                      &                                       sxxsal(:,:,jl), sysal(:,:,jl), syysal(:,:,jl), sxysal(:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rzero, zsm, zs0sm (:,:,jl), sxsal(:,:,jl),   &
+                  CALL lim_adv_x( zusnit, u_ice, 0._wp, zsm, zs0sm (:,:,jl), sxsal(:,:,jl),   &
                      &                                       sxxsal(:,:,jl), sysal(:,:,jl), syysal(:,:,jl), sxysal(:,:,jl)  )
 
-                  CALL lim_adv_y( zusnit, v_ice, rone , zsm, zs0oi (:,:,jl), sxage(:,:,jl),   &   !--- ice age      ---
+                  CALL lim_adv_y( zusnit, v_ice, 1._wp , zsm, zs0oi (:,:,jl), sxage(:,:,jl),   &   !--- ice age      ---
                      &                                       sxxage(:,:,jl), syage(:,:,jl), syyage(:,:,jl), sxyage(:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rzero, zsm, zs0oi (:,:,jl), sxage(:,:,jl),   &
+                  CALL lim_adv_x( zusnit, u_ice, 0._wp, zsm, zs0oi (:,:,jl), sxage(:,:,jl),   &
                      &                                       sxxage(:,:,jl), syage(:,:,jl), syyage(:,:,jl), sxyage(:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rone , zsm, zs0a  (:,:,jl), sxa  (:,:,jl),   &   !--- ice concentrations ---
+                  CALL lim_adv_y( zusnit, v_ice, 1._wp , zsm, zs0a  (:,:,jl), sxa  (:,:,jl),   &   !--- ice concentrations ---
                      &                                       sxxa  (:,:,jl), sya  (:,:,jl), syya  (:,:,jl), sxya  (:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rzero, zsm, zs0a  (:,:,jl), sxa  (:,:,jl),   &
+                  CALL lim_adv_x( zusnit, u_ice, 0._wp, zsm, zs0a  (:,:,jl), sxa  (:,:,jl),   &
                      &                                       sxxa  (:,:,jl), sya  (:,:,jl), syya  (:,:,jl), sxya  (:,:,jl)  )
-                  CALL lim_adv_y( zusnit, v_ice, rone , zsm, zs0c0 (:,:,jl), sxc0 (:,:,jl),   &  !--- snow heat contents ---
+                  CALL lim_adv_y( zusnit, v_ice, 1._wp , zsm, zs0c0 (:,:,jl), sxc0 (:,:,jl),   &  !--- snow heat contents ---
                      &                                       sxxc0 (:,:,jl), syc0 (:,:,jl), syyc0 (:,:,jl), sxyc0 (:,:,jl)  )
-                  CALL lim_adv_x( zusnit, u_ice, rzero, zsm, zs0c0 (:,:,jl), sxc0 (:,:,jl),   &
+                  CALL lim_adv_x( zusnit, u_ice, 0._wp, zsm, zs0c0 (:,:,jl), sxc0 (:,:,jl),   &
                      &                                       sxxc0 (:,:,jl), syc0 (:,:,jl), syyc0 (:,:,jl), sxyc0 (:,:,jl)  )
-                  DO layer = 1, nlay_i                                                           !--- ice heat contents ---
-                     CALL lim_adv_y( zusnit, v_ice, rone , zsm, zs0e(:,:,layer,jl), sxe (:,:,layer,jl),   & 
-                        &                                       sxxe(:,:,layer,jl), sye (:,:,layer,jl),   &
-                        &                                       syye(:,:,layer,jl), sxye(:,:,layer,jl) )
-                     CALL lim_adv_x( zusnit, u_ice, rzero, zsm, zs0e(:,:,layer,jl), sxe (:,:,layer,jl),   & 
-                        &                                       sxxe(:,:,layer,jl), sye (:,:,layer,jl),   &
-                        &                                       syye(:,:,layer,jl), sxye(:,:,layer,jl) )
+                  DO jk = 1, nlay_i                                                           !--- ice heat contents ---
+                     CALL lim_adv_y( zusnit, v_ice, 1._wp , zsm, zs0e(:,:,jk,jl), sxe (:,:,jk,jl),   & 
+                        &                                       sxxe(:,:,jk,jl), sye (:,:,jk,jl),   &
+                        &                                       syye(:,:,jk,jl), sxye(:,:,jk,jl) )
+                     CALL lim_adv_x( zusnit, u_ice, 0._wp, zsm, zs0e(:,:,jk,jl), sxe (:,:,jk,jl),   & 
+                        &                                       sxxe(:,:,jk,jl), sye (:,:,jk,jl),   &
+                        &                                       syye(:,:,jk,jl), sxye(:,:,jk,jl) )
                   END DO
                END DO
@@ -268,8 +254,5 @@
             zs0oi (:,:,jl) = zs0oi (:,:,jl) / area(:,:)
             zs0a  (:,:,jl) = zs0a  (:,:,jl) / area(:,:)
-            zs0c0 (:,:,jl) = zs0c0 (:,:,jl) / area(:,:)
-            DO jk = 1, nlay_i
-               zs0e(:,:,jk,jl) = zs0e(:,:,jk,jl) / area(:,:)
-            END DO
+            !
          END DO
 
@@ -289,8 +272,8 @@
          DO jj = 1, jpjm1                    ! NB: has not to be defined on jpj line and jpi row
             DO ji = 1 , fs_jpim1   ! vector opt.
-               pahu(ji,jj) = ( 1._wp - MAX( rzero, SIGN( rone, -zs0at(ji  ,jj) ) ) )   &
-                  &        * ( 1._wp - MAX( rzero, SIGN( rone, -zs0at(ji+1,jj) ) ) ) * ahiu(ji,jj)
-               pahv(ji,jj) = ( 1._wp - MAX( rzero, SIGN( rone, -zs0at(ji,jj  ) ) ) )   &
-                  &        * ( 1._wp - MAX( rzero, SIGN( rone,- zs0at(ji,jj+1) ) ) ) * ahiv(ji,jj)
+               pahu(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -zs0at(ji  ,jj) ) ) )   &
+                  &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -zs0at(ji+1,jj) ) ) ) * ahiu(ji,jj)
+               pahv(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -zs0at(ji,jj  ) ) ) )   &
+                  &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp,- zs0at(ji,jj+1) ) ) ) * ahiv(ji,jj)
             END DO
          END DO
@@ -305,8 +288,8 @@
             DO jj = 1, jpjm1                 ! NB: has not to be defined on jpj line and jpi row
                DO ji = 1 , fs_jpim1   ! vector opt.
-                  pahu(ji,jj) = ( 1._wp - MAX( rzero, SIGN( rone, -zs0a(ji  ,jj,jl) ) ) )   &
-                     &        * ( 1._wp - MAX( rzero, SIGN( rone, -zs0a(ji+1,jj,jl) ) ) ) * ahiu(ji,jj)
-                  pahv(ji,jj) = ( 1._wp - MAX( rzero, SIGN( rone, -zs0a(ji,jj  ,jl) ) ) )   &
-                     &        * ( 1._wp - MAX( rzero, SIGN( rone,- zs0a(ji,jj+1,jl) ) ) ) * ahiv(ji,jj)
+                  pahu(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -zs0a(ji  ,jj,jl) ) ) )   &
+                     &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -zs0a(ji+1,jj,jl) ) ) ) * ahiu(ji,jj)
+                  pahv(ji,jj) = ( 1._wp - MAX( 0._wp, SIGN( 1._wp, -zs0a(ji,jj  ,jl) ) ) )   &
+                     &        * ( 1._wp - MAX( 0._wp, SIGN( 1._wp,- zs0a(ji,jj+1,jl) ) ) ) * ahiv(ji,jj)
                END DO
             END DO
@@ -334,10 +317,10 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zs0sn (ji,jj,jl) = MAX( rzero, zs0sn (ji,jj,jl) )
-                  zs0ice(ji,jj,jl) = MAX( rzero, zs0ice(ji,jj,jl) )
-                  zs0sm (ji,jj,jl) = MAX( rzero, zs0sm (ji,jj,jl) )
-                  zs0oi (ji,jj,jl) = MAX( rzero, zs0oi (ji,jj,jl) )
-                  zs0a  (ji,jj,jl) = MAX( rzero, zs0a  (ji,jj,jl) )
-                  zs0c0 (ji,jj,jl) = MAX( rzero, zs0c0 (ji,jj,jl) )
+                  zs0sn (ji,jj,jl) = MAX( 0._wp, zs0sn (ji,jj,jl) )
+                  zs0ice(ji,jj,jl) = MAX( 0._wp, zs0ice(ji,jj,jl) )
+                  zs0sm (ji,jj,jl) = MAX( 0._wp, zs0sm (ji,jj,jl) )
+                  zs0oi (ji,jj,jl) = MAX( 0._wp, zs0oi (ji,jj,jl) )
+                  zs0a  (ji,jj,jl) = MAX( 0._wp, zs0a  (ji,jj,jl) )
+                  zs0c0 (ji,jj,jl) = MAX( 0._wp, zs0c0 (ji,jj,jl) )
                   zs0at (ji,jj)    = zs0at(ji,jj) + zs0a(ji,jj,jl)
                END DO
@@ -346,124 +329,35 @@
 
          !---------------------------------------------------------
-         ! 5.2) Snow thickness, Ice thickness, Ice concentrations
+         ! 5.2) Update and mask variables
          !---------------------------------------------------------
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-               zindb        = MAX( 0._wp , SIGN( 1.0, zs0at(ji,jj) - epsi10) )
-               zs0ow(ji,jj) = ( 1._wp - zindb ) + zindb * MAX( zs0ow(ji,jj), 0._wp )
-               ato_i(ji,jj) = zs0ow(ji,jj)
-            END DO
-         END DO
-
-         DO jl = 1, jpl         ! Remove very small areas 
+         DO jl = 1, jpl          
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zvi = zs0ice(ji,jj,jl)
-                  zvs = zs0sn(ji,jj,jl)
+                  rswitch = MAX( 0._wp , SIGN( 1._wp, zs0a(ji,jj,jl) - epsi10 ) )
+
+                  zvi  = zs0ice(ji,jj,jl)
+                  zvs  = zs0sn (ji,jj,jl)
+                  zes  = zs0c0 (ji,jj,jl)      
+                  zsmv = zs0sm (ji,jj,jl)
                   !
-                  zindb         = MAX( 0.0 , SIGN( 1.0, zs0a(ji,jj,jl) - epsi10) )
-                  !
-                  v_s(ji,jj,jl)  = zindb * zs0sn (ji,jj,jl) 
-                  v_i(ji,jj,jl)  = zindb * zs0ice(ji,jj,jl)
-                  !
-                  zindsn         = MAX( rzero, SIGN( rone, v_s(ji,jj,jl) - epsi10 ) )
-                  zindic         = MAX( rzero, SIGN( rone, v_i(ji,jj,jl) - epsi10 ) )
-                  zindb          = MAX( zindsn, zindic )
-                  !
-                  zs0a(ji,jj,jl) = zindb  * zs0a(ji,jj,jl) !ice concentration
-                  a_i (ji,jj,jl) = zs0a(ji,jj,jl)
-                  v_s (ji,jj,jl) = zindsn * v_s(ji,jj,jl)
-                  v_i (ji,jj,jl) = zindic * v_i(ji,jj,jl)
-                  !
-                  ! Update mass fluxes (clem)
-                  rdm_ice(ji,jj) = rdm_ice(ji,jj) + ( v_i(ji,jj,jl) - zvi ) * rhoic 
-                  rdm_snw(ji,jj) = rdm_snw(ji,jj) + ( v_s(ji,jj,jl) - zvs ) * rhosn 
-              END DO
-            END DO
-         END DO
-
-         !--- Thickness correction in case too high (clem) --------------------------------------------------------
-         CALL lim_var_glo2eqv
-         DO jl = 1, jpl
-            DO jj = 1, jpj
-               DO ji = 1, jpi
-
-                  IF ( v_i(ji,jj,jl) > 0._wp ) THEN
-                     zvi = v_i(ji,jj,jl)
-                     zvs = v_s(ji,jj,jl)
-                     zdv = v_i(ji,jj,jl) - zviold(ji,jj,jl)   
-                     !zda = a_i(ji,jj,jl) - zaiold(ji,jj,jl)   
-                     
-                     zindh = 1._wp
-                     IF ( ( zdv > 0.0 .AND. ht_i(ji,jj,jl) > zhimax(ji,jj,jl) .AND. SUM( zaiold(ji,jj,1:jpl) ) < 0.80 ) .OR. &
-                        & ( zdv < 0.0 .AND. ht_i(ji,jj,jl) > zhimax(ji,jj,jl) ) ) THEN                                          
-                        ht_i(ji,jj,jl) = MIN( zhimax(ji,jj,jl), hi_max(jl) )
-                        zindh   =  MAX( rzero, SIGN( rone, ht_i(ji,jj,jl) - epsi10 ) )
-                        a_i(ji,jj,jl)  = zindh * v_i(ji,jj,jl) / MAX( ht_i(ji,jj,jl), epsi10 )
-                     ELSE
-                        ht_i(ji,jj,jl) = MAX( MIN( ht_i(ji,jj,jl), hi_max(jl) ), hi_max(jl-1) )
-                        zindh   =  MAX( rzero, SIGN( rone, ht_i(ji,jj,jl) - epsi10 ) )
-                        a_i(ji,jj,jl)  = zindh * v_i(ji,jj,jl) / MAX( ht_i(ji,jj,jl), epsi10 )
-                     ENDIF
-
-                     ! small correction due to *zindh for a_i
-                     v_i(ji,jj,jl) = zindh * v_i(ji,jj,jl)
-                     v_s(ji,jj,jl) = zindh * v_s(ji,jj,jl)
-
-                     ! Update mass fluxes
-                     rdm_ice(ji,jj) = rdm_ice(ji,jj) + ( v_i(ji,jj,jl) - zvi ) * rhoic
-                     rdm_snw(ji,jj) = rdm_snw(ji,jj) + ( v_s(ji,jj,jl) - zvs ) * rhosn
-
-                  ENDIF
-
-                  diag_trp_vi(ji,jj) = diag_trp_vi(ji,jj) + ( v_i(ji,jj,jl) - zviold(ji,jj,jl) ) * r1_rdtice
-
-               END DO
-            END DO
-         END DO
-
-         ! ---
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-               zs0at(ji,jj) = SUM( zs0a(ji,jj,1:jpl) ) ! clem@useless??
-            END DO
-         END DO
-
-         !----------------------
-         ! 5.3) Ice properties
-         !----------------------
-
-         zbigval = 1.e+13
-
-         DO jl = 1, jpl
-            DO jj = 1, jpj
-               DO ji = 1, jpi
-                  zsmv = zs0sm(ji,jj,jl)
-
-                  ! Switches and dummy variables
-                  zusvosn         = 1.0/MAX( v_s(ji,jj,jl) , epsi10 )
-                  zusvoic         = 1.0/MAX( v_i(ji,jj,jl) , epsi10 )
-                  zindsn          = MAX( rzero, SIGN( rone, v_s(ji,jj,jl) - epsi10 ) )
-                  zindic          = MAX( rzero, SIGN( rone, v_i(ji,jj,jl) - epsi10 ) )
-                  zindb           = MAX( zindsn, zindic )
-
+                  ! Remove very small areas
+                  v_s(ji,jj,jl)   = rswitch * zs0sn (ji,jj,jl) 
+                  v_i(ji,jj,jl)   = rswitch * zs0ice(ji,jj,jl)
+                  a_i(ji,jj,jl)   = rswitch * zs0a  (ji,jj,jl)
+                  e_s(ji,jj,1,jl) = rswitch * zs0c0 (ji,jj,jl)      
                   ! Ice salinity and age
-                  !clem zsal = MAX( MIN( (rhoic-rhosn)/rhoic*sss_m(ji,jj), zusvoic * zs0sm(ji,jj,jl) ), s_i_min ) * v_i(ji,jj,jl)
                   IF(  num_sal == 2  ) THEN
                      smv_i(ji,jj,jl) = MAX( MIN( s_i_max * v_i(ji,jj,jl), zsmv ), s_i_min * v_i(ji,jj,jl) )
                   ENDIF
-
-                  zage = MAX( MIN( zbigval, zs0oi(ji,jj,jl) / MAX( a_i(ji,jj,jl), epsi10 ) ), 0._wp  ) * a_i(ji,jj,jl)
-                  oa_i (ji,jj,jl)  = zindic * zage 
-
-                  ! Snow heat content
-                  ze              =  MIN( MAX( 0.0, zs0c0(ji,jj,jl)*area(ji,jj) ), zbigval )
-                  e_s(ji,jj,1,jl) = zindsn * ze      
-
-                  ! Update salt fluxes (clem)
+                  oa_i(ji,jj,jl) = MAX( rswitch * zs0oi(ji,jj,jl) / MAX( a_i(ji,jj,jl), epsi10 ), 0._wp ) * a_i(ji,jj,jl)
+
+                 ! Update fluxes
+                  wfx_res(ji,jj) = wfx_res(ji,jj) - ( v_i(ji,jj,jl) - zvi ) * rhoic * r1_rdtice 
+                  wfx_snw(ji,jj) = wfx_snw(ji,jj) - ( v_s(ji,jj,jl) - zvs ) * rhosn * r1_rdtice
                   sfx_res(ji,jj) = sfx_res(ji,jj) - ( smv_i(ji,jj,jl) - zsmv ) * rhoic * r1_rdtice 
-               END DO !ji
-            END DO !jj
-         END DO ! jl
+                  hfx_res(ji,jj) = hfx_res(ji,jj) + ( e_s(ji,jj,1,jl) - zes ) * unit_fac / area(ji,jj) * r1_rdtice ! W.m-2 <0
+              END DO
+            END DO
+         END DO
 
          DO jl = 1, jpl
@@ -471,8 +365,9 @@
                DO jj = 1, jpj
                   DO ji = 1, jpi
-                     ! Ice heat content
-                     zindic          =  MAX( rzero, SIGN( rone, v_i(ji,jj,jl) - epsi10 ) )
-                     ze              =  MIN( MAX( 0.0, zs0e(ji,jj,jk,jl)*area(ji,jj) ), zbigval )
-                     e_i(ji,jj,jk,jl) = zindic * ze
+                     rswitch          = MAX( 0._wp , SIGN( 1._wp, zs0a(ji,jj,jl) - epsi10 ) )
+                     zei              = zs0e(ji,jj,jk,jl)      
+                     e_i(ji,jj,jk,jl) = rswitch * MAX( 0._wp, zs0e(ji,jj,jk,jl) )
+                     ! Update fluxes
+                     hfx_res(ji,jj) = hfx_res(ji,jj) + ( e_i(ji,jj,jk,jl) - zei ) * unit_fac / area(ji,jj) * r1_rdtice ! W.m-2 <0
                   END DO !ji
                END DO ! jj
@@ -480,26 +375,89 @@
          END DO ! jl
 
-
-      ! --- agglomerate variables (clem) -----------------
-      vt_i (:,:) = 0._wp
-      vt_s (:,:) = 0._wp
-      at_i (:,:) = 0._wp
-      !
-      DO jl = 1, jpl
+         !--- Thickness correction in case too high (clem) --------------------------------------------------------
+         CALL lim_var_glo2eqv
+         DO jl = 1, jpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+
+                  IF ( v_i(ji,jj,jl) > 0._wp ) THEN
+                     zvi  = v_i  (ji,jj,jl)
+                     zvs  = v_s  (ji,jj,jl)
+                     zsmv = smv_i(ji,jj,jl)
+                     zes  = e_s  (ji,jj,1,jl)
+                     zei  = SUM( e_i(ji,jj,1:nlay_i,jl) )
+                     zdv  = v_i(ji,jj,jl) - zviold(ji,jj,jl)   
+                     !zda = a_i(ji,jj,jl) - zaiold(ji,jj,jl)   
+                     
+                     rswitch = 1._wp
+                     IF ( ( zdv > 0.0 .AND. ht_i(ji,jj,jl) > zhimax(ji,jj,jl) .AND. SUM( zaiold(ji,jj,1:jpl) ) < 0.80 ) .OR. &
+                        & ( zdv < 0.0 .AND. ht_i(ji,jj,jl) > zhimax(ji,jj,jl) ) ) THEN                                          
+                        ht_i(ji,jj,jl) = MIN( zhimax(ji,jj,jl), hi_max(jl) )
+                        rswitch        = MAX( 0._wp, SIGN( 1._wp, ht_i(ji,jj,jl) - epsi20 ) )
+                        a_i(ji,jj,jl)  = rswitch * v_i(ji,jj,jl) / MAX( ht_i(ji,jj,jl), epsi20 )
+                     ELSE
+                        ht_i(ji,jj,jl) = MAX( MIN( ht_i(ji,jj,jl), hi_max(jl) ), hi_max(jl-1) )
+                        rswitch        = MAX( 0._wp, SIGN( 1._wp, ht_i(ji,jj,jl) - epsi20 ) )
+                        a_i(ji,jj,jl)  = rswitch * v_i(ji,jj,jl) / MAX( ht_i(ji,jj,jl), epsi20 )
+                     ENDIF
+
+                     ! small correction due to *rswitch for a_i
+                     v_i  (ji,jj,jl) = rswitch * v_i  (ji,jj,jl)
+                     v_s  (ji,jj,jl) = rswitch * v_s  (ji,jj,jl)
+                     smv_i(ji,jj,jl) = rswitch * smv_i(ji,jj,jl)
+                     e_s(ji,jj,1,jl) = rswitch * e_s(ji,jj,1,jl)
+                     e_i(ji,jj,1:nlay_i,jl) = rswitch * e_i(ji,jj,1:nlay_i,jl)
+
+                     ! Update mass fluxes
+                     wfx_res(ji,jj) = wfx_res(ji,jj) - ( v_i(ji,jj,jl) - zvi ) * rhoic * r1_rdtice
+                     wfx_snw(ji,jj) = wfx_snw(ji,jj) - ( v_s(ji,jj,jl) - zvs ) * rhosn * r1_rdtice
+                     sfx_res(ji,jj) = sfx_res(ji,jj) - ( smv_i(ji,jj,jl) - zsmv ) * rhoic * r1_rdtice 
+                     hfx_res(ji,jj) = hfx_res(ji,jj) + ( e_s(ji,jj,1,jl) - zes ) * unit_fac / area(ji,jj) * r1_rdtice ! W.m-2 <0
+                     hfx_res(ji,jj) = hfx_res(ji,jj) + ( SUM( e_i(ji,jj,1:nlay_i,jl) ) - zei ) * unit_fac / area(ji,jj) * r1_rdtice ! W.m-2 <0
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         ! -------------------------------------------------
+
+         ! --- diags ---
          DO jj = 1, jpj
             DO ji = 1, jpi
-               !
-               vt_i(ji,jj) = vt_i(ji,jj) + v_i(ji,jj,jl) ! ice volume
-               vt_s(ji,jj) = vt_s(ji,jj) + v_s(ji,jj,jl) ! snow volume
-               at_i(ji,jj) = at_i(ji,jj) + a_i(ji,jj,jl) ! ice concentration
-               !
-               zinda = MAX( rzero , SIGN( rone , at_i(ji,jj) - epsi10 ) )
-               icethi(ji,jj) = vt_i(ji,jj) / MAX( at_i(ji,jj) , epsi10 ) * zinda  ! ice thickness
-            END DO
-         END DO
-      END DO
-      ! -------------------------------------------------
-
-
+               diag_trp_ei(ji,jj) = ( SUM( e_i(ji,jj,1:nlay_i,:) ) - zeiold(ji,jj) ) / area(ji,jj) * unit_fac * r1_rdtice
+               diag_trp_es(ji,jj) = ( SUM( e_s(ji,jj,1:nlay_s,:) ) - zesold(ji,jj) ) / area(ji,jj) * unit_fac * r1_rdtice
+
+               diag_trp_vi(ji,jj) = SUM( v_i(ji,jj,:) - zviold(ji,jj,:) ) * r1_rdtice
+               diag_trp_vs(ji,jj) = SUM( v_s(ji,jj,:) - zvsold(ji,jj,:) ) * r1_rdtice
+            END DO
+         END DO
+
+         ! --- agglomerate variables -----------------
+         vt_i (:,:) = 0._wp
+         vt_s (:,:) = 0._wp
+         at_i (:,:) = 0._wp
+         !
+         DO jl = 1, jpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !
+                  vt_i(ji,jj) = vt_i(ji,jj) + v_i(ji,jj,jl) ! ice volume
+                  vt_s(ji,jj) = vt_s(ji,jj) + v_s(ji,jj,jl) ! snow volume
+                  at_i(ji,jj) = at_i(ji,jj) + a_i(ji,jj,jl) ! ice concentration
+               END DO
+            END DO
+         END DO
+         ! -------------------------------------------------
+
+         ! open water
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! open water = 1 if at_i=0
+               rswitch      = MAX( 0._wp , SIGN( 1._wp, - at_i(ji,jj) ) )
+               ato_i(ji,jj) = rswitch + (1._wp - rswitch ) * zs0ow(ji,jj)
+            END DO
+         END DO      
+
+         ! conservation test
+         IF( ln_limdiahsb ) CALL lim_cons_hsm(1, 'limtrp', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
 
       ENDIF
@@ -536,37 +494,10 @@
          END DO
       ENDIF
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF( ln_limdiahsb ) THEN
-         zchk_fs  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) ) - zchk_fs_b
-         zchk_fw  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) ) - zchk_fw_b
- 
-         zchk_v_i = ( glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_v_i_b - ( zchk_fw / rhoic ) ) / rdt_ice
-         zchk_smv = ( glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_smv_b ) / rdt_ice + ( zchk_fs / rhoic )
-
-         zchk_vmin = glob_min(v_i)
-         zchk_amax = glob_max(SUM(a_i,dim=3))
-         zchk_amin = glob_min(a_i)
-         zchk_umax = glob_max(SQRT(u_ice**2 + v_ice**2))
-
-         IF(lwp) THEN
-            IF ( ABS( zchk_v_i   ) >  1.e-5 ) THEN
-               WRITE(numout,*) 'violation volume [m3/day]     (limtrp) = ',(zchk_v_i * rday)
-               WRITE(numout,*) 'u_ice max [m/s]               (limtrp) = ',zchk_umax
-               WRITE(numout,*) 'number of time steps          (limtrp) =',kt
-            ENDIF
-            IF ( ABS( zchk_smv   ) >  1.e-4 ) WRITE(numout,*) 'violation saline [psu*m3/day] (limtrp) = ',(zchk_smv * rday)
-            IF ( zchk_vmin <  0.            ) WRITE(numout,*) 'violation v_i<0  [mm]         (limtrp) = ',(zchk_vmin * 1.e-3)
-            IF ( zchk_amin <  0.            ) WRITE(numout,*) 'violation a_i<0               (limtrp) = ',zchk_amin
-         ENDIF
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
       !
-      CALL wrk_dealloc( jpi, jpj, zui_u, zvi_v, zsm, zs0at, zs0ow )
+      CALL wrk_dealloc( jpi, jpj, zui_u, zvi_v, zsm, zs0at, zs0ow, zeiold, zesold )
       CALL wrk_dealloc( jpi, jpj, jpl, zs0ice, zs0sn, zs0a, zs0c0 , zs0sm , zs0oi )
-      CALL wrk_dealloc( jpi, jpj, jkmax, jpl, zs0e )
-
-      CALL wrk_dealloc( jpi,jpj,jpl,zaiold, zhimax )   ! clem
+      CALL wrk_dealloc( jpi, jpj, nlay_i+1, jpl, zs0e )
+
+      CALL wrk_dealloc( jpi, jpj, jpl, zviold, zvsold, zaiold, zhimax )   ! clem
       !
       IF( nn_timing == 1 )  CALL timing_stop('limtrp')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limupdate1.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limupdate1.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limupdate1.F90	(revision 5075)
@@ -5,4 +5,5 @@
    !!======================================================================
    !! History :  3.0  !  2006-04  (M. Vancoppenolle) Original code
+   !!            3.6  !  2014-06  (C. Rousset)       Complete rewriting/cleaning
    !!----------------------------------------------------------------------
 #if defined key_lim3
@@ -32,4 +33,5 @@
    USE par_ice
    USE limitd_th
+   USE limitd_me
    USE limvar
    USE prtctl           ! Print control
@@ -37,9 +39,9 @@
    USE wrk_nemo         ! work arrays
    USE lib_fortran     ! glob_sum
-   ! Check budget (Rousset)
    USE in_out_manager   ! I/O manager
    USE iom              ! I/O manager
    USE lib_mpp          ! MPP library
    USE timing          ! Timing
+   USE limcons        ! conservation tests
 
    IMPLICIT NONE
@@ -48,8 +50,4 @@
    PUBLIC   lim_update1   ! routine called by ice_step
 
-      REAL(wp)  ::   epsi10 = 1.e-10_wp   !    -       -
-      REAL(wp)  ::   rzero  = 0._wp       !    -       -
-      REAL(wp)  ::   rone   = 1._wp       !    -       -
-         
    !! * Substitutions
 #  include "vectopt_loop_substitute.h90"
@@ -66,122 +64,32 @@
       !!               
       !! ** Purpose :  Computes update of sea-ice global variables at 
-      !!               the end of the time step.
-      !!               Address pathological cases
-      !!               This place is very important
+      !!               the end of the dynamics.
       !!                
-      !! ** Method  :  
-      !!    Ice speed from ice dynamics
-      !!    Ice thickness, Snow thickness, Temperatures, Lead fraction
-      !!      from advection and ice thermodynamics 
-      !!
-      !! ** Action  : - 
       !!---------------------------------------------------------------------
-      INTEGER ::   ji, jj, jk, jl, jm    ! dummy loop indices
-      INTEGER ::   jbnd1, jbnd2
-      INTEGER ::   i_ice_switch
-      INTEGER ::   ind_im, layer      ! indices for internal melt
-      REAL(wp) ::   zweight, zesum, z_da_i, zhimax
-      REAL(wp) ::   zinda, zindb, zindsn, zindic
-      REAL(wp) ::   zindg, zh, zdvres, zviold2
-      REAL(wp) ::   zbigvalue, zvsold2, z_da_ex
-      REAL(wp) ::   z_prescr_hi, zat_i_old, ztmelts, ze_s
-
-      REAL(wp), POINTER, DIMENSION(:) ::   zthick0, zqm0      ! thickness of the layers and heat contents for
-      REAL(wp) :: zchk_v_i, zchk_smv, zchk_fs, zchk_fw, zchk_v_i_b, zchk_smv_b, zchk_fs_b, zchk_fw_b ! Check conservation (C Rousset)
-      REAL(wp) :: zchk_vmin, zchk_amin, zchk_amax ! Check errors (C Rousset)
-      ! mass and salt flux (clem)
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zviold, zvsold, zsmvold   ! old ice volume...
+      INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
+      INTEGER  ::   i_ice_switch
+      REAL(wp) ::   zsal
+      !
+      REAL(wp) :: zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b 
       !!-------------------------------------------------------------------
       IF( nn_timing == 1 )  CALL timing_start('limupdate1')
 
-      CALL wrk_alloc( jkmax, zthick0, zqm0 )
-
-      CALL wrk_alloc( jpi,jpj,jpl,zviold, zvsold, zsmvold )   ! clem
-
-      !------------------------------------------------------------------------------
-      ! 1. Update of Global variables                                               |
-      !------------------------------------------------------------------------------
-
-      !-----------------
-      !  Trend terms
-      !-----------------
-      d_u_ice_dyn(:,:)     = u_ice(:,:)     - old_u_ice(:,:)
-      d_v_ice_dyn(:,:)     = v_ice(:,:)     - old_v_ice(:,:)
-      d_a_i_trp  (:,:,:)   = a_i  (:,:,:)   - old_a_i  (:,:,:)
-      d_v_s_trp  (:,:,:)   = v_s  (:,:,:)   - old_v_s  (:,:,:)  
-      d_v_i_trp  (:,:,:)   = v_i  (:,:,:)   - old_v_i  (:,:,:)   
-      d_e_s_trp  (:,:,:,:) = e_s  (:,:,:,:) - old_e_s  (:,:,:,:)  
-      d_e_i_trp  (:,:,:,:) = e_i  (:,:,:,:) - old_e_i  (:,:,:,:)
-      d_oa_i_trp (:,:,:)   = oa_i (:,:,:)   - old_oa_i (:,:,:)
-      d_smv_i_trp(:,:,:)   = 0._wp
-      IF(  num_sal == 2  )   d_smv_i_trp(:,:,:)  = smv_i(:,:,:) - old_smv_i(:,:,:)
-
-      ! mass and salt flux init (clem)
-      zviold(:,:,:) = v_i(:,:,:)
-      zvsold(:,:,:) = v_s(:,:,:)
-      zsmvold(:,:,:) = smv_i(:,:,:)
-
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_v_i_b = glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_smv_b = glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_fw_b  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) )
-         zchk_fs_b  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) )
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      IF( ln_limdyn ) THEN 
+
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limupdate1', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
+
+      !-----------------
+      ! zap small values
+      !-----------------
+      CALL lim_itd_me_zapsmall
 
       CALL lim_var_glo2eqv
-
-      !--------------------------------------
-      ! 2. Review of all pathological cases
-      !--------------------------------------
-
-! clem: useless now
-      !-------------------------------------------
-      ! 2.1) Advection of ice in an ice-free cell
-      !-------------------------------------------
-      ! should be removed since it is treated after dynamics now
-!      zhimax = 5._wp
-!      ! first category
-!      DO jj = 1, jpj
-!         DO ji = 1, jpi
-!            !--- the thickness of such an ice is often out of bounds
-!            !--- thus we recompute a new area while conserving ice volume
-!            zat_i_old = SUM( old_a_i(ji,jj,:) )
-!            zindb     = MAX( 0._wp, SIGN( 1._wp, ABS( d_a_i_trp(ji,jj,1) ) - epsi10 ) ) 
-!            IF( ( ABS( d_v_i_trp(ji,jj,1) ) / MAX( ABS( d_a_i_trp(ji,jj,1) ), epsi10 ) * zindb .GT. zhimax ) &
-!              &   .AND.( ( v_i(ji,jj,1) / MAX( a_i(ji,jj,1), epsi10 ) * zindb ) .GT. zhimax ) &
-!              &   .AND.( zat_i_old .LT. 1.e-6 ) )  THEN ! new line
-!               ht_i(ji,jj,1) = hi_max(1) * 0.5_wp
-!               a_i (ji,jj,1) = v_i(ji,jj,1) / ht_i(ji,jj,1)
-!            ENDIF
-!         END DO
-!      END DO
-!
-!      zhimax = 20._wp
-!      ! other categories
-!      DO jl = 2, jpl
-!         jm = ice_types(jl)
-!         DO jj = 1, jpj
-!            DO ji = 1, jpi
-!               zindb =  MAX( rzero, SIGN( rone, ABS( d_a_i_trp(ji,jj,jl) ) - epsi10 ) ) 
-!               ! this correction is very tricky... sometimes, advection gets wrong i don't know why
-!               ! it makes problems when the advected volume and concentration do not seem to be 
-!               ! related with each other
-!               ! the new thickness is sometimes very big!
-!               ! and sometimes d_a_i_trp and d_v_i_trp have different sign
-!               ! which of course is plausible
-!               ! but fuck! it fucks everything up :)
-!               IF ( ( ABS( d_v_i_trp(ji,jj,jl) ) / MAX( ABS( d_a_i_trp(ji,jj,jl) ), epsi10 ) * zindb .GT. zhimax ) &
-!                  &  .AND. ( v_i(ji,jj,jl) / MAX( a_i(ji,jj,jl), epsi10 ) * zindb ) .GT. zhimax ) THEN
-!                  ht_i(ji,jj,jl) = ( hi_max_typ(jl-ice_cat_bounds(jm,1),jm) + hi_max_typ(jl-ice_cat_bounds(jm,1)+1,jm) ) * 0.5_wp
-!                  a_i (ji,jj,jl) = v_i(ji,jj,jl) / ht_i(ji,jj,jl)
-!               ENDIF
-!            END DO ! ji
-!         END DO !jj
-!      END DO !jl
      
+      !----------------------------------------------------
+      ! Rebin categories with thickness out of bounds
+      !----------------------------------------------------
+      IF ( jpl > 1 )   CALL lim_itd_th_reb(1, jpl)
+
       at_i(:,:) = 0._wp
       DO jl = 1, jpl
@@ -190,10 +98,15 @@
 
       !----------------------------------------------------
-      ! 2.2) Rebin categories with thickness out of bounds
-      !----------------------------------------------------
-      DO jm = 1, jpm
-         jbnd1 = ice_cat_bounds(jm,1)
-         jbnd2 = ice_cat_bounds(jm,2)
-         IF (ice_ncat_types(jm) .GT. 1 )   CALL lim_itd_th_reb(jbnd1, jbnd2, jm)
+      ! ice concentration should not exceed amax 
+      !-----------------------------------------------------
+      DO jl  = 1, jpl
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( at_i(ji,jj) > amax .AND. a_i(ji,jj,jl) > 0._wp ) THEN
+                  a_i(ji,jj,jl)  = a_i(ji,jj,jl) * ( 1._wp - ( 1._wp - amax / at_i(ji,jj) ) )
+                  ht_i(ji,jj,jl) = v_i(ji,jj,jl) / a_i(ji,jj,jl)
+               ENDIF
+            END DO
+         END DO
       END DO
 
@@ -202,190 +115,50 @@
          at_i(:,:) = a_i(:,:,jl) + at_i(:,:)
       END DO
-
-      zbigvalue      = 1.0e+20
-
-      DO jl = 1, jpl
-         DO jj = 1, jpj 
-            DO ji = 1, jpi
-
-               !switches
-               zindb         = MAX( rzero, SIGN( rone, a_i(ji,jj,jl) - epsi10 ) ) 
-               !switch = 1 if a_i > 1e-06 and 0 if not
-               zindsn        = MAX( rzero, SIGN( rone, v_s(ji,jj,jl) - epsi10 ) ) !=1 if hs > 1e-10 and 0 if not
-               zindic        = MAX( rzero, SIGN( rone, v_i(ji,jj,jl) - epsi10 ) ) !=1 if hi > 1e-10 and 0 if not
-               ! bug fix 25 avril 2007
-               zindb         = zindb*zindic
-
-               !--- 2.3 Correction to ice age 
-               !------------------------------
-               !                IF ((o_i(ji,jj,jl)-1.0)*rday.gt.(rdt_ice*float(numit))) THEN
-               !                   o_i(ji,jj,jl) = rdt_ice*FLOAT(numit)/rday
-               !                ENDIF
-               IF ((oa_i(ji,jj,jl)-1.0)*rday.gt.(rdt_ice*numit*a_i(ji,jj,jl))) THEN
-                  oa_i(ji,jj,jl) = rdt_ice*numit/rday*a_i(ji,jj,jl)
-               ENDIF
-               oa_i(ji,jj,jl) = zindb*zindic*oa_i(ji,jj,jl)
-
-               !--- 2.4 Correction to snow thickness
-               !-------------------------------------
-               !          ! snow thickness has to be greater than 0, and if ice concentration smaller than 1e-6 then hs = 0
-               !             v_s(ji,jj,jl)  = MAX( zindb * v_s(ji,jj,jl), 0.0) 
-               ! snow thickness cannot be smaller than 1e-6
-               zdvres = (zindsn * zindb - 1._wp) * v_s(ji,jj,jl)
-               v_s(ji,jj,jl) = v_s(ji,jj,jl) + zdvres
-
-               !rdm_snw(ji,jj) = rdm_snw(ji,jj) + zdvres * rhosn
- 
-               !--- 2.5 Correction to ice thickness
-               !-------------------------------------
-               zdvres = (zindb - 1._wp) * v_i(ji,jj,jl)
-               v_i(ji,jj,jl) = v_i(ji,jj,jl) + zdvres
-
-               !rdm_ice(ji,jj) = rdm_ice(ji,jj) + zdvres * rhoic
-               !sfx_res(ji,jj)  = sfx_res(ji,jj) - sm_i(ji,jj,jl) * ( rhoic * zdvres / rdt_ice )
-
-               !--- 2.6 Snow is transformed into ice if the original ice cover disappears
-               !----------------------------------------------------------------------------
-               zindg          = tms(ji,jj) *  MAX( 0._wp, SIGN( 1._wp, -v_i(ji,jj,jl) ) )
-               zdvres         = zindg * rhosn * v_s(ji,jj,jl) / rau0
-               v_i(ji,jj,jl)  = v_i(ji,jj,jl)  + zdvres
-
-               zdvres         = zindsn*zindb * ( - zindg * v_s(ji,jj,jl) + zindg * v_i(ji,jj,jl) * ( rau0 - rhoic ) / rhosn )
-               v_s(ji,jj,jl)  = v_s(ji,jj,jl)  + zdvres
-
-               !--- 2.7 Correction to ice concentrations 
-               !--------------------------------------------
-               ! if greater than 0, ice concentration cannot be smaller than 1e-10
-               a_i(ji,jj,jl) = zindb * a_i(ji,jj,jl)
-
-               !-------------------------
-               ! 2.8) Snow heat content
-               !-------------------------
-               e_s(ji,jj,1,jl) = zindsn * ( MIN ( MAX ( 0._wp, e_s(ji,jj,1,jl) ), zbigvalue ) )
-
-            END DO ! ji
-         END DO ! jj
-      END DO ! jl
-
-      !------------------------
-      ! 2.9) Ice heat content 
-      !------------------------
-
-      DO jl = 1, jpl
-         DO jk = 1, nlay_i
+    
+      ! --------------------------------------
+      ! Final thickness distribution rebinning
+      ! --------------------------------------
+      IF ( jpl > 1 ) CALL lim_itd_th_reb(1, jpl)
+
+      !-----------------
+      ! zap small values
+      !-----------------
+      CALL lim_itd_me_zapsmall
+
+      !---------------------
+      ! Ice salinity bounds
+      !---------------------
+      IF (  num_sal == 2  ) THEN 
+         DO jl = 1, jpl
             DO jj = 1, jpj 
                DO ji = 1, jpi
-                  zindic        = MAX( rzero, SIGN( rone, v_i(ji,jj,jl) - epsi10 ) ) 
-                  e_i(ji,jj,jk,jl)= zindic * ( MIN ( MAX ( 0.0, e_i(ji,jj,jk,jl) ), zbigvalue ) )
-               END DO ! ji
-            END DO ! jj
-         END DO !jk
-      END DO !jl
- 
-      at_i(:,:) = 0._wp
-      DO jl = 1, jpl
-         at_i(:,:) = a_i(:,:,jl) + at_i(:,:)
-      END DO
-
-      !--- 2.13 ice concentration should not exceed amax 
-      !         (it should not be the case) 
-      !-----------------------------------------------------
-      DO jj = 1, jpj
-         DO ji = 1, jpi
-            z_da_ex =  MAX( at_i(ji,jj) - amax , 0.0 )        
-            zindb   =  MAX( rzero, SIGN( rone, at_i(ji,jj) - epsi10 ) ) 
-            DO jl  = 1, jpl
-               z_da_i = a_i(ji,jj,jl) * z_da_ex / MAX( at_i(ji,jj), epsi10 ) * zindb
-               a_i(ji,jj,jl) = MAX( 0._wp, a_i(ji,jj,jl) - z_da_i )
-               !
-               zinda   =  MAX( rzero, SIGN( rone, a_i(ji,jj,jl) - epsi10 ) ) 
-               ht_i(ji,jj,jl) = v_i(ji,jj,jl) / MAX( a_i(ji,jj,jl), epsi10 ) * zinda
-               !v_i(ji,jj,jl) = ht_i(ji,jj,jl) * a_i(ji,jj,jl) ! makes ice shrinken but should not be used
+                  zsal            = smv_i(ji,jj,jl)
+                  smv_i(ji,jj,jl) = sm_i(ji,jj,jl) * v_i(ji,jj,jl)
+                  ! salinity stays in bounds
+                  i_ice_switch    = 1._wp - MAX( 0._wp, SIGN( 1._wp, - v_i(ji,jj,jl) ) )
+                  smv_i(ji,jj,jl) = i_ice_switch * MAX( MIN( s_i_max * v_i(ji,jj,jl), smv_i(ji,jj,jl) ), s_i_min * v_i(ji,jj,jl) )
+                  ! associated salt flux
+                  sfx_res(ji,jj) = sfx_res(ji,jj) - ( smv_i(ji,jj,jl) - zsal ) * rhoic * r1_rdtice
+               END DO
             END DO
          END DO
-      END DO
-      at_i(:,:) = a_i(:,:,1)
-      DO jl = 2, jpl
-         at_i(:,:) = a_i(:,:,jl) + at_i(:,:)
-      END DO
-
-
-      ! Final thickness distribution rebinning
-      ! --------------------------------------
-      DO jm = 1, jpm
-         jbnd1 = ice_cat_bounds(jm,1)
-         jbnd2 = ice_cat_bounds(jm,2)
-         IF (ice_ncat_types(jm) .GT. 1 ) CALL lim_itd_th_reb(jbnd1, jbnd2, jm)
-         IF (ice_ncat_types(jm) .EQ. 1 ) THEN
-         ENDIF
-      END DO
-
-
-      !---------------------
-      ! 2.11) Ice salinity
-      !---------------------
-      ! clem correct bug on smv_i
-      smv_i(:,:,:) = sm_i(:,:,:) * v_i(:,:,:)
-
-      IF (  num_sal == 2  ) THEN ! general case
-         DO jl = 1, jpl
-            !DO jk = 1, nlay_i
-               DO jj = 1, jpj 
-                  DO ji = 1, jpi
-                     ! salinity stays in bounds
-                     !clem smv_i(ji,jj,jl)  =  MAX(MIN((rhoic-rhosn)/rhoic*sss_m(ji,jj),smv_i(ji,jj,jl)),0.1 * v_i(ji,jj,jl) )
-                     smv_i(ji,jj,jl) = MAX( MIN( s_i_max * v_i(ji,jj,jl), smv_i(ji,jj,jl) ), s_i_min * v_i(ji,jj,jl) )
-                     i_ice_switch    = 1._wp - MAX( 0._wp, SIGN( 1._wp, -v_i(ji,jj,jl) ) )
-                     smv_i(ji,jj,jl) = i_ice_switch * smv_i(ji,jj,jl) !+ s_i_min * ( 1._wp - i_ice_switch ) * v_i(ji,jj,jl)
-                  END DO ! ji
-               END DO ! jj
-            !END DO !jk
-         END DO !jl
       ENDIF
 
-      at_i(:,:) = a_i(:,:,1)
-      DO jl = 2, jpl
-         at_i(:,:) = a_i(:,:,jl) + at_i(:,:)
-      END DO
-
-
-      !--------------------------------
-      ! Update mass/salt fluxes (clem)
-      !--------------------------------
-      DO jl = 1, jpl
-         DO jj = 1, jpj 
-            DO ji = 1, jpi
-               diag_res_pr(ji,jj) = diag_res_pr(ji,jj) + ( v_i(ji,jj,jl) - zviold(ji,jj,jl) ) / rdt_ice 
-               rdm_ice(ji,jj) = rdm_ice(ji,jj) + ( v_i(ji,jj,jl) - zviold(ji,jj,jl) ) * rhoic 
-               rdm_snw(ji,jj) = rdm_snw(ji,jj) + ( v_s(ji,jj,jl) - zvsold(ji,jj,jl) ) * rhosn 
-               sfx_res(ji,jj) = sfx_res(ji,jj) - ( smv_i(ji,jj,jl) - zsmvold(ji,jj,jl) ) * rhoic / rdt_ice 
-            END DO
-         END DO
-      END DO
-  
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-
-         zchk_fs  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) ) - zchk_fs_b
-         zchk_fw  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) ) - zchk_fw_b
- 
-         zchk_v_i = ( glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_v_i_b - ( zchk_fw / rhoic ) ) * r1_rdtice
-         zchk_smv = ( glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_smv_b ) * r1_rdtice + ( zchk_fs / rhoic )
-
-         zchk_vmin = glob_min(v_i)
-         zchk_amax = glob_max(SUM(a_i,dim=3))
-         zchk_amin = glob_min(a_i)
-       
-         IF(lwp) THEN
-            IF ( ABS( zchk_v_i   ) >  1.e-5 ) WRITE(numout,*) 'violation volume [m3/day]     (limupdate1) = ',(zchk_v_i * rday)
-            IF ( ABS( zchk_smv   ) >  1.e-4 ) WRITE(numout,*) 'violation saline [psu*m3/day] (limupdate1) = ',(zchk_smv * rday)
-            IF ( zchk_vmin <  0.            ) WRITE(numout,*) 'violation v_i<0  [mm]         (limupdate1) = ',(zchk_vmin * 1.e-3)
-            IF ( zchk_amax >  amax+epsi10   ) WRITE(numout,*) 'violation a_i>amax            (limupdate1) = ',zchk_amax
-            IF ( zchk_amin <  0.            ) WRITE(numout,*) 'violation a_i<0               (limupdate1) = ',zchk_amin
-         ENDIF
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      ! -------------------------------------------------
+      ! Diagnostics
+      ! -------------------------------------------------
+      d_u_ice_dyn(:,:)     = u_ice(:,:)     - u_ice_b(:,:)
+      d_v_ice_dyn(:,:)     = v_ice(:,:)     - v_ice_b(:,:)
+      d_a_i_trp  (:,:,:)   = a_i  (:,:,:)   - a_i_b  (:,:,:)
+      d_v_s_trp  (:,:,:)   = v_s  (:,:,:)   - v_s_b  (:,:,:)  
+      d_v_i_trp  (:,:,:)   = v_i  (:,:,:)   - v_i_b  (:,:,:)   
+      d_e_s_trp  (:,:,:,:) = e_s  (:,:,:,:) - e_s_b  (:,:,:,:)  
+      d_e_i_trp  (:,:,1:nlay_i,:) = e_i  (:,:,1:nlay_i,:) - e_i_b(:,:,1:nlay_i,:)
+      d_oa_i_trp (:,:,:)   = oa_i (:,:,:)   - oa_i_b (:,:,:)
+      d_smv_i_trp(:,:,:)   = 0._wp
+      IF(  num_sal == 2  ) d_smv_i_trp(:,:,:) = smv_i(:,:,:) - smv_i_b(:,:,:)
+
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(1, 'limupdate1', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
 
       IF(ln_ctl) THEN   ! Control print
@@ -400,5 +173,5 @@
          CALL prt_ctl(tab2d_1=u_ice      , clinfo1=' lim_update1  : u_ice       :', tab2d_2=v_ice      , clinfo2=' v_ice       :')
          CALL prt_ctl(tab2d_1=d_u_ice_dyn, clinfo1=' lim_update1  : d_u_ice_dyn :', tab2d_2=d_v_ice_dyn, clinfo2=' d_v_ice_dyn :')
-         CALL prt_ctl(tab2d_1=old_u_ice  , clinfo1=' lim_update1  : old_u_ice   :', tab2d_2=old_v_ice  , clinfo2=' old_v_ice   :')
+         CALL prt_ctl(tab2d_1=u_ice_b    , clinfo1=' lim_update1  : u_ice_b     :', tab2d_2=v_ice_b    , clinfo2=' v_ice_b     :')
 
          DO jl = 1, jpl
@@ -413,26 +186,26 @@
             CALL prt_ctl(tab2d_1=o_i        (:,:,jl)        , clinfo1= ' lim_update1  : o_i         : ')
             CALL prt_ctl(tab2d_1=a_i        (:,:,jl)        , clinfo1= ' lim_update1  : a_i         : ')
-            CALL prt_ctl(tab2d_1=old_a_i    (:,:,jl)        , clinfo1= ' lim_update1  : old_a_i     : ')
+            CALL prt_ctl(tab2d_1=a_i_b      (:,:,jl)        , clinfo1= ' lim_update1  : a_i_b       : ')
             CALL prt_ctl(tab2d_1=d_a_i_trp  (:,:,jl)        , clinfo1= ' lim_update1  : d_a_i_trp   : ')
             CALL prt_ctl(tab2d_1=v_i        (:,:,jl)        , clinfo1= ' lim_update1  : v_i         : ')
-            CALL prt_ctl(tab2d_1=old_v_i    (:,:,jl)        , clinfo1= ' lim_update1  : old_v_i     : ')
+            CALL prt_ctl(tab2d_1=v_i_b      (:,:,jl)        , clinfo1= ' lim_update1  : v_i_b       : ')
             CALL prt_ctl(tab2d_1=d_v_i_trp  (:,:,jl)        , clinfo1= ' lim_update1  : d_v_i_trp   : ')
             CALL prt_ctl(tab2d_1=v_s        (:,:,jl)        , clinfo1= ' lim_update1  : v_s         : ')
-            CALL prt_ctl(tab2d_1=old_v_s    (:,:,jl)        , clinfo1= ' lim_update1  : old_v_s     : ')
+            CALL prt_ctl(tab2d_1=v_s_b      (:,:,jl)        , clinfo1= ' lim_update1  : v_s_b       : ')
             CALL prt_ctl(tab2d_1=d_v_s_trp  (:,:,jl)        , clinfo1= ' lim_update1  : d_v_s_trp   : ')
             CALL prt_ctl(tab2d_1=e_i        (:,:,1,jl)/1.0e9, clinfo1= ' lim_update1  : e_i1        : ')
-            CALL prt_ctl(tab2d_1=old_e_i    (:,:,1,jl)/1.0e9, clinfo1= ' lim_update1  : old_e_i1    : ')
+            CALL prt_ctl(tab2d_1=e_i_b      (:,:,1,jl)/1.0e9, clinfo1= ' lim_update1  : e_i1_b      : ')
             CALL prt_ctl(tab2d_1=d_e_i_trp  (:,:,1,jl)/1.0e9, clinfo1= ' lim_update1  : de_i1_trp   : ')
             CALL prt_ctl(tab2d_1=e_i        (:,:,2,jl)/1.0e9, clinfo1= ' lim_update1  : e_i2        : ')
-            CALL prt_ctl(tab2d_1=old_e_i    (:,:,2,jl)/1.0e9, clinfo1= ' lim_update1  : old_e_i2    : ')
+            CALL prt_ctl(tab2d_1=e_i_b      (:,:,2,jl)/1.0e9, clinfo1= ' lim_update1  : e_i2_b      : ')
             CALL prt_ctl(tab2d_1=d_e_i_trp  (:,:,2,jl)/1.0e9, clinfo1= ' lim_update1  : de_i2_trp   : ')
             CALL prt_ctl(tab2d_1=e_s        (:,:,1,jl)      , clinfo1= ' lim_update1  : e_snow      : ')
-            CALL prt_ctl(tab2d_1=old_e_s    (:,:,1,jl)      , clinfo1= ' lim_update1  : old_e_snow  : ')
+            CALL prt_ctl(tab2d_1=e_s_b      (:,:,1,jl)      , clinfo1= ' lim_update1  : e_snow_b    : ')
             CALL prt_ctl(tab2d_1=d_e_s_trp  (:,:,1,jl)/1.0e9, clinfo1= ' lim_update1  : d_e_s_trp   : ')
             CALL prt_ctl(tab2d_1=smv_i      (:,:,jl)        , clinfo1= ' lim_update1  : smv_i       : ')
-            CALL prt_ctl(tab2d_1=old_smv_i  (:,:,jl)        , clinfo1= ' lim_update1  : old_smv_i   : ')
+            CALL prt_ctl(tab2d_1=smv_i_b    (:,:,jl)        , clinfo1= ' lim_update1  : smv_i_b     : ')
             CALL prt_ctl(tab2d_1=d_smv_i_trp(:,:,jl)        , clinfo1= ' lim_update1  : d_smv_i_trp : ')
             CALL prt_ctl(tab2d_1=oa_i       (:,:,jl)        , clinfo1= ' lim_update1  : oa_i        : ')
-            CALL prt_ctl(tab2d_1=old_oa_i   (:,:,jl)        , clinfo1= ' lim_update1  : old_oa_i    : ')
+            CALL prt_ctl(tab2d_1=oa_i_b     (:,:,jl)        , clinfo1= ' lim_update1  : oa_i_b      : ')
             CALL prt_ctl(tab2d_1=d_oa_i_trp (:,:,jl)        , clinfo1= ' lim_update1  : d_oa_i_trp  : ')
 
@@ -446,7 +219,5 @@
          CALL prt_ctl_info(' - Heat / FW fluxes : ')
          CALL prt_ctl_info('   ~~~~~~~~~~~~~~~~~~ ')
-         CALL prt_ctl(tab2d_1=fmmec  , clinfo1= ' lim_update1 : fmmec : ', tab2d_2=fhmec     , clinfo2= ' fhmec     : ')
          CALL prt_ctl(tab2d_1=sst_m  , clinfo1= ' lim_update1 : sst   : ', tab2d_2=sss_m     , clinfo2= ' sss       : ')
-         CALL prt_ctl(tab2d_1=fhbri  , clinfo1= ' lim_update1 : fhbri : ', tab2d_2=fheat_mec , clinfo2= ' fheat_mec : ')
 
          CALL prt_ctl_info(' ')
@@ -458,8 +229,5 @@
       ENDIF
    
-
-      CALL wrk_dealloc( jkmax, zthick0, zqm0 )
-
-      CALL wrk_dealloc( jpi,jpj,jpl,zviold, zvsold, zsmvold )   ! clem
+      ENDIF ! ln_limdyn
 
       IF( nn_timing == 1 )  CALL timing_stop('limupdate1')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limupdate2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limupdate2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limupdate2.F90	(revision 5075)
@@ -5,4 +5,5 @@
    !!======================================================================
    !! History :  3.0  !  2006-04  (M. Vancoppenolle) Original code
+   !!            3.6  !  2014-06  (C. Rousset)       Complete rewriting/cleaning
    !!----------------------------------------------------------------------
 #if defined key_lim3
@@ -39,4 +40,5 @@
    USE lib_fortran     ! glob_sum
    USE timing          ! Timing
+   USE limcons        ! conservation tests
 
    IMPLICIT NONE
@@ -45,8 +47,4 @@
    PUBLIC   lim_update2   ! routine called by ice_step
 
-      REAL(wp)  ::   epsi10 = 1.e-10_wp   !    -       -
-      REAL(wp)  ::   rzero  = 0._wp       !    -       -
-      REAL(wp)  ::   rone   = 1._wp       !    -       -
-         
    !! * Substitutions
 #  include "vectopt_loop_substitute.h90"
@@ -64,120 +62,46 @@
       !! ** Purpose :  Computes update of sea-ice global variables at 
       !!               the end of the time step.
-      !!               Address pathological cases
-      !!               This place is very important
-      !!                
-      !! ** Method  :  
-      !!    Ice speed from ice dynamics
-      !!    Ice thickness, Snow thickness, Temperatures, Lead fraction
-      !!      from advection and ice thermodynamics 
       !!
-      !! ** Action  : - 
       !!---------------------------------------------------------------------
-      INTEGER ::   ji, jj, jk, jl, jm    ! dummy loop indices
-      INTEGER ::   jbnd1, jbnd2
-      INTEGER ::   i_ice_switch
-      INTEGER ::   ind_im, layer      ! indices for internal melt
-      REAL(wp) ::   zweight, zesum, zhimax, z_da_i
-      REAL(wp) ::   zinda, zindb, zindsn, zindic
-      REAL(wp) ::   zindg, zh, zdvres, zviold2
-      REAL(wp) ::   zbigvalue, zvsold2, z_da_ex
-      REAL(wp) ::   z_prescr_hi, zat_i_old, ztmelts, ze_s
-
-      INTEGER , POINTER, DIMENSION(:,:,:) ::  internal_melt
-      REAL(wp), POINTER, DIMENSION(:) ::   zthick0, zqm0      ! thickness of the layers and heat contents for
-      REAL(wp) :: zchk_v_i, zchk_smv, zchk_fs, zchk_fw, zchk_v_i_b, zchk_smv_b, zchk_fs_b, zchk_fw_b ! Check conservation (C Rousset)
-      REAL(wp) :: zchk_vmin, zchk_amin, zchk_amax ! Check errors (C Rousset)
-      ! mass and salt flux (clem)
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zviold, zvsold, zsmvold   ! old ice volume...
+      INTEGER  ::   ji, jj, jk, jl    ! dummy loop indices
+      INTEGER  ::   i_ice_switch
+      REAL(wp) ::   zh, zsal
+      !
+      REAL(wp) :: zvi_b, zsmv_b, zei_b, zfs_b, zfw_b, zft_b 
       !!-------------------------------------------------------------------
       IF( nn_timing == 1 )  CALL timing_start('limupdate2')
 
-      CALL wrk_alloc( jpi,jpj,jpl, internal_melt )   ! integer
-      CALL wrk_alloc( jkmax, zthick0, zqm0 )
-
-      CALL wrk_alloc( jpi,jpj,jpl,zviold, zvsold, zsmvold )   ! clem
-
-      !----------------------------------------------------------------------------------------
-      ! 1. Computation of trend terms      
-      !----------------------------------------------------------------------------------------
-      !- Trend terms
-      d_a_i_thd(:,:,:)   = a_i(:,:,:)   - old_a_i(:,:,:) 
-      d_v_s_thd(:,:,:)   = v_s(:,:,:)   - old_v_s(:,:,:)
-      d_v_i_thd(:,:,:)   = v_i(:,:,:)   - old_v_i(:,:,:)  
-      d_e_s_thd(:,:,:,:) = e_s(:,:,:,:) - old_e_s(:,:,:,:) 
-      d_e_i_thd(:,:,:,:) = e_i(:,:,:,:) - old_e_i(:,:,:,:)
-      !?? d_oa_i_thd(:,:,:)  = oa_i (:,:,:) - old_oa_i (:,:,:)
-      d_smv_i_thd(:,:,:) = 0._wp
-      IF( num_sal == 2 )   d_smv_i_thd(:,:,:) = smv_i(:,:,:) - old_smv_i(:,:,:)
-      ! diag only (clem)
-      dv_dt_thd(:,:,:) = d_v_i_thd(:,:,:) * r1_rdtice * rday
-
-      ! mass and salt flux init (clem)
-      zviold(:,:,:) = v_i(:,:,:)
-      zvsold(:,:,:) = v_s(:,:,:)
-      zsmvold(:,:,:) = smv_i(:,:,:)
-
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-         zchk_v_i_b = glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_smv_b = glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) )
-         zchk_fw_b  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) )
-         zchk_fs_b  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) )
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limupdate2', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
+
+      !-----------------
+      ! zap small values
+      !-----------------
+      CALL lim_itd_me_zapsmall
 
       CALL lim_var_glo2eqv
 
-      !--------------------------------------
-      ! 2. Review of all pathological cases
-      !--------------------------------------
-
-! clem: useless now
-      !-------------------------------------------
-      ! 2.1) Advection of ice in an ice-free cell
-      !-------------------------------------------
-      ! should be removed since it is treated after dynamics now
-!      zhimax = 5._wp
-!      ! first category
-!      DO jj = 1, jpj
-!         DO ji = 1, jpi
-!            !--- the thickness of such an ice is often out of bounds
-!            !--- thus we recompute a new area while conserving ice volume
-!            zat_i_old = SUM( old_a_i(ji,jj,:) )
-!            zindb     = MAX( 0._wp, SIGN( 1._wp, ABS( d_a_i_thd(ji,jj,1) ) - epsi10 ) ) 
-!            IF ( ( ABS( d_v_i_thd(ji,jj,1) ) / MAX( ABS( d_a_i_thd(ji,jj,1) ),epsi10 ) * zindb .GT. zhimax ) &
-!               &  .AND. ( ( v_i(ji,jj,1) / MAX( a_i(ji,jj,1), epsi10 ) * zindb ) .GT. zhimax ) &
-!               &  .AND. ( zat_i_old .LT. 1.e-6 ) )  THEN ! new line
-!               ht_i(ji,jj,1) = hi_max(1) * 0.5_wp
-!               a_i (ji,jj,1) = v_i(ji,jj,1) / ht_i(ji,jj,1)
-!            ENDIF
-!         END DO
-!      END DO
-
-!      zhimax = 20._wp
-!      ! other categories
-!      DO jl = 2, jpl
-!         jm = ice_types(jl)
-!         DO jj = 1, jpj
-!            DO ji = 1, jpi
-!               zindb =  MAX( rzero, SIGN( rone, ABS( d_a_i_thd(ji,jj,jl)) - epsi10 ) ) 
-!              ! this correction is very tricky... sometimes, advection gets wrong i don't know why
-!               ! it makes problems when the advected volume and concentration do not seem to be 
-!               ! related with each other
-!               ! the new thickness is sometimes very big!
-!               ! and sometimes d_a_i_trp and d_v_i_trp have different sign
-!               ! which of course is plausible
-!               ! but fuck! it fucks everything up :)
-!               IF ( ( ABS( d_v_i_thd(ji,jj,jl) ) / MAX( ABS( d_a_i_thd(ji,jj,jl) ), epsi10 ) * zindb .GT. zhimax ) &
-!                  &  .AND. ( v_i(ji,jj,jl) / MAX( a_i(ji,jj,jl), epsi10 ) * zindb ) .GT. zhimax ) THEN
-!                  ht_i(ji,jj,jl) = ( hi_max_typ(jl-ice_cat_bounds(jm,1),jm) + hi_max_typ(jl-ice_cat_bounds(jm,1)+1,jm) ) * 0.5_wp
-!                  a_i (ji,jj,jl) = v_i(ji,jj,jl) / ht_i(ji,jj,jl)
-!               ENDIF
-!            END DO ! ji
-!         END DO !jj
-!      END DO !jl
-     
+      !----------------------------------------------------
+      ! Rebin categories with thickness out of bounds
+      !----------------------------------------------------
+      IF ( jpl > 1 )   CALL lim_itd_th_reb(1, jpl)
+
+      !----------------------------------------------------------------------
+      ! Constrain the thickness of the smallest category above hiclim
+      !----------------------------------------------------------------------
+      DO jj = 1, jpj 
+         DO ji = 1, jpi
+            IF( v_i(ji,jj,1) > 0._wp .AND. ht_i(ji,jj,1) < hiclim ) THEN
+               zh             = hiclim / ht_i(ji,jj,1)
+               ht_s(ji,jj,1) = ht_s(ji,jj,1) * zh
+               ht_i(ji,jj,1) = ht_i(ji,jj,1) * zh
+               a_i (ji,jj,1) = a_i(ji,jj,1)  / zh
+            ENDIF
+         END DO
+      END DO
+      
+      !-----------------------------------------------------
+      ! ice concentration should not exceed amax 
+      !-----------------------------------------------------
       at_i(:,:) = 0._wp
       DO jl = 1, jpl
@@ -185,232 +109,14 @@
       END DO
 
-      !----------------------------------------------------
-      ! 2.2) Rebin categories with thickness out of bounds
-      !----------------------------------------------------
-      DO jm = 1, jpm
-         jbnd1 = ice_cat_bounds(jm,1)
-         jbnd2 = ice_cat_bounds(jm,2)
-         IF (ice_ncat_types(jm) .GT. 1 )   CALL lim_itd_th_reb(jbnd1, jbnd2, jm)
-      END DO
-
-      !---------------------------------
-      ! 2.3) Melt of an internal layer
-      !---------------------------------
-      internal_melt(:,:,:) = 0
-
-      DO jl = 1, jpl
-         DO jk = 1, nlay_i
-            DO jj = 1, jpj 
-               DO ji = 1, jpi
-                  ztmelts = - tmut * s_i(ji,jj,jk,jl) + rtt
-                  IF ( ( ( e_i(ji,jj,jk,jl) .LE. 0.0 ) .OR. ( t_i(ji,jj,jk,jl) .GE. ztmelts ) ) &
-                    & .AND. ( v_i(ji,jj,jl) .GT. 0.0 ) .AND. ( a_i(ji,jj,jl) .GT. 0.0 ) ) THEN
-                     internal_melt(ji,jj,jl) = 1
-                  ENDIF
-               END DO ! ji
-            END DO ! jj
-         END DO !jk
-      END DO !jl
-
-      DO jl = 1, jpl
-         DO jj = 1, jpj 
+      DO jl  = 1, jpl
+         DO jj = 1, jpj
             DO ji = 1, jpi
-               IF( internal_melt(ji,jj,jl) == 1 ) THEN
-                  ! initial ice thickness
-                  !-----------------------
+               IF( at_i(ji,jj) > amax .AND. a_i(ji,jj,jl) > 0._wp ) THEN
+                  a_i(ji,jj,jl)  = a_i(ji,jj,jl) * ( 1._wp - ( 1._wp - amax / at_i(ji,jj) ) )
                   ht_i(ji,jj,jl) = v_i(ji,jj,jl) / a_i(ji,jj,jl)
-
-                  ! reduce ice thickness
-                  !-----------------------
-                  ind_im = 0
-                  zesum = 0.0
-                  DO jk = 1, nlay_i
-                     ztmelts = - tmut * s_i(ji,jj,jk,jl) + rtt
-                     IF ( ( e_i(ji,jj,jk,jl) .LE. 0.0 ) .OR. ( t_i(ji,jj,jk,jl) .GE. ztmelts ) ) ind_im = ind_im + 1
-                     zesum = zesum + e_i(ji,jj,jk,jl)
-                  END DO
-                  ht_i(ji,jj,jl) = ht_i(ji,jj,jl) - REAL(ind_im)*ht_i(ji,jj,jl) / REAL(nlay_i)
-                  v_i(ji,jj,jl)  = ht_i(ji,jj,jl) * a_i(ji,jj,jl)
-
-                  !CLEM
-                  zdvres = REAL(ind_im)*ht_i(ji,jj,jl) / REAL(nlay_i) * a_i(ji,jj,jl)
-                  !rdm_ice(ji,jj) = rdm_ice(ji,jj) - zdvres * rhoic
-                  !sfx_res(ji,jj)  = sfx_res(ji,jj) + sm_i(ji,jj,jl) * ( rhoic * zdvres / rdt_ice )
-
-                  ! redistribute heat
-                  !-----------------------
-                  ! old thicknesses and enthalpies
-                  ind_im = 0
-                  DO jk = 1, nlay_i
-                     ztmelts = - tmut * s_i(ji,jj,jk,jl) + rtt
-                     IF ( ( e_i(ji,jj,jk,jl) .GT. 0.0 ) .AND.  & 
-                        ( t_i(ji,jj,jk,jl) .LT. ztmelts ) ) THEN
-                        ind_im = ind_im + 1
-                        zthick0(ind_im) = ht_i(ji,jj,jl) * REAL(ind_im / nlay_i)
-                        zqm0   (ind_im) = MAX( e_i(ji,jj,jk,jl) , 0.0 )
-                     ENDIF
-                  END DO
-
-                  ! Redistributing energy on the new grid
-                  IF ( ind_im .GT. 0 ) THEN
-
-                     DO jk = 1, nlay_i
-                        e_i(ji,jj,jk,jl) = 0.0
-                        DO layer = 1, ind_im
-                           zweight         = MAX (  &
-                              MIN( ht_i(ji,jj,jl) * REAL(layer/ind_im) , ht_i(ji,jj,jl) * REAL(jk / nlay_i) ) -       &
-                              MAX( ht_i(ji,jj,jl) * REAL((layer-1)/ind_im) , ht_i(ji,jj,jl) * REAL((jk-1) / nlay_i) ) , 0.0 ) &
-                              /  ( ht_i(ji,jj,jl) / REAL(ind_im) )
-
-                           e_i(ji,jj,jk,jl) =  e_i(ji,jj,jk,jl) + zweight*zqm0(layer)
-                        END DO !layer
-                     END DO ! jk
-
-                     zesum = 0.0
-                     DO jk = 1, nlay_i
-                        zesum = zesum + e_i(ji,jj,jk,jl)
-                     END DO
-
-                  ELSE ! ind_im .EQ. 0, total melt
-                     e_i(ji,jj,jk,jl) = 0.0
-                  ENDIF
-
-               ENDIF ! internal_melt
-
-            END DO ! ji
-         END DO !jj
-      END DO !jl
-
-      internal_melt(:,:,:) = 0
-
-
-      ! Melt of snow
-      !--------------
-      DO jl = 1, jpl
-         DO jj = 1, jpj 
-            DO ji = 1, jpi
-               ! snow energy of melting
-               zinda   =  MAX( 0._wp, SIGN( 1._wp, v_s(ji,jj,jl) - epsi10 ) )
-               ze_s = zinda * e_s(ji,jj,1,jl) * unit_fac / area(ji,jj) / MAX( v_s(ji,jj,jl), epsi10 )  ! snow energy of melting
-
-               ! If snow energy of melting smaller then Lf
-               ! Then all snow melts and meltwater, heat go to the ocean
-               IF ( ze_s .LE. rhosn * lfus ) internal_melt(ji,jj,jl) = 1
-
+               ENDIF
             END DO
          END DO
       END DO
-
-      DO jl = 1, jpl
-         DO jj = 1, jpj 
-            DO ji = 1, jpi
-               IF ( internal_melt(ji,jj,jl) == 1 ) THEN
-                  zdvres = v_s(ji,jj,jl)
-                  ! release heat
-                  fheat_res(ji,jj) = fheat_res(ji,jj) + ze_s * zdvres / rdt_ice
-                  ! release mass
-                  !rdm_snw(ji,jj) =  rdm_snw(ji,jj) - zdvres * rhosn
-                  !
-                  v_s(ji,jj,jl)   = 0.0
-                  e_s(ji,jj,1,jl) = 0.0
-                 ENDIF
-            END DO
-         END DO
-      END DO
-
-      zbigvalue      = 1.0e+20
-      DO jl = 1, jpl
-         DO jj = 1, jpj 
-            DO ji = 1, jpi
-
-               !switches
-               zindb         = MAX( rzero, SIGN( rone, a_i(ji,jj,jl) - epsi10 ) ) 
-               !switch = 1 if a_i > 1e-06 and 0 if not
-               zindsn        = MAX( rzero, SIGN( rone, v_s(ji,jj,jl) - epsi10 ) ) !=1 if hs > 1e-10 and 0 if not
-               zindic        = MAX( rzero, SIGN( rone, v_i(ji,jj,jl) - epsi10 ) ) !=1 if hi > 1e-10 and 0 if not
-               ! bug fix 25 avril 2007
-               zindb         = zindb*zindic
-
-               !--- 2.3 Correction to ice age 
-               !------------------------------
-               !                IF ((o_i(ji,jj,jl)-1.0)*rday.gt.(rdt_ice*float(numit))) THEN
-               !                   o_i(ji,jj,jl) = rdt_ice*FLOAT(numit)/rday
-               !                ENDIF
-               IF ((oa_i(ji,jj,jl)-1.0)*rday.gt.(rdt_ice*numit*a_i(ji,jj,jl))) THEN
-                  oa_i(ji,jj,jl) = rdt_ice*numit/rday*a_i(ji,jj,jl)
-               ENDIF
-               oa_i(ji,jj,jl) = zindb*zindic*oa_i(ji,jj,jl)
-
-               !--- 2.4 Correction to snow thickness
-               !-------------------------------------
-               zdvres = (zindsn * zindb - 1._wp) * v_s(ji,jj,jl)
-               v_s(ji,jj,jl) = v_s(ji,jj,jl) + zdvres
-
-               !rdm_snw(ji,jj) = rdm_snw(ji,jj) + zdvres * rhosn
- 
-               !--- 2.5 Correction to ice thickness
-               !-------------------------------------
-               zdvres = (zindb - 1._wp) * v_i(ji,jj,jl)
-               v_i(ji,jj,jl) = v_i(ji,jj,jl) + zdvres
-
-               !rdm_ice(ji,jj) = rdm_ice(ji,jj) + zdvres * rhoic
-               !sfx_res(ji,jj)  = sfx_res(ji,jj) - sm_i(ji,jj,jl) * ( rhoic * zdvres / rdt_ice )
-
-               !--- 2.6 Snow is transformed into ice if the original ice cover disappears
-               !----------------------------------------------------------------------------
-               zindg          = tms(ji,jj) *  MAX( 0._wp, SIGN( 1._wp, -v_i(ji,jj,jl) ) )
-               zdvres         = zindg * rhosn * v_s(ji,jj,jl) / rau0
-               v_i(ji,jj,jl)  = v_i(ji,jj,jl)  + zdvres
-
-               zdvres         = zindsn*zindb * ( - zindg * v_s(ji,jj,jl) + zindg * v_i(ji,jj,jl) * ( rau0 - rhoic ) / rhosn )
-               v_s(ji,jj,jl)  = v_s(ji,jj,jl)  + zdvres
-
-               !--- 2.7 Correction to ice concentrations 
-               !--------------------------------------------
-               a_i(ji,jj,jl) = zindb * a_i(ji,jj,jl)
-
-               !-------------------------
-               ! 2.8) Snow heat content
-               !-------------------------
-               e_s(ji,jj,1,jl) = zindsn * ( MIN ( MAX ( 0.0, e_s(ji,jj,1,jl) ), zbigvalue ) )
-
-            END DO ! ji
-         END DO ! jj
-      END DO ! jl
-
-      !------------------------
-      ! 2.9) Ice heat content 
-      !------------------------
-
-      DO jl = 1, jpl
-         DO jk = 1, nlay_i
-            DO jj = 1, jpj 
-               DO ji = 1, jpi
-                  zindic        = MAX( rzero, SIGN( rone, v_i(ji,jj,jl) - epsi10 ) ) 
-                  e_i(ji,jj,jk,jl)= zindic * ( MIN ( MAX ( 0.0, e_i(ji,jj,jk,jl) ), zbigvalue ) )
-               END DO ! ji
-            END DO ! jj
-         END DO !jk
-      END DO !jl
-
-
-      DO jm = 1, jpm
-         DO jj = 1, jpj 
-            DO ji = 1, jpi
-               jl = ice_cat_bounds(jm,1)
-               !--- 2.12 Constrain the thickness of the smallest category above 5 cm
-               !----------------------------------------------------------------------
-               zindb         = MAX( rzero, SIGN( rone, a_i(ji,jj,jl) - epsi10 ) ) 
-               ht_i(ji,jj,jl) = zindb*v_i(ji,jj,jl)/MAX(a_i(ji,jj,jl), epsi10)
-               zh            = MAX( rone , zindb * hiclim  / MAX( ht_i(ji,jj,jl) , epsi10 ) )
-               ht_s(ji,jj,jl) = ht_s(ji,jj,jl)* zh
-               ht_i(ji,jj,jl) = ht_i(ji,jj,jl)* zh
-               a_i (ji,jj,jl) = a_i(ji,jj,jl) / zh
-               !CLEM
-               v_i (ji,jj,jl) = a_i(ji,jj,jl) * ht_i(ji,jj,jl)
-               v_s (ji,jj,jl) = a_i(ji,jj,jl) * ht_s(ji,jj,jl)
-            END DO !ji
-         END DO !jj
-      END DO !jm
 
       at_i(:,:) = 0.0
@@ -418,64 +124,33 @@
          at_i(:,:) = a_i(:,:,jl) + at_i(:,:)
       END DO
-      
-      !--- 2.13 ice concentration should not exceed amax 
-      !         (it should not be the case) 
-      !-----------------------------------------------------
-      DO jj = 1, jpj
-         DO ji = 1, jpi
-            z_da_ex =  MAX( at_i(ji,jj) - amax , 0.0 )        
-            zindb   =  MAX( rzero, SIGN( rone, at_i(ji,jj) - epsi10 ) ) 
-            DO jl  = 1, jpl
-               z_da_i = a_i(ji,jj,jl) * z_da_ex / MAX( at_i(ji,jj), epsi10 ) * zindb
-               a_i(ji,jj,jl) = MAX( 0._wp, a_i(ji,jj,jl) - z_da_i )
-               !
-               zinda   =  MAX( rzero, SIGN( rone, a_i(ji,jj,jl) - epsi10 ) ) 
-               ht_i(ji,jj,jl) = v_i(ji,jj,jl) / MAX( a_i(ji,jj,jl), epsi10 ) * zinda
-               !v_i(ji,jj,jl) = ht_i(ji,jj,jl) * a_i(ji,jj,jl) ! makes ice shrinken but should not be used
-            END DO
-         END DO
-      END DO
-      at_i(:,:) = 0.0
-      DO jl = 1, jpl
-         at_i(:,:) = a_i(:,:,jl) + at_i(:,:)
-      END DO
-
+
+      ! --------------------------------------
       ! Final thickness distribution rebinning
       ! --------------------------------------
-      DO jm = 1, jpm
-         jbnd1 = ice_cat_bounds(jm,1)
-         jbnd2 = ice_cat_bounds(jm,2)
-         IF (ice_ncat_types(jm) .GT. 1 ) CALL lim_itd_th_reb(jbnd1, jbnd2, jm)
-         IF (ice_ncat_types(jm) .EQ. 1 ) THEN
-         ENDIF
-      END DO
+      IF ( jpl > 1 ) CALL lim_itd_th_reb( 1, jpl )
+
+      !-----------------
+      ! zap small values
+      !-----------------
+      CALL lim_itd_me_zapsmall
 
       !---------------------
       ! 2.11) Ice salinity
       !---------------------
-      ! clem correct bug on smv_i
-      smv_i(:,:,:) = sm_i(:,:,:) * v_i(:,:,:)
-
-      IF (  num_sal == 2  ) THEN ! general case
+      IF (  num_sal == 2  ) THEN 
          DO jl = 1, jpl
-            !DO jk = 1, nlay_i
-               DO jj = 1, jpj 
-                  DO ji = 1, jpi
-                     ! salinity stays in bounds
-                     !clem smv_i(ji,jj,jl)  =  MAX(MIN((rhoic-rhosn)/rhoic*sss_m(ji,jj),smv_i(ji,jj,jl)),0.1 * v_i(ji,jj,jl) )
-                     smv_i(ji,jj,jl) = MAX( MIN( s_i_max * v_i(ji,jj,jl), smv_i(ji,jj,jl) ), s_i_min * v_i(ji,jj,jl) )
-                     i_ice_switch    = 1._wp - MAX( 0._wp, SIGN( 1._wp, -v_i(ji,jj,jl) ) )
-                     smv_i(ji,jj,jl) = i_ice_switch * smv_i(ji,jj,jl) !+ s_i_min * ( 1._wp - i_ice_switch ) * v_i(ji,jj,jl)
-                  END DO ! ji
-               END DO ! jj
-            !END DO !jk
+            DO jj = 1, jpj 
+               DO ji = 1, jpi
+                  zsal            = smv_i(ji,jj,jl)
+                  smv_i(ji,jj,jl) = sm_i(ji,jj,jl) * v_i(ji,jj,jl)
+                  ! salinity stays in bounds
+                  i_ice_switch    = 1._wp - MAX( 0._wp, SIGN( 1._wp, - v_i(ji,jj,jl) ) )
+                  smv_i(ji,jj,jl) = i_ice_switch * MAX( MIN( s_i_max * v_i(ji,jj,jl), smv_i(ji,jj,jl) ), s_i_min * v_i(ji,jj,jl) ) !+ s_i_min * ( 1._wp - i_ice_switch ) * v_i(ji,jj,jl)
+                  ! associated salt flux
+                  sfx_res(ji,jj) = sfx_res(ji,jj) - ( smv_i(ji,jj,jl) - zsal ) * rhoic * r1_rdtice
+               END DO ! ji
+            END DO ! jj
          END DO !jl
       ENDIF
-
-      ! -------------------
-      at_i(:,:) = a_i(:,:,1)
-      DO jl = 2, jpl
-         at_i(:,:) = a_i(:,:,jl) + at_i(:,:)
-      END DO
 
       !------------------------------------------------------------------------------
@@ -486,9 +161,9 @@
       DO jj = 2, jpjm1
          DO ji = 2, jpim1
-            IF ( at_i(ji,jj) .EQ. 0.0 ) THEN ! what to do if there is no ice
-               IF ( at_i(ji+1,jj) .EQ. 0.0 ) u_ice(ji,jj)   = 0.0 ! right side
-               IF ( at_i(ji-1,jj) .EQ. 0.0 ) u_ice(ji-1,jj) = 0.0 ! left side
-               IF ( at_i(ji,jj+1) .EQ. 0.0 ) v_ice(ji,jj)   = 0.0 ! upper side
-               IF ( at_i(ji,jj-1) .EQ. 0.0 ) v_ice(ji,jj-1) = 0.0 ! bottom side
+            IF ( at_i(ji,jj) == 0._wp ) THEN ! what to do if there is no ice
+               IF ( at_i(ji+1,jj) == 0._wp ) u_ice(ji,jj)   = 0._wp ! right side
+               IF ( at_i(ji-1,jj) == 0._wp ) u_ice(ji-1,jj) = 0._wp ! left side
+               IF ( at_i(ji,jj+1) == 0._wp ) v_ice(ji,jj)   = 0._wp ! upper side
+               IF ( at_i(ji,jj-1) == 0._wp ) v_ice(ji,jj-1) = 0._wp ! bottom side
             ENDIF
          END DO
@@ -501,42 +176,29 @@
       v_ice(:,:) = v_ice(:,:) * tmv(:,:)
  
-      !--------------------------------
-      ! Update mass/salt fluxes (clem)
-      !--------------------------------
-      DO jl = 1, jpl
-         DO jj = 1, jpj 
-            DO ji = 1, jpi
-               diag_res_pr(ji,jj) = diag_res_pr(ji,jj) + ( v_i(ji,jj,jl) - zviold(ji,jj,jl) ) / rdt_ice 
-               rdm_ice(ji,jj) = rdm_ice(ji,jj) + ( v_i(ji,jj,jl) - zviold(ji,jj,jl) ) * rhoic 
-               rdm_snw(ji,jj) = rdm_snw(ji,jj) + ( v_s(ji,jj,jl) - zvsold(ji,jj,jl) ) * rhosn 
-               sfx_res(ji,jj) = sfx_res(ji,jj) - ( smv_i(ji,jj,jl) - zsmvold(ji,jj,jl) ) * rhoic / rdt_ice 
-            END DO
-         END DO
-      END DO
-
-      ! -------------------------------
-      !- check conservation (C Rousset)
-      IF (ln_limdiahsb) THEN
-
-         zchk_fs  = glob_sum( ( sfx_bri(:,:) + sfx_thd(:,:) + sfx_res(:,:) + sfx_mec(:,:) ) * area(:,:) * tms(:,:) ) - zchk_fs_b
-         zchk_fw  = glob_sum( rdm_ice(:,:) * area(:,:) * tms(:,:) ) - zchk_fw_b
- 
-         zchk_v_i = ( glob_sum( SUM(   v_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_v_i_b - ( zchk_fw / rhoic ) ) * r1_rdtice
-         zchk_smv = ( glob_sum( SUM( smv_i(:,:,:), dim=3 ) * area(:,:) * tms(:,:) ) - zchk_smv_b ) * r1_rdtice + ( zchk_fs / rhoic )
-
-         zchk_vmin = glob_min(v_i)
-         zchk_amax = glob_max(SUM(a_i,dim=3))
-         zchk_amin = glob_min(a_i)
-
-         IF(lwp) THEN
-            IF ( ABS( zchk_v_i   ) >  1.e-5 ) WRITE(numout,*) 'violation volume [m3/day]     (limupdate2) = ',(zchk_v_i * rday)
-            IF ( ABS( zchk_smv   ) >  1.e-4 ) WRITE(numout,*) 'violation saline [psu*m3/day] (limupdate2) = ',(zchk_smv * rday)
-            IF ( zchk_vmin <  0.            ) WRITE(numout,*) 'violation v_i<0  [mm]         (limupdate2) = ',(zchk_vmin * 1.e-3)
-            IF ( zchk_amax >  amax+epsi10   ) WRITE(numout,*) 'violation a_i>amax            (limupdate2) = ',zchk_amax
-            IF ( zchk_amin <  0.            ) WRITE(numout,*) 'violation a_i<0               (limupdate2) = ',zchk_amin
-         ENDIF
-      ENDIF
-      !- check conservation (C Rousset)
-      ! -------------------------------
+      ! -------------------------------------------------
+      ! Diagnostics
+      ! -------------------------------------------------
+      d_a_i_thd(:,:,:)   = a_i(:,:,:)   - a_i_b(:,:,:) 
+      d_v_s_thd(:,:,:)   = v_s(:,:,:)   - v_s_b(:,:,:)
+      d_v_i_thd(:,:,:)   = v_i(:,:,:)   - v_i_b(:,:,:)  
+      d_e_s_thd(:,:,:,:) = e_s(:,:,:,:) - e_s_b(:,:,:,:) 
+      d_e_i_thd(:,:,1:nlay_i,:) = e_i(:,:,1:nlay_i,:) - e_i_b(:,:,1:nlay_i,:)
+      !?? d_oa_i_thd(:,:,:)  = oa_i (:,:,:) - oa_i_b (:,:,:)
+      d_smv_i_thd(:,:,:) = 0._wp
+      IF( num_sal == 2 )   d_smv_i_thd(:,:,:) = smv_i(:,:,:) - smv_i_b(:,:,:)
+      ! diag only (clem)
+      dv_dt_thd(:,:,:) = d_v_i_thd(:,:,:) * r1_rdtice * rday
+
+      ! heat content variation (W.m-2)
+      DO jj = 1, jpj
+         DO ji = 1, jpi            
+            diag_heat_dhc(ji,jj) = ( SUM( d_e_i_trp(ji,jj,1:nlay_i,:) + d_e_i_thd(ji,jj,1:nlay_i,:) ) +  & 
+               &                     SUM( d_e_s_trp(ji,jj,1:nlay_s,:) + d_e_s_thd(ji,jj,1:nlay_s,:) )    &
+               &                   ) * unit_fac * r1_rdtice / area(ji,jj)   
+         END DO
+      END DO
+
+      ! conservation test
+      IF( ln_limdiahsb ) CALL lim_cons_hsm(0, 'limupdate2', zvi_b, zsmv_b, zei_b, zfw_b, zfs_b, zft_b)
 
       IF(ln_ctl) THEN   ! Control print
@@ -550,5 +212,5 @@
          CALL prt_ctl(tab2d_1=strength   , clinfo1=' lim_update2  : strength    :')
          CALL prt_ctl(tab2d_1=u_ice      , clinfo1=' lim_update2  : u_ice       :', tab2d_2=v_ice      , clinfo2=' v_ice       :')
-         CALL prt_ctl(tab2d_1=old_u_ice  , clinfo1=' lim_update2  : old_u_ice   :', tab2d_2=old_v_ice  , clinfo2=' old_v_ice   :')
+         CALL prt_ctl(tab2d_1=u_ice_b    , clinfo1=' lim_update2  : u_ice_b     :', tab2d_2=v_ice_b    , clinfo2=' v_ice_b     :')
 
          DO jl = 1, jpl
@@ -563,26 +225,26 @@
             CALL prt_ctl(tab2d_1=o_i        (:,:,jl)        , clinfo1= ' lim_update2  : o_i         : ')
             CALL prt_ctl(tab2d_1=a_i        (:,:,jl)        , clinfo1= ' lim_update2  : a_i         : ')
-            CALL prt_ctl(tab2d_1=old_a_i    (:,:,jl)        , clinfo1= ' lim_update2  : old_a_i     : ')
+            CALL prt_ctl(tab2d_1=a_i_b      (:,:,jl)        , clinfo1= ' lim_update2  : a_i_b       : ')
             CALL prt_ctl(tab2d_1=d_a_i_thd  (:,:,jl)        , clinfo1= ' lim_update2  : d_a_i_thd   : ')
             CALL prt_ctl(tab2d_1=v_i        (:,:,jl)        , clinfo1= ' lim_update2  : v_i         : ')
-            CALL prt_ctl(tab2d_1=old_v_i    (:,:,jl)        , clinfo1= ' lim_update2  : old_v_i     : ')
+            CALL prt_ctl(tab2d_1=v_i_b      (:,:,jl)        , clinfo1= ' lim_update2  : v_i_b       : ')
             CALL prt_ctl(tab2d_1=d_v_i_thd  (:,:,jl)        , clinfo1= ' lim_update2  : d_v_i_thd   : ')
             CALL prt_ctl(tab2d_1=v_s        (:,:,jl)        , clinfo1= ' lim_update2  : v_s         : ')
-            CALL prt_ctl(tab2d_1=old_v_s    (:,:,jl)        , clinfo1= ' lim_update2  : old_v_s     : ')
+            CALL prt_ctl(tab2d_1=v_s_b      (:,:,jl)        , clinfo1= ' lim_update2  : v_s_b       : ')
             CALL prt_ctl(tab2d_1=d_v_s_thd  (:,:,jl)        , clinfo1= ' lim_update2  : d_v_s_thd   : ')
             CALL prt_ctl(tab2d_1=e_i        (:,:,1,jl)/1.0e9, clinfo1= ' lim_update2  : e_i1        : ')
-            CALL prt_ctl(tab2d_1=old_e_i    (:,:,1,jl)/1.0e9, clinfo1= ' lim_update2  : old_e_i1    : ')
+            CALL prt_ctl(tab2d_1=e_i_b      (:,:,1,jl)/1.0e9, clinfo1= ' lim_update2  : e_i1_b      : ')
             CALL prt_ctl(tab2d_1=d_e_i_thd  (:,:,1,jl)/1.0e9, clinfo1= ' lim_update2  : de_i1_thd   : ')
             CALL prt_ctl(tab2d_1=e_i        (:,:,2,jl)/1.0e9, clinfo1= ' lim_update2  : e_i2        : ')
-            CALL prt_ctl(tab2d_1=old_e_i    (:,:,2,jl)/1.0e9, clinfo1= ' lim_update2  : old_e_i2    : ')
+            CALL prt_ctl(tab2d_1=e_i_b      (:,:,2,jl)/1.0e9, clinfo1= ' lim_update2  : e_i2_b      : ')
             CALL prt_ctl(tab2d_1=d_e_i_thd  (:,:,2,jl)/1.0e9, clinfo1= ' lim_update2  : de_i2_thd   : ')
             CALL prt_ctl(tab2d_1=e_s        (:,:,1,jl)      , clinfo1= ' lim_update2  : e_snow      : ')
-            CALL prt_ctl(tab2d_1=old_e_s    (:,:,1,jl)      , clinfo1= ' lim_update2  : old_e_snow  : ')
+            CALL prt_ctl(tab2d_1=e_s_b      (:,:,1,jl)      , clinfo1= ' lim_update2  : e_snow_b    : ')
             CALL prt_ctl(tab2d_1=d_e_s_thd  (:,:,1,jl)/1.0e9, clinfo1= ' lim_update2  : d_e_s_thd   : ')
             CALL prt_ctl(tab2d_1=smv_i      (:,:,jl)        , clinfo1= ' lim_update2  : smv_i       : ')
-            CALL prt_ctl(tab2d_1=old_smv_i  (:,:,jl)        , clinfo1= ' lim_update2  : old_smv_i   : ')
+            CALL prt_ctl(tab2d_1=smv_i_b    (:,:,jl)        , clinfo1= ' lim_update2  : smv_i_b     : ')
             CALL prt_ctl(tab2d_1=d_smv_i_thd(:,:,jl)        , clinfo1= ' lim_update2  : d_smv_i_thd : ')
             CALL prt_ctl(tab2d_1=oa_i       (:,:,jl)        , clinfo1= ' lim_update2  : oa_i        : ')
-            CALL prt_ctl(tab2d_1=old_oa_i   (:,:,jl)        , clinfo1= ' lim_update2  : old_oa_i    : ')
+            CALL prt_ctl(tab2d_1=oa_i_b     (:,:,jl)        , clinfo1= ' lim_update2  : oa_i_b      : ')
             CALL prt_ctl(tab2d_1=d_oa_i_thd (:,:,jl)        , clinfo1= ' lim_update2  : d_oa_i_thd  : ')
 
@@ -596,7 +258,5 @@
          CALL prt_ctl_info(' - Heat / FW fluxes : ')
          CALL prt_ctl_info('   ~~~~~~~~~~~~~~~~~~ ')
-         CALL prt_ctl(tab2d_1=fmmec  , clinfo1= ' lim_update2 : fmmec : ', tab2d_2=fhmec     , clinfo2= ' fhmec     : ')
          CALL prt_ctl(tab2d_1=sst_m  , clinfo1= ' lim_update2 : sst   : ', tab2d_2=sss_m     , clinfo2= ' sss       : ')
-         CALL prt_ctl(tab2d_1=fhbri  , clinfo1= ' lim_update2 : fhbri : ', tab2d_2=fheat_mec , clinfo2= ' fheat_mec : ')
 
          CALL prt_ctl_info(' ')
@@ -608,10 +268,6 @@
       ENDIF
    
-      CALL wrk_dealloc( jpi,jpj,jpl, internal_melt )   ! integer
-      CALL wrk_dealloc( jkmax, zthick0, zqm0 )
-
-      CALL wrk_dealloc( jpi,jpj,jpl,zviold, zvsold, zsmvold )   ! clem
-
       IF( nn_timing == 1 )  CALL timing_stop('limupdate2')
+
    END SUBROUTINE lim_update2
 #else
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limvar.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limvar.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limvar.F90	(revision 5075)
@@ -66,8 +66,4 @@
    PUBLIC   lim_var_salprof1d    !
 
-   REAL(wp) ::   epsi10 = 1.e-10_wp   !    -       -
-   REAL(wp) ::   zzero = 0.e0        !    -       -
-   REAL(wp) ::   zone  = 1.e0        !    -       -
-
    !!----------------------------------------------------------------------
    !! NEMO/LIM3 4.0 , UCL - NEMO Consortium (2011)
@@ -94,5 +90,4 @@
       !
       INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
-      REAL(wp) ::   zinda, zindb
       !!------------------------------------------------------------------
 
@@ -113,6 +108,6 @@
                at_i(ji,jj) = at_i(ji,jj) + a_i(ji,jj,jl) ! ice concentration
                !
-               zinda = MAX( zzero , SIGN( zone , at_i(ji,jj) - epsi10 ) ) 
-               icethi(ji,jj) = vt_i(ji,jj) / MAX( at_i(ji,jj) , epsi10 ) * zinda  ! ice thickness
+               rswitch = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi10 ) ) 
+               icethi(ji,jj) = vt_i(ji,jj) / MAX( at_i(ji,jj) , epsi10 ) * rswitch  ! ice thickness
             END DO
          END DO
@@ -134,9 +129,9 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zinda = MAX( zzero , SIGN( zone , vt_i(ji,jj) - epsi10 ) ) 
-                  zindb = MAX( zzero , SIGN( zone , at_i(ji,jj) - epsi10 ) ) 
                   et_s(ji,jj)  = et_s(ji,jj)  + e_s(ji,jj,1,jl)                                       ! snow heat content
-                  smt_i(ji,jj) = smt_i(ji,jj) + smv_i(ji,jj,jl) / MAX( vt_i(ji,jj) , epsi10 ) * zinda   ! ice salinity
-                  ot_i(ji,jj)  = ot_i(ji,jj)  + oa_i(ji,jj,jl)  / MAX( at_i(ji,jj) , epsi10 ) * zindb   ! ice age
+                  rswitch = MAX( 0._wp , SIGN( 1._wp , vt_i(ji,jj) - epsi10 ) ) 
+                  smt_i(ji,jj) = smt_i(ji,jj) + smv_i(ji,jj,jl) / MAX( vt_i(ji,jj) , epsi10 ) * rswitch   ! ice salinity
+                  rswitch = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi10 ) ) 
+                  ot_i(ji,jj)  = ot_i(ji,jj)  + oa_i(ji,jj,jl)  / MAX( at_i(ji,jj) , epsi10 ) * rswitch   ! ice age
                END DO
             END DO
@@ -163,5 +158,5 @@
       INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
       REAL(wp) ::   zq_i, zaaa, zbbb, zccc, zdiscrim     ! local scalars
-      REAL(wp) ::   ztmelts, zindb, zq_s, zfac1, zfac2   !   -      -
+      REAL(wp) ::   ztmelts, zq_s, zfac1, zfac2   !   -      -
       !!------------------------------------------------------------------
 
@@ -172,8 +167,8 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               zindb = 1._wp - MAX( 0._wp , SIGN( 1._wp,- a_i(ji,jj,jl) + epsi10 ) )   !0 if no ice and 1 if yes
-               ht_i(ji,jj,jl) = v_i (ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi10 ) * zindb
-               ht_s(ji,jj,jl) = v_s (ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi10 ) * zindb
-               o_i(ji,jj,jl)  = oa_i(ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi10 ) * zindb
+               rswitch = 1._wp - MAX( 0._wp , SIGN( 1._wp,- a_i(ji,jj,jl) + epsi10 ) )   !0 if no ice and 1 if yes
+               ht_i(ji,jj,jl) = v_i (ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi10 ) * rswitch
+               ht_s(ji,jj,jl) = v_s (ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi10 ) * rswitch
+               o_i(ji,jj,jl)  = oa_i(ji,jj,jl) / MAX( a_i(ji,jj,jl) , epsi10 ) * rswitch
             END DO
          END DO
@@ -184,6 +179,6 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zindb = 1._wp - MAX( 0._wp , SIGN( 1._wp,- a_i(ji,jj,jl) + epsi10 ) )   !0 if no ice and 1 if yes
-                  sm_i(ji,jj,jl) = smv_i(ji,jj,jl) / MAX( v_i(ji,jj,jl) , epsi10 ) * zindb
+                  rswitch = 1._wp - MAX( 0._wp , SIGN( 1._wp,- a_i(ji,jj,jl) + epsi10 ) )   !0 if no ice and 1 if yes
+                  sm_i(ji,jj,jl) = smv_i(ji,jj,jl) / MAX( v_i(ji,jj,jl) , epsi10 ) * rswitch
                END DO
             END DO
@@ -205,7 +200,7 @@
                DO ji = 1, jpi
                   !                                                              ! Energy of melting q(S,T) [J.m-3]
-                  zq_i    = e_i(ji,jj,jk,jl) / area(ji,jj) / MAX( v_i(ji,jj,jl) , epsi10 ) * REAL(nlay_i,wp) 
-                  zindb   = 1.0 - MAX( 0.0 , SIGN( 1.0 , - v_i(ji,jj,jl) + epsi10 ) )     ! zindb = 0 if no ice and 1 if yes
-                  zq_i    = zq_i * unit_fac * zindb                              !convert units
+                  rswitch   = 1.0 - MAX( 0.0 , SIGN( 1.0 , - v_i(ji,jj,jl) + epsi10 ) )     ! rswitch = 0 if no ice and 1 if yes
+                  zq_i    = rswitch * e_i(ji,jj,jk,jl) / area(ji,jj) / MAX( v_i(ji,jj,jl) , epsi10 ) * REAL(nlay_i,wp) 
+                  zq_i    = zq_i * unit_fac                             !convert units
                   ztmelts = -tmut * s_i(ji,jj,jk,jl) + rtt                       ! Ice layer melt temperature
                   !
@@ -214,5 +209,5 @@
                   zccc       =  lfus * (ztmelts-rtt)
                   zdiscrim   =  SQRT( MAX(zbbb*zbbb - 4._wp*zaaa*zccc , 0._wp) )
-                  t_i(ji,jj,jk,jl) = rtt + zindb *( - zbbb - zdiscrim ) / ( 2.0 *zaaa )
+                  t_i(ji,jj,jk,jl) = rtt + rswitch *( - zbbb - zdiscrim ) / ( 2.0 *zaaa )
                   t_i(ji,jj,jk,jl) = MIN( rtt, MAX( 173.15_wp, t_i(ji,jj,jk,jl) ) )       ! 100-rtt < t_i < rtt
                END DO
@@ -231,9 +226,9 @@
                DO ji = 1, jpi
                   !Energy of melting q(S,T) [J.m-3]
-                  zq_s  = e_s(ji,jj,jk,jl) / ( area(ji,jj) * MAX( v_s(ji,jj,jl) , epsi10 ) ) * REAL(nlay_s,wp)
-                  zindb = 1._wp - MAX( 0._wp , SIGN( 1._wp , - v_s(ji,jj,jl) + epsi10 ) )     ! zindb = 0 if no ice and 1 if yes
-                  zq_s  = zq_s * unit_fac * zindb                                    ! convert units
+                  rswitch = 1._wp - MAX( 0._wp , SIGN( 1._wp , - v_s(ji,jj,jl) + epsi10 ) )     ! rswitch = 0 if no ice and 1 if yes
+                  zq_s  = rswitch * e_s(ji,jj,jk,jl) / ( area(ji,jj) * MAX( v_s(ji,jj,jl) , epsi10 ) ) * REAL(nlay_s,wp)
+                  zq_s  = zq_s * unit_fac                                    ! convert units
                   !
-                  t_s(ji,jj,jk,jl) = rtt + zindb * ( - zfac1 * zq_s + zfac2 )
+                  t_s(ji,jj,jk,jl) = rtt + rswitch * ( - zfac1 * zq_s + zfac2 )
                   t_s(ji,jj,jk,jl) = MIN( rtt, MAX( 173.15, t_s(ji,jj,jk,jl) ) )     ! 100-rtt < t_i < rtt
                END DO
@@ -250,6 +245,6 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zindb = (  1._wp - MAX( 0._wp , SIGN( 1._wp , - vt_i(ji,jj) + epsi10 ) )  )
-                  tm_i(ji,jj) = tm_i(ji,jj) + zindb * t_i(ji,jj,jk,jl) * v_i(ji,jj,jl)   &
+                  rswitch = (  1._wp - MAX( 0._wp , SIGN( 1._wp , - vt_i(ji,jj) + epsi10 ) )  )
+                  tm_i(ji,jj) = tm_i(ji,jj) + rswitch * t_i(ji,jj,jk,jl) * v_i(ji,jj,jl)   &
                      &                      / (  REAL(nlay_i,wp) * MAX( vt_i(ji,jj) , epsi10 )  )
                END DO
@@ -297,5 +292,5 @@
       INTEGER  ::   ji, jj, jk, jl   ! dummy loop index
       REAL(wp) ::   dummy_fac0, dummy_fac1, dummy_fac, zsal      ! local scalar
-      REAL(wp) ::   zind0, zind01, zindbal, zargtemp , zs_zero   !   -      -
+      REAL(wp) ::   zswi0, zswi01, zswibal, zargtemp , zs_zero   !   -      -
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   z_slope_s, zalpha   ! 3D pointer
       !!------------------------------------------------------------------
@@ -320,5 +315,5 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  z_slope_s(ji,jj,jl) = 2._wp * sm_i(ji,jj,jl) / MAX( 0.01 , ht_i(ji,jj,jl) )
+                  z_slope_s(ji,jj,jl) = 2._wp * sm_i(ji,jj,jl) / MAX( epsi10 , ht_i(ji,jj,jl) )
                END DO
             END DO
@@ -332,13 +327,13 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  ! zind0 = 1 if sm_i le s_i_0 and 0 otherwise
-                  zind0  = MAX( 0._wp   , SIGN( 1._wp  , s_i_0 - sm_i(ji,jj,jl) ) ) 
-                  ! zind01 = 1 if sm_i is between s_i_0 and s_i_1 and 0 othws 
-                  zind01 = ( 1._wp - zind0 ) * MAX( 0._wp   , SIGN( 1._wp  , s_i_1 - sm_i(ji,jj,jl) ) ) 
-                  ! If 2.sm_i GE sss_m then zindbal = 1
+                  ! zswi0 = 1 if sm_i le s_i_0 and 0 otherwise
+                  zswi0  = MAX( 0._wp   , SIGN( 1._wp  , s_i_0 - sm_i(ji,jj,jl) ) ) 
+                  ! zswi01 = 1 if sm_i is between s_i_0 and s_i_1 and 0 othws 
+                  zswi01 = ( 1._wp - zswi0 ) * MAX( 0._wp   , SIGN( 1._wp  , s_i_1 - sm_i(ji,jj,jl) ) ) 
+                  ! If 2.sm_i GE sss_m then zswibal = 1
                   ! this is to force a constant salinity profile in the Baltic Sea
-                  zindbal = MAX( 0._wp , SIGN( 1._wp , 2._wp * sm_i(ji,jj,jl) - sss_m(ji,jj) ) )
-                  zalpha(ji,jj,jl) = zind0  + zind01 * ( sm_i(ji,jj,jl) * dummy_fac0 + dummy_fac1 )
-                  zalpha(ji,jj,jl) = zalpha(ji,jj,jl) * ( 1._wp - zindbal )
+                  zswibal = MAX( 0._wp , SIGN( 1._wp , 2._wp * sm_i(ji,jj,jl) - sss_m(ji,jj) ) )
+                  zalpha(ji,jj,jl) = zswi0  + zswi01 * ( sm_i(ji,jj,jl) * dummy_fac0 + dummy_fac1 )
+                  zalpha(ji,jj,jl) = zalpha(ji,jj,jl) * ( 1._wp - zswibal )
                END DO
             END DO
@@ -392,5 +387,4 @@
       !!------------------------------------------------------------------
       INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
-      REAL(wp) ::   zindb   !   -      -
       !!------------------------------------------------------------------
 
@@ -401,6 +395,6 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zindb = (  1._wp - MAX( 0._wp , SIGN( 1._wp , - vt_i(ji,jj) + epsi10 ) )  )
-                  tm_i(ji,jj) = tm_i(ji,jj) + zindb * t_i(ji,jj,jk,jl) * v_i(ji,jj,jl)   &
+                  rswitch = (  1._wp - MAX( 0._wp , SIGN( 1._wp , - vt_i(ji,jj) + epsi10 ) )  )
+                  tm_i(ji,jj) = tm_i(ji,jj) + rswitch * t_i(ji,jj,jk,jl) * v_i(ji,jj,jl)   &
                      &                      / (  REAL(nlay_i,wp) * MAX( vt_i(ji,jj) , epsi10 )  )
                END DO
@@ -423,5 +417,5 @@
       !!------------------------------------------------------------------
       INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
-      REAL(wp) ::   zbvi, zinda, zindb      ! local scalars
+      REAL(wp) ::   zbvi             ! local scalars
       !!------------------------------------------------------------------
       !
@@ -431,9 +425,9 @@
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zinda = (  1._wp - MAX( 0._wp , SIGN( 1._wp , (t_i(ji,jj,jk,jl) - rtt) + epsi10 ) )  )
-                  zindb = (  1._wp - MAX( 0._wp , SIGN( 1._wp , - vt_i(ji,jj) + epsi10 ) )  )
-                  zbvi  = - zinda * tmut * s_i(ji,jj,jk,jl) / MIN( t_i(ji,jj,jk,jl) - rtt, - epsi10 )   &
+                  rswitch = (  1._wp - MAX( 0._wp , SIGN( 1._wp , (t_i(ji,jj,jk,jl) - rtt) + epsi10 ) )  )
+                  zbvi  = - rswitch * tmut * s_i(ji,jj,jk,jl) / MIN( t_i(ji,jj,jk,jl) - rtt, - epsi10 )   &
                      &                   * v_i(ji,jj,jl)    / REAL(nlay_i,wp)
-                  bv_i(ji,jj) = bv_i(ji,jj) + zindb * zbvi  / MAX( vt_i(ji,jj) , epsi10 )
+                  rswitch = (  1._wp - MAX( 0._wp , SIGN( 1._wp , - vt_i(ji,jj) + epsi10 ) )  )
+                  bv_i(ji,jj) = bv_i(ji,jj) + rswitch * zbvi  / MAX( vt_i(ji,jj) , epsi10 )
                END DO
             END DO
@@ -456,5 +450,5 @@
       INTEGER  ::   ii, ij  ! local integers
       REAL(wp) ::   dummy_fac0, dummy_fac1, dummy_fac2, zargtemp, zsal   ! local scalars
-      REAL(wp) ::   zalpha, zind0, zind01, zindbal, zs_zero              !   -      -
+      REAL(wp) ::   zalpha, zswi0, zswi01, zswibal, zs_zero              !   -      -
       !
       REAL(wp), POINTER, DIMENSION(:) ::   z_slope_s
@@ -466,5 +460,5 @@
       ! Vertically constant, constant in time
       !---------------------------------------
-      IF( num_sal == 1 )   s_i_b(:,:) = bulk_sal
+      IF( num_sal == 1 )   s_i_1d(:,:) = bulk_sal
 
       !------------------------------------------------------
@@ -475,5 +469,5 @@
          !
          DO ji = kideb, kiut          ! Slope of the linear profile zs_zero
-            z_slope_s(ji) = 2._wp * sm_i_b(ji) / MAX( 0.01 , ht_i_b(ji) )
+            z_slope_s(ji) = 2._wp * sm_i_1d(ji) / MAX( epsi10 , ht_i_1d(ji) )
          END DO
 
@@ -490,17 +484,17 @@
                ii =  MOD( npb(ji) - 1 , jpi ) + 1
                ij =     ( npb(ji) - 1 ) / jpi + 1
-               ! zind0 = 1 if sm_i le s_i_0 and 0 otherwise
-               zind0  = MAX( 0._wp , SIGN( 1._wp  , s_i_0 - sm_i_b(ji) ) ) 
-               ! zind01 = 1 if sm_i is between s_i_0 and s_i_1 and 0 othws 
-               zind01 = ( 1._wp - zind0 ) * MAX( 0._wp , SIGN( 1._wp , s_i_1 - sm_i_b(ji) ) ) 
-               ! if 2.sm_i GE sss_m then zindbal = 1
+               ! zswi0 = 1 if sm_i le s_i_0 and 0 otherwise
+               zswi0  = MAX( 0._wp , SIGN( 1._wp  , s_i_0 - sm_i_1d(ji) ) ) 
+               ! zswi01 = 1 if sm_i is between s_i_0 and s_i_1 and 0 othws 
+               zswi01 = ( 1._wp - zswi0 ) * MAX( 0._wp , SIGN( 1._wp , s_i_1 - sm_i_1d(ji) ) ) 
+               ! if 2.sm_i GE sss_m then zswibal = 1
                ! this is to force a constant salinity profile in the Baltic Sea
-               zindbal = MAX( 0._wp , SIGN( 1._wp , 2._wp * sm_i_b(ji) - sss_m(ii,ij) ) )
+               zswibal = MAX( 0._wp , SIGN( 1._wp , 2._wp * sm_i_1d(ji) - sss_m(ii,ij) ) )
                !
-               zalpha = (  zind0 + zind01 * ( sm_i_b(ji) * dummy_fac0 + dummy_fac1 )  ) * ( 1.0 - zindbal )
+               zalpha = (  zswi0 + zswi01 * ( sm_i_1d(ji) * dummy_fac0 + dummy_fac1 )  ) * ( 1.0 - zswibal )
                !
-               zs_zero = z_slope_s(ji) * ( REAL(jk,wp) - 0.5_wp ) * ht_i_b(ji) * dummy_fac2
+               zs_zero = z_slope_s(ji) * ( REAL(jk,wp) - 0.5_wp ) * ht_i_1d(ji) * dummy_fac2
                ! weighting the profile
-               s_i_b(ji,jk) = zalpha * zs_zero + ( 1._wp - zalpha ) * sm_i_b(ji)
+               s_i_1d(ji,jk) = zalpha * zs_zero + ( 1._wp - zalpha ) * sm_i_1d(ji)
             END DO ! ji
          END DO ! jk
@@ -514,5 +508,5 @@
       IF( num_sal == 3 ) THEN      ! Schwarzacher (1959) multiyear salinity profile (mean = 2.30)
          !
-         sm_i_b(:) = 2.30_wp
+         sm_i_1d(:) = 2.30_wp
          !
 !CDIR NOVERRCHK
@@ -521,5 +515,5 @@
             zsal =  1.6_wp * (  1._wp - COS( rpi * zargtemp**(0.407_wp/(0.573_wp+zargtemp)) )  )
             DO ji = kideb, kiut
-               s_i_b(ji,jk) = zsal
+               s_i_1d(ji,jk) = zsal
             END DO
          END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limwri.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limwri.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limwri.F90	(revision 5075)
@@ -9,5 +9,4 @@
    !!----------------------------------------------------------------------
    !!   lim_wri      : write of the diagnostics variables in ouput file 
-   !!   lim_wri_init : initialization and namelist read
    !!   lim_wri_state : write for initial state or/and abandon
    !!----------------------------------------------------------------------
@@ -36,23 +35,4 @@
    PUBLIC lim_wri_state  ! called by dia_wri_state 
 
-   INTEGER, PARAMETER ::   jpnoumax = 43   !: maximum number of variable for ice output
-   
-   INTEGER  ::   noumef             ! number of fields
-   INTEGER  ::   noumefa            ! number of additional fields
-   INTEGER  ::   add_diag_swi       ! additional diagnostics
-   INTEGER  ::   nz                                         ! dimension for the itd field
-
-   REAL(wp) , DIMENSION(jpnoumax) ::   cmulti         ! multiplicative constant
-   REAL(wp) , DIMENSION(jpnoumax) ::   cadd           ! additive constant
-   REAL(wp) , DIMENSION(jpnoumax) ::   cmultia        ! multiplicative constant
-   REAL(wp) , DIMENSION(jpnoumax) ::   cadda          ! additive constant
-   CHARACTER(len = 35), DIMENSION(jpnoumax) ::   titn, titna   ! title of the field
-   CHARACTER(len = 8 ), DIMENSION(jpnoumax) ::   nam , nama    ! name of the field
-   CHARACTER(len = 8 ), DIMENSION(jpnoumax) ::   uni , unia    ! unit of the field
-   INTEGER            , DIMENSION(jpnoumax) ::   nc  , nca     ! switch for saving field ( = 1 ) or not ( = 0 )
-
-   REAL(wp)  ::   epsi06 = 1.e-6_wp
-   REAL(wp)  ::   zzero  = 0._wp
-   REAL(wp)  ::   zone   = 1._wp      
    !!----------------------------------------------------------------------
    !! NEMO/LIM3 4.0 , UCL - NEMO Consortium (2011)
@@ -78,300 +58,200 @@
       INTEGER, INTENT(in) ::   kindic   ! if kindic < 0 there has been an error somewhere
       !
-      INTEGER ::  ji, jj, jk, jl, jf, ipl ! dummy loop indices
-      INTEGER ::  ierr
-      REAL(wp),DIMENSION(1) ::   zdept
-      REAL(wp) ::  zsto, zjulian, zout, zindh, zinda, zindb, zindc
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zcmo, zcmoa
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::   zfield
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zmaskitd, zoi, zei
-
-      CHARACTER(len = 60) ::   clhstnam, clop, clhstnama
-
-      INTEGER , SAVE ::   nice, nhorid, ndim, niter, ndepid
-      INTEGER , SAVE ::   nicea, nhorida, ndimitd
-      INTEGER , ALLOCATABLE, DIMENSION(:), SAVE ::   ndex51
-      INTEGER , ALLOCATABLE, DIMENSION(:), SAVE ::   ndexitd
+      INTEGER  ::  ji, jj, jk, jl  ! dummy loop indices
+      REAL(wp) ::  z1_365
+      REAL(wp) ::  ztmp
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::  zoi, zei
+      REAL(wp), POINTER, DIMENSION(:,:)   ::  z2d, z2da, z2db, zswi    ! 2D workspace
       !!-------------------------------------------------------------------
 
       IF( nn_timing == 1 )  CALL timing_start('limwri')
 
-      CALL wrk_alloc( jpi, jpj, zfield )
-      CALL wrk_alloc( jpi, jpj, jpnoumax, zcmo, zcmoa )
-      CALL wrk_alloc( jpi, jpj, jpl, zmaskitd, zoi, zei )
-
-      ipl = jpl
-
-      IF( numit == nstart ) THEN 
-
-         ALLOCATE( ndex51(jpij), ndexitd(jpij*jpl), STAT=ierr )
-         IF( lk_mpp    )   CALL mpp_sum ( ierr )
-         IF( ierr /= 0 ) THEN
-            CALL ctl_stop( 'lim_wri : unable to allocate standard arrays' )   ;   RETURN
-         ENDIF
-
-         CALL lim_wri_init 
-
-         IF(lwp) WRITE(numout,*) ' lim_wri, first time step '
-         IF(lwp) WRITE(numout,*) ' add_diag_swi ', add_diag_swi
-
-         !--------------------
-         !  1) Initialization
-         !--------------------
-
-         !-------------
-         ! Normal file
-         !-------------
-         niter    = ( nit000 - 1 ) / nn_fsbc
-         CALL ymds2ju ( nyear, nmonth, nday, rdt, zjulian )
-         zjulian = zjulian - adatrj   !   set calendar origin to the beginning of the experiment
-!clem
-!         zsto     = rdt_ice
-!         IF( ln_mskland )   THEN   ;   clop = "ave(only(x))"   ! put 1.e+20 on land (very expensive!!)
-!         ELSE                      ;   clop = "ave(x)"         ! no use of the mask value (require less cpu time)
-!         ENDIF
-!         zout     = nwrite * rdt_ice / nn_fsbc
-!         zdept(1) = 0.
-!
-!         CALL dia_nam ( clhstnam, nwrite, 'icemod_old' )
-!         CALL histbeg ( clhstnam, jpi, glamt, jpj, gphit, 1, jpi, 1, jpj, niter, zjulian, rdt_ice,   &
-!            &           nhorid, nice, domain_id=nidom, snc4chunks=snc4set )
-!         CALL histvert( nice, "deptht", "Vertical T levels", "m", 1, zdept, ndepid, "down")
-!         CALL wheneq  ( jpij , tmask(:,:,1), 1, 1., ndex51, ndim)
-!
-!         DO jf = 1 , noumef
-!            IF(lwp) WRITE(numout,*) 'jf', jf
-!            IF ( nc(jf) == 1 ) THEN
-!               CALL histdef( nice, nam(jf), titn(jf), uni(jf), jpi, jpj &
-!                  , nhorid, 1, 1, 1, -99, 32, clop, zsto, zout )
-!               IF(lwp) WRITE(numout,*) 'nice, nam(jf), titn(jf), uni(jf), nhorid, clop, zsto, zout'
-!               IF(lwp) WRITE(numout,*)  nice, nam(jf), titn(jf), uni(jf), nhorid, clop, zsto, zout 
-!            ENDIF
-!         END DO
-!
-!         CALL histend(nice, snc4set)
-!clem
-         !
-         !-----------------
-         ! ITD file output
-         !-----------------
-         zsto     = rdt_ice
-         clop     = "ave(x)"
-         zout     = nwrite * rdt_ice / nn_fsbc
-         zdept(1) = 0.
-
-         CALL dia_nam ( clhstnama, nwrite, 'icemoa' )
-         CALL histbeg ( clhstnama, jpi, glamt, jpj, gphit,         &
-            1, jpi, 1, jpj,            & ! zoom
-            niter, zjulian, rdt_ice,   & ! time
-            nhorida,                   & ! ? linked with horizontal ...
-            nicea , domain_id=nidom, snc4chunks=snc4set)                  ! file 
-         CALL histvert( nicea, "icethi", "L levels","m", ipl , hi_mean , nz )
+      CALL wrk_alloc( jpi, jpj, jpl, zoi, zei )
+      CALL wrk_alloc( jpi, jpj     , z2d, z2da, z2db, zswi )
+
+      !-----------------------------
+      ! Mean category values
+      !-----------------------------
+
+      CALL lim_var_icetm      ! mean sea ice temperature
+
+      CALL lim_var_bv         ! brine volume
+
+      DO jj = 1, jpj          ! presence indicator of ice
+         DO ji = 1, jpi
+            zswi(ji,jj)  = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) - epsi06 ) )
+         END DO
+      END DO
+      !
+      !
+      !                                             
+      IF ( iom_use( "icethic_cea" ) ) THEN                       ! mean ice thickness
+         DO jj = 1, jpj 
+            DO ji = 1, jpi
+               z2d(ji,jj)  = vt_i(ji,jj) / MAX( at_i(ji,jj), epsi06 ) * zswi(ji,jj)
+            END DO
+         END DO
+         CALL iom_put( "icethic_cea"  , z2d              )
+      ENDIF
+
+      IF ( iom_use( "snowthic_cea" ) ) THEN                      ! snow thickness = mean snow thickness over the cell 
+         DO jj = 1, jpj                                            
+            DO ji = 1, jpi
+               z2d(ji,jj)  = vt_s(ji,jj) / MAX( at_i(ji,jj), epsi06 ) * zswi(ji,jj)
+            END DO
+         END DO
+         CALL iom_put( "snowthic_cea" , z2d              )       
+      ENDIF
+      !
+      IF ( iom_use( "uice_ipa" ) .OR. iom_use( "vice_ipa" ) .OR. iom_use( "icevel" ) ) THEN 
+         DO jj = 2 , jpjm1
+            DO ji = 2 , jpim1
+               z2da(ji,jj)  = (  u_ice(ji,jj) * tmu(ji,jj) + u_ice(ji-1,jj) * tmu(ji-1,jj) ) * 0.5_wp
+               z2db(ji,jj)  = (  v_ice(ji,jj) * tmv(ji,jj) + v_ice(ji,jj-1) * tmv(ji,jj-1) ) * 0.5_wp
+           END DO
+         END DO
+         CALL lbc_lnk( z2da, 'T', -1. )
+         CALL lbc_lnk( z2db, 'T', -1. )
+         CALL iom_put( "uice_ipa"     , z2da                )       ! ice velocity u component
+         CALL iom_put( "vice_ipa"     , z2db                )       ! ice velocity v component
+         DO jj = 1, jpj                                 
+            DO ji = 1, jpi
+               z2d(ji,jj)  = SQRT( z2da(ji,jj) * z2da(ji,jj) + z2db(ji,jj) * z2db(ji,jj) ) 
+            END DO
+         END DO
+         CALL iom_put( "icevel"       , z2d                 )       ! ice velocity module
+      ENDIF
+      !
+      IF ( iom_use( "miceage" ) ) THEN 
+         z2d(:,:) = 0.e0
          DO jl = 1, jpl
-            zmaskitd(:,:,jl) = tmask(:,:,1)
-         END DO
-         CALL wheneq  ( jpij , tmask(:,:,1), 1, 1., ndex51, ndim)
-         CALL wheneq( jpi*jpj*jpl, zmaskitd, 1, 1., ndexitd, ndimitd  )  
-         CALL histdef( nicea, "iice_itd", "Ice area in categories"         , "-"    ,   &  
-            jpi, jpj, nhorida, jpl, 1, jpl, nz, 15, clop, zsto, zout )
-         CALL histdef( nicea, "iice_hid", "Ice thickness in categories"    , "m"    ,   &  
-            jpi, jpj, nhorida, jpl, 1, jpl, nz, 15, clop, zsto, zout )
-         CALL histdef( nicea, "iice_hsd", "Snow depth in in categories"    , "m"    ,   &  
-            jpi, jpj, nhorida, jpl, 1, jpl, nz, 15, clop, zsto, zout )
-         CALL histdef( nicea, "iice_std", "Ice salinity distribution"      , "ppt"  ,   &  
-            jpi, jpj, nhorida, jpl, 1, jpl, nz, 15, clop, zsto, zout )
-         CALL histdef( nicea, "iice_otd", "Ice age distribution"               , "days",   &  
-            jpi, jpj, nhorida, jpl, 1, jpl, nz, 15, clop, zsto, zout )
-         CALL histdef( nicea, "iice_etd", "Brine volume distr. "               , "%"    ,   &  
-            jpi, jpj, nhorida, jpl, 1, jpl, nz, 15, clop, zsto, zout )
-         CALL histend(nicea, snc4set)
-      ENDIF
-
-      !     !-----------------------------------------------------------------------!
-      !     !--2. Computation of instantaneous values                               ! 
-      !     !-----------------------------------------------------------------------!
-
-      !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-      !IF( ln_nicep ) THEN
-      !   WRITE(numout,*)
-      !   WRITE(numout,*) 'lim_wri : write ice outputs in NetCDF files at time : ', nyear, nmonth, nday, numit
-      !   WRITE(numout,*) '~~~~~~~ '
-      !   WRITE(numout,*) ' kindic = ', kindic
-      !ENDIF
-      !++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
-
-      !-- calculs des valeurs instantanees
-      zcmo ( 1:jpi, 1:jpj, 1:jpnoumax ) = 0._wp
-      zcmoa( 1:jpi, 1:jpj, 1:jpnoumax ) = 0._wp
-
-      ! Ice surface temperature and some fluxes
-      DO jl = 1, jpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = z2d(ji,jj) + zswi(ji,jj) * oa_i(ji,jj,jl)
+               END DO
+            END DO
+         END DO
+         z1_365 = 1._wp / 365._wp
+         CALL iom_put( "miceage"     , z2d * z1_365         )        ! mean ice age
+      ENDIF
+
+      IF ( iom_use( "micet" ) ) THEN 
          DO jj = 1, jpj
             DO ji = 1, jpi
-               zinda  = MAX( zzero , SIGN( zone , at_i(ji,jj) - epsi06 ) )
-               zcmo(ji,jj,17) = zcmo(ji,jj,17) + a_i(ji,jj,jl)*qsr_ice (ji,jj,jl) 
-               zcmo(ji,jj,18) = zcmo(ji,jj,18) + a_i(ji,jj,jl)*qns_ice(ji,jj,jl) 
-               zcmo(ji,jj,27) = zcmo(ji,jj,27) + zinda*(t_su(ji,jj,jl)-rtt)*a_i(ji,jj,jl)/MAX(at_i(ji,jj),epsi06)
-               zcmo(ji,jj,21) = zcmo(ji,jj,21) + zinda*oa_i(ji,jj,jl)/MAX(at_i(ji,jj),epsi06) 
-            END DO
-         END DO
-      END DO
-
-      ! Mean sea ice temperature
-      CALL lim_var_icetm
-
-      ! Brine volume
-      CALL lim_var_bv
-
-      DO jj = 2 , jpjm1
-         DO ji = 2 , jpim1
-            zinda  = MAX( zzero , SIGN( zone , at_i(ji,jj) - epsi06 ) )
-            zindb  = MAX( zzero , SIGN( zone , at_i(ji,jj) ) )
-
-            zcmo(ji,jj,1)  = at_i(ji,jj)
-            zcmo(ji,jj,2)  = vt_i(ji,jj) / MAX( at_i(ji,jj), epsi06 ) * zinda
-            zcmo(ji,jj,3)  = vt_s(ji,jj) / MAX( at_i(ji,jj), epsi06 ) * zinda
-            zcmo(ji,jj,4)  = diag_bot_gr(ji,jj) * rday     ! Bottom thermodynamic ice production
-            zcmo(ji,jj,5)  = diag_dyn_gr(ji,jj) * rday     ! Dynamic ice production (rid/raft)
-            zcmo(ji,jj,22) = diag_lat_gr(ji,jj) * rday     ! Lateral thermodynamic ice production
-            zcmo(ji,jj,23) = diag_sni_gr(ji,jj) * rday     ! Snow ice production ice production
-            zcmo(ji,jj,24) = (tm_i(ji,jj) - rtt) * zinda
-
-            zcmo(ji,jj,6)  = fbif(ji,jj)*at_i(ji,jj)
-            zcmo(ji,jj,7)  = (  u_ice(ji,jj) * tmu(ji,jj) + u_ice(ji-1,jj) * tmu(ji-1,jj) ) * 0.5_wp
-            zcmo(ji,jj,8)  = (  v_ice(ji,jj) * tmv(ji,jj) + v_ice(ji,jj-1) * tmv(ji,jj-1) ) * 0.5_wp
-            zcmo(ji,jj,9)  = sst_m(ji,jj)
-            zcmo(ji,jj,10) = sss_m(ji,jj)
-
-            zcmo(ji,jj,11) = qns(ji,jj) + qsr(ji,jj)
-            zcmo(ji,jj,12) = qsr(ji,jj)
-            zcmo(ji,jj,13) = qns(ji,jj)
-            zcmo(ji,jj,14) = fhbri(ji,jj)
-            zcmo(ji,jj,15) = utau_ice(ji,jj)
-            zcmo(ji,jj,16) = vtau_ice(ji,jj)
-            zcmo(ji,jj,17) = zcmo(ji,jj,17) + ( 1._wp - at_i(ji,jj) ) * qsr(ji,jj)
-            zcmo(ji,jj,18) = zcmo(ji,jj,18) + ( 1._wp - at_i(ji,jj) ) * qns(ji,jj)
-            zcmo(ji,jj,19) = sprecip(ji,jj)
-            zcmo(ji,jj,20) = smt_i(ji,jj)
-            zcmo(ji,jj,25) = et_i(ji,jj)
-            zcmo(ji,jj,26) = et_s(ji,jj)
-            zcmo(ji,jj,28) = sfx_bri(ji,jj)
-            zcmo(ji,jj,29) = sfx_thd(ji,jj)
-
-            zcmo(ji,jj,30) = bv_i(ji,jj)
-            zcmo(ji,jj,31) = hicol(ji,jj) * zindb
-            zcmo(ji,jj,32) = strength(ji,jj)
-            zcmo(ji,jj,33) = SQRT(  zcmo(ji,jj,7)*zcmo(ji,jj,7) + zcmo(ji,jj,8)*zcmo(ji,jj,8)  )
-            zcmo(ji,jj,34) = diag_sur_me(ji,jj) * rday     ! Surface melt
-            zcmo(ji,jj,35) = diag_bot_me(ji,jj) * rday     ! Bottom melt
-            zcmo(ji,jj,36) = divu_i(ji,jj)
-            zcmo(ji,jj,37) = shear_i(ji,jj)
-            zcmo(ji,jj,38) = diag_res_pr(ji,jj) * rday     ! Bottom melt
-            zcmo(ji,jj,39) = vt_i(ji,jj)  ! ice volume
-            zcmo(ji,jj,40) = vt_s(ji,jj)  ! snow volume
-
-            zcmo(ji,jj,41) = sfx_mec(ji,jj)
-            zcmo(ji,jj,42) = sfx_res(ji,jj)
-
-            zcmo(ji,jj,43) = diag_trp_vi(ji,jj) * rday     ! transport of ice volume
-
-        END DO
-      END DO
-
-      !
-      ! ecriture d'un fichier netcdf
-      !
-      niter = niter + 1
-!clem
-!      DO jf = 1 , noumef
-!         !
-!         zfield(:,:) = zcmo(:,:,jf) * cmulti(jf) + cadd(jf)
-!         !
-!         IF( jf == 7  .OR. jf == 8  .OR. jf == 15 .OR. jf == 16 ) THEN   ;   CALL lbc_lnk( zfield, 'T', -1. )
-!         ELSE                                                            ;   CALL lbc_lnk( zfield, 'T',  1. )
-!         ENDIF
-!         !
-!         IF( ln_nicep ) THEN 
-!            WRITE(numout,*)
-!            WRITE(numout,*) 'nc(jf), nice, nam(jf), niter, ndim'
-!            WRITE(numout,*) nc(jf), nice, nam(jf), niter, ndim
-!         ENDIF
-!         IF( nc(jf) == 1 ) CALL histwrite( nice, nam(jf), niter, zfield, ndim, ndex51 )
-!         !
-!      END DO
-!
-!      IF( ( nn_fsbc * niter ) >= nitend .OR. kindic < 0 ) THEN
-!         IF( lwp) WRITE(numout,*) ' Closing the icemod file '
-!         CALL histclo( nice )
-!      ENDIF
-!clem
-      !
-       CALL iom_put ('iceconc', zcmo(:,:,1) )          ! field1: ice concentration
-       CALL iom_put ('icethic_cea', zcmo(:,:,2) )      ! field2: ice thickness (i.e. icethi(:,:))
-       CALL iom_put ('snowthic_cea', zcmo(:,:,3))      ! field3: snow thickness
-       CALL iom_put ('icebopr', zcmo(:,:,4) )   ! field4: daily bottom thermo ice production
-       CALL iom_put ('icedypr', zcmo(:,:,5) )   ! field5: daily dynamic ice production
-       CALL iom_put ('ioceflxb', zcmo(:,:,6) )         ! field6: Oceanic flux at the ice base
-       CALL iom_put ('uice_ipa', zcmo(:,:,7) )         ! field7: ice velocity u component
-       CALL iom_put ('vice_ipa', zcmo(:,:,8) )         ! field8: ice velocity v component
-       CALL iom_put ('isst', zcmo(:,:,9) )             ! field 9: sea surface temperature
-       CALL iom_put ('isss', zcmo(:,:,10) )            ! field 10: sea surface salinity
-       CALL iom_put ('qt_oce', zcmo(:,:,11) )           ! field 11: total flux at ocean surface
-       CALL iom_put ('qsr_oce', zcmo(:,:,12) )          ! field 12: solar flux at ocean surface
-       CALL iom_put ('qns_oce', zcmo(:,:,13) )          ! field 13: non-solar flux at ocean surface
-       !CALL iom_put ('hfbri', fhbri )                  ! field 14: heat flux due to brine release
-       CALL iom_put( 'utau_ice', zcmo(:,:,15)  )     ! Wind stress over ice along i-axis at I-point
-       CALL iom_put( 'vtau_ice', zcmo(:,:,16) )     ! Wind stress over ice along j-axis at I-point
-       CALL iom_put ('qsr_io', zcmo(:,:,17) )          ! field 17: solar flux at ice/ocean surface
-       CALL iom_put ('qns_io', zcmo(:,:,18) )          ! field 18: non-solar flux at ice/ocean surface
-       !CALL iom_put ('snowpre', zcmo(:,:,19) * rday ! field 19 :snow precip          
-       CALL iom_put ('micesalt', zcmo(:,:,20) )        ! field 20 :mean ice salinity
-       CALL iom_put ('miceage', zcmo(:,:,21) / 365)    ! field 21: mean ice age
-       CALL iom_put ('icelapr',zcmo(:,:,22) )   ! field 22: daily lateral thermo ice prod.
-       CALL iom_put ('icesipr',zcmo(:,:,23) )   ! field 23: daily snowice ice prod.
-       CALL iom_put ('micet', zcmo(:,:,24) )           ! field 24: mean ice temperature
-       CALL iom_put ('icehc', zcmo(:,:,25) )           ! field 25: ice total heat content
-       CALL iom_put ('isnowhc', zcmo(:,:,26) )         ! field 26: snow total heat content
-       CALL iom_put ('icest', zcmo(:,:,27) )           ! field 27: ice surface temperature
-       CALL iom_put ('sfxbri', zcmo(:,:,28) * rday )           ! field 28: brine salt flux
-       CALL iom_put ('sfxthd', zcmo(:,:,29) * rday )           ! field 29: equivalent FW salt flux
-       CALL iom_put ('ibrinv', zcmo(:,:,30) *100 )     ! field 30: brine volume
-       CALL iom_put ('icecolf', zcmo(:,:,31) )         ! field 31: frazil ice collection thickness
-       CALL iom_put ('icestr', zcmo(:,:,32) * 0.001 )  ! field 32: ice strength
-       CALL iom_put ('icevel', zcmo(:,:,33) )          ! field 33: ice velocity
-       CALL iom_put ('isume', zcmo(:,:,34) )    ! field 34: surface melt
-       CALL iom_put ('ibome', zcmo(:,:,35) )     ! field 35: bottom melt
-       CALL iom_put ('idive', zcmo(:,:,36) * 1.0e8)    ! field 36: divergence
-       CALL iom_put ('ishear', zcmo(:,:,37) * 1.0e8 )  ! field 37: shear
-       CALL iom_put ('icerepr', zcmo(:,:,38) ) ! field 38: daily prod./melting due to limupdate
-       CALL iom_put ('icevolu', zcmo(:,:,39) ) ! field 39: ice volume
-       CALL iom_put ('snowvol', zcmo(:,:,40) ) ! field 40: snow volume
-       CALL iom_put ('sfxmec', zcmo(:,:,41) * rday )           ! field 41: salt flux from ridging rafting
-       CALL iom_put ('sfxres', zcmo(:,:,42) * rday )           ! field 42: salt flux from limupdate (resultant)
-       CALL iom_put ('icetrp', zcmo(:,:,43) )    ! field 43: ice volume transport
-
-      !-----------------------------
-      ! Thickness distribution file
-      !-----------------------------
-      IF( add_diag_swi == 1 ) THEN
-
-         DO jl = 1, jpl 
-            CALL lbc_lnk( a_i(:,:,jl)  , 'T' ,  1. )
-            CALL lbc_lnk( sm_i(:,:,jl) , 'T' ,  1. )
-            CALL lbc_lnk( oa_i(:,:,jl) , 'T' ,  1. )
-            CALL lbc_lnk( ht_i(:,:,jl) , 'T' ,  1. )
-            CALL lbc_lnk( ht_s(:,:,jl) , 'T' ,  1. )
-         END DO
-
-         ! Compute ice age
+               z2d(ji,jj) = ( tm_i(ji,jj) - rtt ) * zswi(ji,jj)
+            END DO
+         END DO
+         CALL iom_put( "micet"       , z2d                  )        ! mean ice temperature
+      ENDIF
+      !
+      IF ( iom_use( "icest" ) ) THEN 
+         z2d(:,:) = 0.e0
+         DO jl = 1, jpl
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = z2d(ji,jj) + zswi(ji,jj) * ( t_su(ji,jj,jl) - rtt ) * a_i(ji,jj,jl) / MAX( at_i(ji,jj) , epsi06 )
+               END DO
+            END DO
+         END DO
+         CALL iom_put( "icest"       , z2d                 )        ! ice surface temperature
+      ENDIF
+
+      IF ( iom_use( "icecolf" ) ) THEN 
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               rswitch  = MAX( 0._wp , SIGN( 1._wp , at_i(ji,jj) ) )
+               z2d(ji,jj) = hicol(ji,jj) * rswitch
+            END DO
+         END DO
+         CALL iom_put( "icecolf"     , z2d                 )        ! frazil ice collection thickness
+      ENDIF
+
+      CALL iom_put( "isst"        , sst_m               )        ! sea surface temperature
+      CALL iom_put( "isss"        , sss_m               )        ! sea surface salinity
+      CALL iom_put( "iceconc"     , at_i                )        ! ice concentration
+      CALL iom_put( "icevolu"     , vt_i                )        ! ice volume = mean ice thickness over the cell
+      CALL iom_put( "icehc"       , et_i                )        ! ice total heat content
+      CALL iom_put( "isnowhc"     , et_s                )        ! snow total heat content
+      CALL iom_put( "ibrinv"      , bv_i * 100._wp      )        ! brine volume
+      CALL iom_put( "utau_ice"    , utau_ice            )        ! wind stress over ice along i-axis at I-point
+      CALL iom_put( "vtau_ice"    , vtau_ice            )        ! wind stress over ice along j-axis at I-point
+      CALL iom_put( "snowpre"     , sprecip             )        ! snow precipitation 
+      CALL iom_put( "micesalt"    , smt_i               )        ! mean ice salinity
+
+      CALL iom_put( "icestr"      , strength * 0.001    )        ! ice strength
+      CALL iom_put( "idive"       , divu_i * 1.0e8      )        ! divergence
+      CALL iom_put( "ishear"      , shear_i * 1.0e8     )        ! shear
+      CALL iom_put( "snowvol"     , vt_s                )        ! snow volume
+      
+      CALL iom_put( "icetrp"      , diag_trp_vi * rday  )        ! ice volume transport
+      CALL iom_put( "snwtrp"      , diag_trp_vs * rday  )        ! snw volume transport
+      CALL iom_put( "deitrp"      , diag_trp_ei         )        ! advected ice enthalpy (W/m2)
+      CALL iom_put( "destrp"      , diag_trp_es         )        ! advected snw enthalpy (W/m2)
+
+      CALL iom_put( "sfxbog"      , sfx_bog * rday      )        ! salt flux from brines
+      CALL iom_put( "sfxbom"      , sfx_bom * rday      )        ! salt flux from brines
+      CALL iom_put( "sfxsum"      , sfx_sum * rday      )        ! salt flux from brines
+      CALL iom_put( "sfxsni"      , sfx_sni * rday      )        ! salt flux from brines
+      CALL iom_put( "sfxopw"      , sfx_opw * rday      )        ! salt flux from brines
+      CALL iom_put( "sfxdyn"      , sfx_dyn * rday      )        ! salt flux from ridging rafting
+      CALL iom_put( "sfxres"      , sfx_res * rday      )        ! salt flux from limupdate (resultant)
+      CALL iom_put( "sfxbri"      , sfx_bri * rday      )        ! salt flux from brines
+      CALL iom_put( "sfx"         , sfx     * rday      )        ! total salt flux
+
+      ztmp = rday / rhoic
+      CALL iom_put( "vfxres"     , wfx_res * ztmp  )             ! daily prod./melting due to limupdate 
+      CALL iom_put( "vfxopw"     , wfx_opw * ztmp  )             ! daily lateral thermodynamic ice production
+      CALL iom_put( "vfxsni"     , wfx_sni * ztmp  )             ! daily snowice ice production
+      CALL iom_put( "vfxbog"     , wfx_bog * ztmp  )             ! daily bottom thermodynamic ice production
+      CALL iom_put( "vfxdyn"     , wfx_dyn * ztmp  )             ! daily dynamic ice production (rid/raft)
+      CALL iom_put( "vfxsum"     , wfx_sum * ztmp  )             ! surface melt 
+      CALL iom_put( "vfxbom"     , wfx_bom * ztmp  )             ! bottom melt 
+      CALL iom_put( "vfxice"     , wfx_ice * ztmp  )             ! total ice growth/melt 
+      CALL iom_put( "vfxsnw"     , wfx_snw * ztmp  )             ! total snw growth/melt 
+      CALL iom_put( "vfxsub"     , wfx_sub * ztmp  )             ! sublimation (snow) 
+      CALL iom_put( "vfxspr"     , wfx_spr * ztmp  )             ! precip (snow) 
+
+      CALL iom_put ('hfxthd', hfx_thd(:,:) )   !  
+      CALL iom_put ('hfxdyn', hfx_dyn(:,:) )   !  
+      CALL iom_put ('hfxres', hfx_res(:,:) )   !  
+      CALL iom_put ('hfxout', hfx_out(:,:) )   !  
+      CALL iom_put ('hfxin' , hfx_in(:,:) )   !  
+      CALL iom_put ('hfxsnw', hfx_snw(:,:) )   !  
+      CALL iom_put ('hfxsub', hfx_sub(:,:) )   !  
+      CALL iom_put ('hfxerr', hfx_err(:,:) )   !  
+      CALL iom_put ('hfxerr_rem', hfx_err_rem(:,:) )   !  
+      
+      CALL iom_put ('hfxsum', hfx_sum(:,:) )   !  
+      CALL iom_put ('hfxbom', hfx_bom(:,:) )   !  
+      CALL iom_put ('hfxbog', hfx_bog(:,:) )   !  
+      CALL iom_put ('hfxdif', hfx_dif(:,:) )   !  
+      CALL iom_put ('hfxopw', hfx_opw(:,:) )   !  
+      CALL iom_put ('hfxtur', fhtur(:,:) * at_i(:,:) )   ! turbulent heat flux at ice base 
+      CALL iom_put ('hfxdhc', diag_heat_dhc(:,:) )          ! Heat content variation in snow and ice 
+      CALL iom_put ('hfxspr', hfx_spr(:,:) )          ! Heat content of snow precip 
+      
+      !--------------------------------
+      ! Output values for each category
+      !--------------------------------
+      CALL iom_put( "iceconc_cat"      , a_i         )        ! area for categories
+      CALL iom_put( "icethic_cat"      , ht_i        )        ! thickness for categories
+      CALL iom_put( "snowthic_cat"     , ht_s        )        ! snow depth for categories
+      CALL iom_put( "salinity_cat"     , sm_i        )        ! salinity for categories
+
+      ! Compute ice age
+      IF ( iom_use( "iceage_cat" ) ) THEN 
          DO jl = 1, jpl 
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zinda = MAX( zzero , SIGN( zone , a_i(ji,jj,jl) - epsi06 ) )
-                  zoi(ji,jj,jl) = oa_i(ji,jj,jl)  / MAX( a_i(ji,jj,jl) , epsi06 ) * zinda
+                  rswitch = MAX( 0._wp , SIGN( 1._wp , a_i(ji,jj,jl) - epsi06 ) )
+                  zoi(ji,jj,jl) = oa_i(ji,jj,jl)  / MAX( a_i(ji,jj,jl) , epsi06 ) * rswitch
                END DO
             END DO
          END DO
-
-         ! Compute brine volume
+         CALL iom_put( "iceage_cat"     , zoi         )        ! ice age for categories
+      ENDIF
+
+      ! Compute brine volume
+      IF ( iom_use( "brinevol_cat" ) ) THEN 
          zei(:,:,:) = 0._wp
          DO jl = 1, jpl 
@@ -379,38 +259,21 @@
                DO jj = 1, jpj
                   DO ji = 1, jpi
-                     zinda = MAX( zzero , SIGN( zone , a_i(ji,jj,jl) - epsi06 ) )
+                     rswitch = MAX( 0._wp , SIGN( 1._wp , a_i(ji,jj,jl) - epsi06 ) )
                      zei(ji,jj,jl) = zei(ji,jj,jl) + 100.0* &
                         ( - tmut * s_i(ji,jj,jk,jl) / MIN( ( t_i(ji,jj,jk,jl) - rtt ), - epsi06 ) ) * &
-                        zinda / nlay_i
+                        rswitch / nlay_i
                   END DO
                END DO
             END DO
          END DO
-
-         DO jl = 1, jpl 
-            CALL lbc_lnk( zei(:,:,jl) , 'T' ,  1. )
-         END DO
-
-         CALL histwrite( nicea, "iice_itd", niter, a_i  , ndimitd , ndexitd  )   ! area
-         CALL histwrite( nicea, "iice_hid", niter, ht_i , ndimitd , ndexitd  )   ! thickness
-         CALL histwrite( nicea, "iice_hsd", niter, ht_s , ndimitd , ndexitd  )   ! snow depth
-         CALL histwrite( nicea, "iice_std", niter, sm_i , ndimitd , ndexitd  )   ! salinity
-         CALL histwrite( nicea, "iice_otd", niter, zoi  , ndimitd , ndexitd  )   ! age
-         CALL histwrite( nicea, "iice_etd", niter, zei  , ndimitd , ndexitd  )   ! brine volume
-
-         !     !  Create an output files (output.lim.abort.nc) if S < 0 or u > 20 m/s
-         !     IF( kindic < 0 )   CALL lim_wri_state( 'output.abort' )
-         !     not yet implemented
-
-         IF( ( nn_fsbc * niter ) >= nitend .OR. kindic < 0 ) THEN
-            IF(lwp) WRITE(numout,*) ' Closing the icemod file '
-            CALL histclo( nicea ) 
-         ENDIF
-         !
-      ENDIF
-
-      CALL wrk_dealloc( jpi, jpj, zfield )
-      CALL wrk_dealloc( jpi, jpj, jpnoumax, zcmo, zcmoa )
-      CALL wrk_dealloc( jpi, jpj, jpl, zmaskitd, zoi, zei )
+         CALL iom_put( "brinevol_cat"     , zei         )        ! brine volume for categories
+      ENDIF
+
+      !     !  Create an output files (output.lim.abort.nc) if S < 0 or u > 20 m/s
+      !     IF( kindic < 0 )   CALL lim_wri_state( 'output.abort' )
+      !     not yet implemented
+      
+      CALL wrk_dealloc( jpi, jpj, jpl, zoi, zei )
+      CALL wrk_dealloc( jpi, jpj     , z2d, zswi, z2da, z2db )
 
       IF( nn_timing == 1 )  CALL timing_stop('limwri')
@@ -419,124 +282,4 @@
 #endif
 
-   SUBROUTINE lim_wri_init
-      !!-------------------------------------------------------------------
-      !!                    ***   ROUTINE lim_wri_init  ***
-      !!                
-      !! ** Purpose :   ???
-      !!
-      !! ** Method  : Read the namicewri namelist and check the parameter 
-      !!       values called at the first timestep (nit000)
-      !!
-      !! ** input   :   Namelist namicewri
-      !!-------------------------------------------------------------------
-      INTEGER ::   nf      ! ???
-      INTEGER ::   ios     ! Local integer output status for namelist read
-
-      TYPE FIELD 
-         CHARACTER(len = 35) :: ztitle 
-         CHARACTER(len = 8 ) :: zname          
-         CHARACTER(len = 8 ) :: zunit
-         INTEGER             :: znc   
-         REAL                :: zcmulti 
-         REAL                :: zcadd        
-      END TYPE FIELD
-
-      TYPE(FIELD) ::  &
-         field_1 , field_2 , field_3 , field_4 , field_5 , field_6 ,   &
-         field_7 , field_8 , field_9 , field_10, field_11, field_12,   &
-         field_13, field_14, field_15, field_16, field_17, field_18,   &
-         field_19, field_20, field_21, field_22, field_23, field_24,   &
-         field_25, field_26, field_27, field_28, field_29, field_30,   &
-         field_31, field_32, field_33, field_34, field_35, field_36,   &
-         field_37, field_38, field_39, field_40, field_41, field_42, field_43
-
-      TYPE(FIELD) , DIMENSION(jpnoumax) :: zfield
-      !
-      NAMELIST/namiceout/ noumef, &
-         field_1 , field_2 , field_3 , field_4 , field_5 , field_6 ,   &
-         field_7 , field_8 , field_9 , field_10, field_11, field_12,   &
-         field_13, field_14, field_15, field_16, field_17, field_18,   &
-         field_19, field_20, field_21, field_22, field_23, field_24,   &
-         field_25, field_26, field_27, field_28, field_29, field_30,   &
-         field_31, field_32, field_33, field_34, field_35, field_36,   &
-         field_37, field_38, field_39, field_40, field_41, field_42, field_43, add_diag_swi
-      !!-------------------------------------------------------------------
-      REWIND( numnam_ice_ref )              ! Namelist namiceout in reference namelist : Ice outputs
-      READ  ( numnam_ice_ref, namiceout, IOSTAT = ios, ERR = 901)
-901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namiceout in reference namelist', lwp )
-
-      REWIND( numnam_ice_cfg )              ! Namelist namiceout in configuration namelist : Ice outputs
-      READ  ( numnam_ice_cfg, namiceout, IOSTAT = ios, ERR = 902 )
-902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namiceout in configuration namelist', lwp )
-      IF(lwm) WRITE ( numoni, namiceout )
-
-      zfield(1)  = field_1
-      zfield(2)  = field_2
-      zfield(3)  = field_3
-      zfield(4)  = field_4
-      zfield(5)  = field_5
-      zfield(6)  = field_6
-      zfield(7)  = field_7
-      zfield(8)  = field_8
-      zfield(9)  = field_9
-      zfield(10) = field_10
-      zfield(11) = field_11
-      zfield(12) = field_12
-      zfield(13) = field_13
-      zfield(14) = field_14
-      zfield(15) = field_15
-      zfield(16) = field_16
-      zfield(17) = field_17
-      zfield(18) = field_18
-      zfield(19) = field_19
-      zfield(20) = field_20
-      zfield(21) = field_21
-      zfield(22) = field_22
-      zfield(23) = field_23
-      zfield(24) = field_24
-      zfield(25) = field_25
-      zfield(26) = field_26
-      zfield(27) = field_27
-      zfield(28) = field_28
-      zfield(29) = field_29
-      zfield(30) = field_30
-      zfield(31) = field_31
-      zfield(32) = field_32
-      zfield(33) = field_33
-      zfield(34) = field_34
-      zfield(35) = field_35
-      zfield(36) = field_36
-      zfield(37) = field_37
-      zfield(38) = field_38
-      zfield(39) = field_39
-      zfield(40) = field_40
-      zfield(41) = field_41
-      zfield(42) = field_42
-      zfield(43) = field_43
-
-      DO nf = 1, noumef
-         titn  (nf) = zfield(nf)%ztitle
-         nam   (nf) = zfield(nf)%zname
-         uni   (nf) = zfield(nf)%zunit
-         nc    (nf) = zfield(nf)%znc
-         cmulti(nf) = zfield(nf)%zcmulti
-         cadd  (nf) = zfield(nf)%zcadd
-      END DO
-
-      IF(lwp) THEN                        ! control print
-         WRITE(numout,*)
-         WRITE(numout,*) 'lim_wri_init : Ice parameters for outputs'
-         WRITE(numout,*) '~~~~~~~~~~~~'
-         WRITE(numout,*) '    number of fields to be stored         noumef = ', noumef
-         WRITE(numout,*) '           title                            name     unit      Saving (1/0) ',   &
-            &            '    multiplicative constant       additive constant '
-         DO nf = 1 , noumef         
-            WRITE(numout,*) '   ', titn(nf), '   '    , nam   (nf), '      '  , uni (nf),   &
-               &            '  ' , nc  (nf),'        ', cmulti(nf), '        ', cadd(nf)
-         END DO
-         WRITE(numout,*) ' add_diag_swi ', add_diag_swi
-      ENDIF
-      !
-   END SUBROUTINE lim_wri_init
  
    SUBROUTINE lim_wri_state( kt, kid, kh_i )
@@ -555,35 +298,49 @@
       INTEGER, INTENT( in ) ::   kid , kh_i       
       !!----------------------------------------------------------------------
-      !CALL histvert( kid, "icethi", "L levels","m", jpl , hi_mean , nz )
-
-      CALL histdef( kid, "iicethic", "Ice thickness"           , "m"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iiceconc", "Ice concentration"       , "%"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicetemp", "Ice temperature"         , "C"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicevelu", "i-Ice speed (I-point)"   , "m/s"    , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicevelv", "j-Ice speed (I-point)"   , "m/s"    , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
-      CALL histdef( kid, "iicestru", "i-Wind stress over ice (I-pt)", "Pa", jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicestrv", "j-Wind stress over ice (I-pt)", "Pa", jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
-      CALL histdef( kid, "iicesflx", "Solar flux over ocean"     , "w/m2"   , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
-      CALL histdef( kid, "iicenflx", "Non-solar flux over ocean" , "w/m2"   , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "isnowpre", "Snow precipitation"      , "kg/m2/s", jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
-      CALL histdef( kid, "iicesali", "Ice salinity"            , "PSU"    , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
-      CALL histdef( kid, "iicevolu", "Ice volume"              , "m"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
-      CALL histdef( kid, "iicedive", "Ice divergence"          , "10-8s-1", jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
-      CALL histdef( kid, "iicebopr", "Ice bottom production"   , "m/s"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicedypr", "Ice dynamic production"  , "m/s"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicelapr", "Ice open water prod"     , "m/s"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicesipr", "Snow ice production "    , "m/s"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicerepr", "Ice prod from limupdate" , "m/s"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicebome", "Ice bottom melt"         , "m/s"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iicesume", "Ice surface melt"        , "m/s"      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iisfxthd", "Salt flux from thermo"   , ""      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iisfxmec", "Salt flux from dynmics"  , ""      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-      CALL histdef( kid, "iisfxres", "Salt flux from limupdate", ""      , jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
-
-
-      !CALL histdef( kid, "iice_itd", "Ice concentration by cat", "%"      , jpi, jpj, kh_i, jpl, 1, jpl, -99, 32, "inst(x)", rdt, rdt ) 
-      !CALL histdef( kid, "iice_hid", "Ice thickness by cat"    , "m"      , jpi, jpj, kh_i, jpl, 1, jpl, -99, 32, "inst(x)", rdt, rdt ) 
-      !CALL histdef( kid, "iice_hsd", "Snow thickness by cat"   , "m"      , jpi, jpj, kh_i, jpl, 1, jpl, -99, 32, "inst(x)", rdt, rdt ) 
-      !CALL histdef( kid, "iice_std", "Ice salinity by cat"     , "PSU"    , jpi, jpj, kh_i, jpl, 1, jpl, -99, 32, "inst(x)", rdt, rdt ) 
+
+      CALL histdef( kid, "iicethic", "Ice thickness"           , "m"      ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iiceconc", "Ice concentration"       , "%"      ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicetemp", "Ice temperature"         , "C"      ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicevelu", "i-Ice speed (I-point)"   , "m/s"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicevelv", "j-Ice speed (I-point)"   , "m/s"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
+      CALL histdef( kid, "iicestru", "i-Wind stress over ice (I-pt)", "Pa",   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicestrv", "j-Wind stress over ice (I-pt)", "Pa",   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
+      CALL histdef( kid, "iicesflx", "Solar flux over ocean"     , "w/m2" ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
+      CALL histdef( kid, "iicenflx", "Non-solar flux over ocean" , "w/m2" ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "isnowpre", "Snow precipitation"      , "kg/m2/s",   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
+      CALL histdef( kid, "iicesali", "Ice salinity"            , "PSU"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
+      CALL histdef( kid, "iicevolu", "Ice volume"              , "m"      ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
+      CALL histdef( kid, "iicedive", "Ice divergence"          , "10-8s-1",   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt ) 
+      CALL histdef( kid, "iicebopr", "Ice bottom production"   , "m/s"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicedypr", "Ice dynamic production"  , "m/s"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicelapr", "Ice open water prod"     , "m/s"    ,   &
+      &       jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicesipr", "Snow ice production "    , "m/s"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicerepr", "Ice prod from limupdate" , "m/s"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicebome", "Ice bottom melt"         , "m/s"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iicesume", "Ice surface melt"        , "m/s"    ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iisfxdyn", "Salt flux from dynmics"  , ""       ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
+      CALL histdef( kid, "iisfxres", "Salt flux from limupdate", ""       ,   &
+      &      jpi, jpj, kh_i, 1, 1, 1, -99, 32, "inst(x)", rdt, rdt )
 
       CALL histend( kid, snc4set )   ! end of the file definition
@@ -603,19 +360,17 @@
       CALL histwrite( kid, "iicedive", kt, divu_i*1.0e8   , jpi*jpj, (/1/) )
 
-      CALL histwrite( kid, "iicebopr", kt, diag_bot_gr        , jpi*jpj, (/1/) )
-      CALL histwrite( kid, "iicedypr", kt, diag_dyn_gr        , jpi*jpj, (/1/) )
-      CALL histwrite( kid, "iicelapr", kt, diag_lat_gr        , jpi*jpj, (/1/) )
-      CALL histwrite( kid, "iicesipr", kt, diag_sni_gr        , jpi*jpj, (/1/) )
-      CALL histwrite( kid, "iicerepr", kt, diag_res_pr        , jpi*jpj, (/1/) )
-      CALL histwrite( kid, "iicebome", kt, diag_bot_me        , jpi*jpj, (/1/) )
-      CALL histwrite( kid, "iicesume", kt, diag_sur_me        , jpi*jpj, (/1/) )
-      CALL histwrite( kid, "iisfxthd", kt, sfx_thd        , jpi*jpj, (/1/) )
-      CALL histwrite( kid, "iisfxmec", kt, sfx_mec        , jpi*jpj, (/1/) )
+      CALL histwrite( kid, "iicebopr", kt, wfx_bog        , jpi*jpj, (/1/) )
+      CALL histwrite( kid, "iicedypr", kt, wfx_dyn        , jpi*jpj, (/1/) )
+      CALL histwrite( kid, "iicelapr", kt, wfx_opw        , jpi*jpj, (/1/) )
+      CALL histwrite( kid, "iicesipr", kt, wfx_sni        , jpi*jpj, (/1/) )
+      CALL histwrite( kid, "iicerepr", kt, wfx_res        , jpi*jpj, (/1/) )
+      CALL histwrite( kid, "iicebome", kt, wfx_bom        , jpi*jpj, (/1/) )
+      CALL histwrite( kid, "iicesume", kt, wfx_sum        , jpi*jpj, (/1/) )
+      CALL histwrite( kid, "iisfxdyn", kt, sfx_dyn        , jpi*jpj, (/1/) )
       CALL histwrite( kid, "iisfxres", kt, sfx_res        , jpi*jpj, (/1/) )
 
-      !CALL histwrite( kid, "iice_itd", kt, a_i  , jpi*jpj*jpl, (/1/)  )   ! area
-      !CALL histwrite( kid, "iice_hid", kt, ht_i , jpi*jpj*jpl, (/1/)  )   ! thickness
-      !CALL histwrite( kid, "iice_hsd", kt, ht_s , jpi*jpj*jpl, (/1/)  )   ! snow depth
-      !CALL histwrite( kid, "iice_std", kt, sm_i , jpi*jpj*jpl, (/1/)  )   ! salinity
+      ! Close the file
+      ! -----------------
+      !CALL histclo( kid )
 
     END SUBROUTINE lim_wri_state
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limwri_dimg.h90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limwri_dimg.h90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/limwri_dimg.h90	(revision 5075)
@@ -89,14 +89,14 @@
    DO jj = 2 , jpjm1
       DO ji = 2 , jpim1   ! NO vector opt.
-         zindh  = MAX( zzero , SIGN( zone , ht_i(ji,jj,1) * (1.0 - frld(ji,jj) ) - 0.10 ) )
-         zinda  = MAX( zzero , SIGN( zone , ( 1.0 - frld(ji,jj) ) - 0.10 ) )
+         zindh  = MAX( 0._wp , SIGN( 1._wp , ht_i(ji,jj,1) * (1.0 - frld(ji,jj) ) - 0.10 ) )
+         zinda  = MAX( 0._wp , SIGN( 1._wp , ( 1.0 - frld(ji,jj) ) - 0.10 ) )
          zindb  = zindh * zinda
-         ztmu   = MAX( 0.5 * zone , ( tmu(ji,jj) + tmu(ji+1,jj) + tmu(ji,jj+1) + tmu(ji+1,jj+1) ) ) 
+         ztmu   = MAX( 0.5 * 1._wp , ( tmu(ji,jj) + tmu(ji+1,jj) + tmu(ji,jj+1) + tmu(ji+1,jj+1) ) ) 
          zcmo(ji,jj,1)  = ht_s (ji,jj,1)
          zcmo(ji,jj,2)  = ht_i (ji,jj,1)
-         zcmo(ji,jj,3)  = hicifp(ji,jj)
+         zcmo(ji,jj,3)  = 0.
          zcmo(ji,jj,4)  = frld  (ji,jj)
          zcmo(ji,jj,5)  = sist  (ji,jj)
-         zcmo(ji,jj,6)  = fbif  (ji,jj)
+         zcmo(ji,jj,6)  = fhtur  (ji,jj)
          zcmo(ji,jj,7)  = zindb * (  u_ice(ji,jj  ) * tmu(ji,jj  ) + u_ice(ji+1,jj  ) * tmu(ji+1,jj  )   &
             + u_ice(ji,jj+1) * tmu(ji,jj+1) + u_ice(ji+1,jj+1) * tmu(ji+1,jj+1) ) &
@@ -132,14 +132,14 @@
          DO jj = 2 , jpjm1
             DO ji = 2 , jpim1   ! NO vector opt.
-               zindh  = MAX( zzero , SIGN( zone , ht_i(ji,jj,1) * (1.0 - frld(ji,jj) ) - 0.10 ) )
-               zinda  = MAX( zzero , SIGN( zone , ( 1.0 - frld(ji,jj) ) - 0.10 ) )
+               zindh  = MAX( 0._wp , SIGN( 1._wp , ht_i(ji,jj,1) * (1.0 - frld(ji,jj) ) - 0.10 ) )
+               zinda  = MAX( 0._wp , SIGN( 1._wp , ( 1.0 - frld(ji,jj) ) - 0.10 ) )
                zindb  = zindh * zinda
-               ztmu   = MAX( 0.5 * zone , ( tmu(ji,jj) + tmu(ji+1,jj) + tmu(ji,jj+1) + tmu(ji+1,jj+1) ) )
+               ztmu   = MAX( 0.5 * 1._wp , ( tmu(ji,jj) + tmu(ji+1,jj) + tmu(ji,jj+1) + tmu(ji+1,jj+1) ) )
                rcmoy(ji,jj,1)  = ht_s (ji,jj,1)
                rcmoy(ji,jj,2)  = ht_i (ji,jj,1)
-               rcmoy(ji,jj,3)  = hicifp(ji,jj)
+               rcmoy(ji,jj,3)  = 0.
                rcmoy(ji,jj,4)  = frld  (ji,jj)
                rcmoy(ji,jj,5)  = sist  (ji,jj)
-               rcmoy(ji,jj,6)  = fbif  (ji,jj)
+               rcmoy(ji,jj,6)  = fhtur  (ji,jj)
                rcmoy(ji,jj,7)  = zindb * (  u_ice(ji,jj  ) * tmu(ji,jj  ) + u_ice(ji+1,jj  ) * tmu(ji+1,jj  )   &
                   + u_ice(ji,jj+1) * tmu(ji,jj+1) + u_ice(ji+1,jj+1) * tmu(ji+1,jj+1) ) &
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/par_ice.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/par_ice.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/par_ice.F90	(revision 5075)
@@ -12,10 +12,9 @@
 
    !                                             !!! ice thermodynamics
-   INTEGER, PUBLIC, PARAMETER ::   jkmax    = 6   !: maximum number of ice layers
+   INTEGER, PUBLIC, PARAMETER ::   nlay_i   = 5   !: number of ice layers
    INTEGER, PUBLIC, PARAMETER ::   nlay_s   = 1   !: number of snow layers
 
    !                                             !!! ice mechanical redistribution
    INTEGER, PUBLIC, PARAMETER ::   jpl      = 5   !: number of ice categories
-   INTEGER, PUBLIC, PARAMETER ::   jpm      = 1   !: number of ice types
 
    !!----------------------------------------------------------------------
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/thd_ice.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/thd_ice.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/LIM_SRC_3/thd_ice.F90	(revision 5075)
@@ -20,22 +20,13 @@
    !                               !!! ** ice-thermo namelist (namicethd) **
    REAL(wp), PUBLIC ::   hmelt       !: maximum melting at the bottom; active only for one category
-   REAL(wp), PUBLIC ::   hicmin      !: (REMOVE)
    REAL(wp), PUBLIC ::   hiclim      !: minimum ice thickness
-   REAL(wp), PUBLIC ::   sbeta       !: numerical scheme for diffusion in ice  (REMOVE)
-   REAL(wp), PUBLIC ::   parlat      !: (REMOVE)
-   REAL(wp), PUBLIC ::   hakspl      !: (REMOVE)
-   REAL(wp), PUBLIC ::   hibspl      !: (REMOVE)
-   REAL(wp), PUBLIC ::   exld        !: (REMOVE)
-   REAL(wp), PUBLIC ::   hakdif      !: (REMOVE)
-   REAL(wp), PUBLIC ::   thth        !: (REMOVE)
    REAL(wp), PUBLIC ::   hnzst       !: thick. of the surf. layer in temp. comp.
    REAL(wp), PUBLIC ::   parsub      !: switch for snow sublimation or not
-   REAL(wp), PUBLIC ::   alphs       !: coef. for snow density when snow-ice formation
-   REAL(wp), PUBLIC ::   fraz_swi    !: use of frazil ice collection in function of wind (1.0) or not (0.0)
    REAL(wp), PUBLIC ::   maxfrazb    !: maximum portion of frazil ice collecting at the ice bottom
    REAL(wp), PUBLIC ::   vfrazb      !: threshold drift speed for collection of bottom frazil ice
    REAL(wp), PUBLIC ::   Cfrazb      !: squeezing coefficient for collection of bottom frazil ice
+   REAL(wp), PUBLIC ::   hiccrit     !: ice th. for lateral accretion in the NH (SH) (m)
 
-   REAL(wp), PUBLIC, DIMENSION(2) ::   hiccrit   !: ice th. for lateral accretion in the NH (SH) (m)
+   INTEGER , PUBLIC ::   fraz_swi    !: use of frazil ice collection in function of wind (1) or not (0)
 
    !!-----------------------------
@@ -43,5 +34,5 @@
    !!-----------------------------
    !: In ice thermodynamics, to spare memory, the vectors are folded
-   !: from 1D to 2D vectors. The following variables, with ending _1d (or _b)
+   !: from 1D to 2D vectors. The following variables, with ending _1d
    !: are the variables corresponding to 2d vectors
 
@@ -49,28 +40,53 @@
    INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   npac   !: correspondance between points (lateral accretion)
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qldif_1d      !: <==> the 2D  qldif
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qcmif_1d      !: <==> the 2D  qcmif
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fstbif_1d     !: <==> the 2D  fstric
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fltbif_1d     !: <==> the 2D  ffltbif
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fscbq_1d      !: <==> the 2D  fscmcbq
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qsr_ice_1d    !: <==> the 2D  qsr_ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fr1_i0_1d     !: <==> the 2D  fr1_i0
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fr2_i0_1d     !: <==> the 2D  fr2_i0
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qnsr_ice_1d   !: <==> the 2D  qns_ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qfvbq_1d      !: <==> the 2D  qfvbq
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   t_bo_b        !: <==> the 2D  t_bo
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qlead_1d     
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ftr_ice_1d   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qsr_ice_1d  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fr1_i0_1d   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fr2_i0_1d   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qns_ice_1d  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   t_bo_1d     
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_sum_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_bom_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_bog_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_dif_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_opw_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_snw_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_err_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_err_rem_1d
+
+   ! heat flux associated with ice-atmosphere mass exchange
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_sub_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_spr_1d
+
+   ! heat flux associated with ice-ocean mass exchange
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_thd_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hfx_res_1d
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_snw_1d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_sub_1d
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_bog_1d    
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_bom_1d   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_sum_1d  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_sni_1d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_opw_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_res_1d 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   wfx_spr_1d
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_bri_1d
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_bog_1d    
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_bom_1d    
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_sum_1d    
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_sni_1d    
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_opw_1d   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_res_1d  
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sprecip_1d    !: <==> the 2D  sprecip
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   frld_1d       !: <==> the 2D  frld
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   at_i_b        !: <==> the 2D  frld
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fbif_1d       !: <==> the 2D  fbif
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   rdm_ice_1d    !: <==> the 2D  rdm_ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   rdm_snw_1d    !: <==> the 2D  rdm_snw
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qlbbq_1d      !: <==> the 2D  qlbsbq
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dmgwi_1d      !: <==> the 2D  dmgwi
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dvsbq_1d      !: <==> the 2D  rdvosif
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dvbbq_1d      !: <==> the 2D  rdvobif
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dvlbq_1d      !: <==> the 2D  rdvolif
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dvnbq_1d      !: <==> the 2D  rdvolif
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   at_i_1d        !: <==> the 2D  at_i
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fhtur_1d      !: <==> the 2D  fhtur
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fhld_1d       !: <==> the 2D  fhld
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dqns_ice_1d   !: <==> the 2D  dqns_ice
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   qla_ice_1d    !: <==> the 2D  qla_ice
@@ -78,63 +94,33 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   tatm_ice_1d   !: <==> the 2D  tatm_ice
    !                                                     ! to reintegrate longwave flux inside the ice thermodynamics
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fsup          !: Energy flux sent from bottom to lateral ablation if |dhb|> 0.15 m
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   focea         !: Remaining energy in case of total ablation
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   i0            !: fraction of radiation transmitted to the ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   old_ht_i_b    !: Ice thickness at the beginnning of the time step [m]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   old_ht_s_b    !: Snow thickness at the beginning of the time step [m]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_bri_1d    !: <==> the 2D sfx_bri
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fhbri_1d      !: Heat flux due to brine drainage
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sfx_thd_1d    !: <==> the 2D sfx_thd
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dsm_i_fl_1d   !: Ice salinity variations due to flushing
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dsm_i_gd_1d   !: Ice salinity variations due to gravity drainage
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dsm_i_se_1d   !: Ice salinity variations due to basal salt entrapment
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dsm_i_si_1d   !: Ice salinity variations due to lateral accretion    
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hicol_b       !: Ice collection thickness accumulated in fleads
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   hicol_1d      !: Ice collection thickness accumulated in leads
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   t_su_b      !: <==> the 2D  t_su
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   a_i_b       !: <==> the 2D  a_i
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ht_i_b      !: <==> the 2D  ht_s
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ht_s_b      !: <==> the 2D  ht_i
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fc_su       !: Surface Conduction flux 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fc_bo_i     !: Bottom  Conduction flux 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_s_tot    !: Snow accretion/ablation        [m]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_surf   !: Ice surface accretion/ablation [m]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_bott   !: Ice bottom accretion/ablation  [m]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_snowice  !: Snow ice formation             [m of ice]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sm_i_b      !: Ice bulk salinity [ppt]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   s_i_new     !: Salinity of new ice at the bottom
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   s_snowice   !: Salinity of new snow ice on top of the ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   o_i_b       !: Ice age                        [days]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   t_su_1d       !: <==> the 2D  t_su
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   a_i_1d        !: <==> the 2D  a_i
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ht_i_1d       !: <==> the 2D  ht_s
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ht_s_1d       !: <==> the 2D  ht_i
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fc_su         !: Surface Conduction flux 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   fc_bo_i       !: Bottom  Conduction flux 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_s_tot      !: Snow accretion/ablation        [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_surf     !: Ice surface accretion/ablation [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_i_bott     !: Ice bottom accretion/ablation  [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   dh_snowice    !: Snow ice formation             [m of ice]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   sm_i_1d       !: Ice bulk salinity [ppt]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   s_i_new       !: Salinity of new ice at the bottom
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   iatte_1d   !: clem attenuation coef of the input solar flux (unitless)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   oatte_1d   !: clem attenuation coef of the input solar flux (unitless)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   t_s_1d   !: corresponding to the 2D var  t_s
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   t_i_1d   !: corresponding to the 2D var  t_i
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   s_i_1d   !: profiled ice salinity
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   q_i_1d   !:    Ice  enthalpy per unit volume
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   q_s_1d   !:    Snow enthalpy per unit volume
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   t_s_b   !: corresponding to the 2D var  t_s
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   t_i_b   !: corresponding to the 2D var  t_i
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   s_i_b   !: profiled ice salinity
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   q_i_b   !:    Ice  enthalpy per unit volume
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   q_s_b   !:    Snow enthalpy per unit volume
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qh_i_old !: ice heat content (q*h, J.m-2)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   h_i_old  !: ice thickness layer (m)
 
-   ! Clean the following ...
-   ! These variables are coded for conservation checks
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qt_i_in                  !: ice energy summed over categories (initial)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qt_i_fin                 !: ice energy summed over categories (final)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   qt_s_in, qt_s_fin        !: snow energy summed over categories
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   dq_i, sum_fluxq          !: increment of energy, sum of fluxes
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fatm, foce               !: atmospheric, oceanic, heat flux
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   cons_error, surf_error   !: conservation, surface error
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   q_i_layer_in        !: goes to trash
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   q_i_layer_fin       !: goes to trash
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   dq_i_layer, radab   !: goes to trash
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ftotal_in    !: initial total heat flux
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   ftotal_fin   !: final total heat flux
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fc_s
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   fc_i
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   de_s_lay
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   de_i_lay
-   
    INTEGER , PUBLIC ::   jiindex_1d   ! 1D index of debugging point
 
@@ -151,50 +137,40 @@
       !!---------------------------------------------------------------------!
       INTEGER ::   thd_ice_alloc   ! return value
-      INTEGER ::   ierr(4)
+      INTEGER ::   ierr(3)
       !!---------------------------------------------------------------------!
 
       ALLOCATE( npb      (jpij) , npac     (jpij),                          &
          !                                                                  !
-         &      qldif_1d (jpij) , qcmif_1d (jpij) , fstbif_1d  (jpij) ,     &
-         &      fltbif_1d(jpij) , fscbq_1d (jpij) , qsr_ice_1d (jpij) ,     &
-         &      fr1_i0_1d(jpij) , fr2_i0_1d(jpij) , qnsr_ice_1d(jpij) ,     &
-         &      qfvbq_1d (jpij) , t_bo_b   (jpij) , iatte_1d   (jpij) ,     &
-         &      oatte_1d (jpij)                                       , STAT=ierr(1) )
+         &      qlead_1d (jpij) , ftr_ice_1d  (jpij) ,     &
+         &      qsr_ice_1d (jpij) ,     &
+         &      fr1_i0_1d(jpij) , fr2_i0_1d(jpij) , qns_ice_1d(jpij) ,     &
+         &      t_bo_1d   (jpij) ,                                          &
+         &      hfx_sum_1d(jpij) , hfx_bom_1d(jpij) ,hfx_bog_1d(jpij) ,     & 
+         &      hfx_dif_1d(jpij) ,hfx_opw_1d(jpij) , &
+         &      hfx_thd_1d(jpij) , hfx_spr_1d(jpij) , &
+         &      hfx_snw_1d(jpij) , hfx_sub_1d(jpij) , hfx_err_1d(jpij) , &
+         &      hfx_res_1d(jpij) , hfx_err_rem_1d(jpij),       STAT=ierr(1) )
       !
-      ALLOCATE( sprecip_1d (jpij) , frld_1d    (jpij) , at_i_b     (jpij) ,     &
-         &      fbif_1d    (jpij) , rdm_ice_1d (jpij) , rdm_snw_1d (jpij) ,     &
-         &      qlbbq_1d   (jpij) , dmgwi_1d   (jpij) , dvsbq_1d   (jpij) ,     &
-         &      dvbbq_1d   (jpij) , dvlbq_1d   (jpij) , dvnbq_1d   (jpij) ,     &
+      ALLOCATE( sprecip_1d (jpij) , frld_1d    (jpij) , at_i_1d     (jpij) ,     &
+         &      fhtur_1d   (jpij) , wfx_snw_1d (jpij) , wfx_spr_1d (jpij) ,     &
+         &      fhld_1d    (jpij) , wfx_sub_1d (jpij) , wfx_bog_1d(jpij) , wfx_bom_1d(jpij) , &
+         &      wfx_sum_1d(jpij)  , wfx_sni_1d (jpij) , wfx_opw_1d (jpij) ,  wfx_res_1d (jpij) ,  &
          &      dqns_ice_1d(jpij) , qla_ice_1d (jpij) , dqla_ice_1d(jpij) ,     &
-         &      tatm_ice_1d(jpij) , fsup       (jpij) , focea      (jpij) ,     &   
-         &      i0         (jpij) , old_ht_i_b (jpij) , old_ht_s_b (jpij) ,     &  
-         &      sfx_bri_1d (jpij) , fhbri_1d   (jpij) , sfx_thd_1d (jpij) ,     &
+         &      tatm_ice_1d(jpij) ,      &   
+         &      i0         (jpij) ,     &  
+         &      sfx_bri_1d (jpij) , sfx_bog_1d (jpij) , sfx_bom_1d (jpij) ,sfx_sum_1d (jpij) ,   &
+         &      sfx_sni_1d (jpij) , sfx_opw_1d (jpij) , sfx_res_1d (jpij) , &
          &      dsm_i_fl_1d(jpij) , dsm_i_gd_1d(jpij) , dsm_i_se_1d(jpij) ,     &     
-         &      dsm_i_si_1d(jpij) , hicol_b    (jpij)                     , STAT=ierr(2) )
+         &      dsm_i_si_1d(jpij) , hicol_1d    (jpij)                     , STAT=ierr(2) )
       !
-      ALLOCATE( t_su_b    (jpij) , a_i_b    (jpij) , ht_i_b   (jpij) ,    &   
-         &      ht_s_b    (jpij) , fc_su    (jpij) , fc_bo_i  (jpij) ,    &    
+      ALLOCATE( t_su_1d    (jpij) , a_i_1d    (jpij) , ht_i_1d   (jpij) ,    &   
+         &      ht_s_1d    (jpij) , fc_su    (jpij) , fc_bo_i  (jpij) ,    &    
          &      dh_s_tot  (jpij) , dh_i_surf(jpij) , dh_i_bott(jpij) ,    &    
-         &      dh_snowice(jpij) , sm_i_b   (jpij) , s_i_new  (jpij) ,    &    
-         &      s_snowice (jpij) , o_i_b    (jpij)                   ,    &
-         !                                                                !
-         &      t_s_b(jpij,nlay_s),                                       &
-         !                                                                !
-         &      t_i_b(jpij,jkmax), s_i_b(jpij,jkmax)                ,     &            
-         &      q_i_b(jpij,jkmax), q_s_b(jpij,jkmax)                , STAT=ierr(3))
+         &      dh_snowice(jpij) , sm_i_1d   (jpij) , s_i_new  (jpij) ,    &
+         &      t_s_1d(jpij,nlay_s),                                       &
+         &      t_i_1d(jpij,nlay_i+1), s_i_1d(jpij,nlay_i+1)                ,     &            
+         &      q_i_1d(jpij,nlay_i+1), q_s_1d(jpij,nlay_i+1)                ,     &
+         &      qh_i_old(jpij,0:nlay_i+1), h_i_old(jpij,0:nlay_i+1) , STAT=ierr(3))
       !
-      ALLOCATE( qt_i_in   (jpij,jpl) , qt_i_fin(jpij,jpl) , qt_s_in   (jpij,jpl) ,     &
-         &      qt_s_fin  (jpij,jpl) , dq_i    (jpij,jpl) , sum_fluxq (jpij,jpl) ,     &
-         &      fatm      (jpij,jpl) , foce    (jpij,jpl) , cons_error(jpij,jpl) ,     &
-         &      surf_error(jpij,jpl)                                             ,     &
-         !                                                                             !
-         &      q_i_layer_in(jpij,jkmax) , q_i_layer_fin(jpij,jkmax)             ,     &
-         &      dq_i_layer  (jpij,jkmax) , radab        (jpij,jkmax)             ,     &
-         !                                                                             !
-         &      ftotal_in(jpij), ftotal_fin(jpij)                                ,     &
-         !                                                                             !
-         &      fc_s(jpij,0:nlay_s) , de_s_lay(jpij,nlay_s)                      ,     &
-         &      fc_i(jpij,0:jkmax)  , de_i_lay(jpij,jkmax)                       , STAT=ierr(4) )
-
       thd_ice_alloc = MAXVAL( ierr )
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/domain.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/domain.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/domain.F90	(revision 5075)
@@ -337,5 +337,5 @@
       INTEGER ::   ios
       !!
-      NAMELIST/namzgr/ ln_zco, ln_zps, ln_sco
+      NAMELIST/namzgr/ ln_zco, ln_zps, ln_sco, ln_isfcav
       !!----------------------------------------------------------------------
 
@@ -354,7 +354,8 @@
          WRITE(numout,*) '~~~~~~~'
          WRITE(numout,*) '          Namelist namzgr : set vertical coordinate'
-         WRITE(numout,*) '             z-coordinate - full steps      ln_zco = ', ln_zco
-         WRITE(numout,*) '             z-coordinate - partial steps   ln_zps = ', ln_zps
-         WRITE(numout,*) '             s- or hybrid z-s-coordinate    ln_sco = ', ln_sco
+         WRITE(numout,*) '             z-coordinate - full steps      ln_zco    = ', ln_zco
+         WRITE(numout,*) '             z-coordinate - partial steps   ln_zps    = ', ln_zps
+         WRITE(numout,*) '             s- or hybrid z-s-coordinate    ln_sco    = ', ln_sco
+         WRITE(numout,*) '             ice shelf cavity               ln_isfcav = ', ln_isfcav
       ENDIF
 
@@ -363,5 +364,7 @@
       IF( ln_zps ) ioptio = ioptio + 1
       IF( ln_sco ) ioptio = ioptio + 1
-      IF ( ioptio /= 1 )   CALL ctl_stop( ' none or several vertical coordinate options used' )
+      IF( ln_isfcav ) ioptio = 33
+      IF ( ioptio /= 1  )   CALL ctl_stop( ' none or several vertical coordinate options used' )
+      IF ( ioptio == 33 )   CALL ctl_stop( ' isf cavity with off line module not yet done    ' )
 
    END SUBROUTINE dom_zgr
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/dommsk.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/dommsk.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/dommsk.F90	(revision 5075)
@@ -58,4 +58,5 @@
       ! Interior domain mask (used for global sum)
       ! --------------------
+      ssmask(:,:)  = tmask(:,:,1)
       tmask_i(:,:) = tmask(:,:,1)
       iif = jpreci                        ! thickness of exchange halos in i-axis
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/domrea.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/domrea.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/domrea.F90	(revision 5075)
@@ -164,5 +164,6 @@
 
          CALL iom_get( inum4, jpdom_data, 'mbathy', zmbk )              ! number of ocean t-points
-         mbathy(:,:) = INT( zmbk(:,:) )
+         mbathy (:,:) = INT( zmbk(:,:) )
+         misfdep(:,:) = 1                                               ! ice shelf case not yet done
          
          CALL zgr_bot_level                                             ! mbk. arrays (deepest ocean t-, u- & v-points
@@ -371,4 +372,5 @@
       !
       mbkt(:,:) = MAX( mbathy(:,:) , 1 )    ! bottom k-index of T-level (=1 over land)
+      mikt(:,:) = 1 ; miku(:,:) = 1; mikv(:,:) = 1; ! top k-index of T-level (=1 over open ocean; >1 beneath ice shelf)
       !                                     ! bottom k-index of W-level = mbkt+1
       DO jj = 1, jpjm1                      ! bottom k-index of u- (v-) level
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/dtadyn.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/dtadyn.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/dtadyn.F90	(revision 5075)
@@ -535,8 +535,13 @@
       !!---------------------------------------------------------------------
 #if defined key_ldfslp && ! defined key_c1d
-      CALL eos( pts, rhd, rhop, gdept_0(:,:,:) )   ! Time-filtered in situ density 
-      CALL bn2( pts, rn2 )         ! before Brunt-Vaisala frequency
-      IF( ln_zps )   &
-         &  CALL zps_hde( kt, jpts, pts, gtsu, gtsv, rhd, gru, grv )  ! Partial steps: before Horizontal DErivative
+      CALL eos_rab( pts, rab_n )       ! now local thermal/haline expension ratio at T-points
+      CALL bn2    ( pts, rab_n, rn2  ) ! now    Brunt-Vaisala
+      IF( ln_zps )   & ! Partial steps: before Horizontal DErivative
+        &    CALL zps_hde( kt, jpts, pts, gtsu, gtsv,  &        ! Partial steps: before horizontal gradient
+        &                                        rhd, gru , grv , aru , arv , gzu , gzv , ge3ru , ge3rv ,   &             !
+        &                                 gtui, gtvi, grui, grvi, arui, arvi, gzui, gzvi, ge3rui, ge3rvi    )  ! of t, s, rd at the last ocean level
+        ! only gtsu, gtsv, rhd, gru , grv are used 
+
+
          !                                                            ! of t, s, rd at the bottom ocean level
       CALL zdf_mxl( kt )            ! mixed layer depth
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/istate.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/istate.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/istate.F90	(revision 5075)
@@ -12,5 +12,4 @@
    USE oce             ! ocean dynamics and active tracers 
    USE dom_oce         ! ocean space and time domain 
-   USE daymod          ! calendar
 
    IMPLICIT NONE
@@ -47,6 +46,4 @@
       rn2  (:,:,:) = 0.e0 
       !
-      CALL day_init                           ! model calendar (using both namelist and restart infos)
-
    END SUBROUTINE istate_init
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/nemogcm.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/nemogcm.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OFF_SRC/nemogcm.F90	(revision 5075)
@@ -46,9 +46,10 @@
    USE timing          ! Timing
    USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
-   USE lbcnfd, ONLY: isendto, nsndto
+   USE lbcnfd, ONLY: isendto, nsndto, nfsloop, nfeloop ! Setup of north fold exchanges
 
    USE trc
    USE trcnam
    USE trcrst
+   USE diaptr         ! Need to initialise this as some variables are used in if statements later
 
    IMPLICIT NONE
@@ -298,5 +299,9 @@
       !                                     ! Passive tracers
                             CALL     trc_init   ! Passive tracers initialization
-
+      !
+      ! Initialise diaptr as some variables are used in if statements later (in
+      ! various advection and diffusion routines.
+                            CALL dia_ptr_init
+      !
       IF(lwp) WRITE(numout,cform_aaa)       ! Flag AAAAAAA
       !
@@ -589,5 +594,6 @@
       !!----------------------------------------------------------------------
       !!    1.0  ! 2011-10  (A. C. Coward, NOCS & J. Donners, PRACE)
-      !!    2.0  ! 2013-06 Setup avoiding MPI communication (I. Epicoco, S. Mocavero, CMCC) 
+      !!    2.0  ! 2013-06 Setup avoiding MPI communication (I. Epicoco, S.
+      !Mocavero, CMCC) 
       !!----------------------------------------------------------------------
 
@@ -612,27 +618,38 @@
           !loop over the other north-fold processes to find the processes
           !managing the points belonging to the sxT-dxT range
-          DO jn = jpnij - jpni +1, jpnij
-             IF ( njmppt(jn) == njmppmax ) THEN
+
+          DO jn = 1, jpni
                 !sxT is the first point (in the global domain) of the jn
                 !process
-                sxT = nimppt(jn)
+                sxT = nfiimpp(jn, jpnj)
                 !dxT is the last point (in the global domain) of the jn
                 !process
-                dxT = nimppt(jn) + nlcit(jn) - 1
+                dxT = nfiimpp(jn, jpnj) + nfilcit(jn, jpnj) - 1
                 IF ((sxM .gt. sxT) .AND. (sxM .lt. dxT)) THEN
                    nsndto = nsndto + 1
-                   isendto(nsndto) = jn
-                ELSEIF ((sxM .le. sxT) .AND. (dxM .gt. dxT)) THEN
+                     isendto(nsndto) = jn
+                ELSEIF ((sxM .le. sxT) .AND. (dxM .ge. dxT)) THEN
                    nsndto = nsndto + 1
-                   isendto(nsndto) = jn
+                     isendto(nsndto) = jn
                 ELSEIF ((dxM .lt. dxT) .AND. (sxT .lt. dxM)) THEN
                    nsndto = nsndto + 1
-                   isendto(nsndto) = jn
+                     isendto(nsndto) = jn
                 END IF
-             END IF
           END DO
+          nfsloop = 1
+          nfeloop = nlci
+          DO jn = 2,jpni-1
+           IF(nfipproc(jn,jpnj) .eq. (narea - 1)) THEN
+              IF (nfipproc(jn - 1 ,jpnj) .eq. -1) THEN
+                 nfsloop = nldi
+              ENDIF
+              IF (nfipproc(jn + 1,jpnj) .eq. -1) THEN
+                 nfeloop = nlei
+              ENDIF
+           ENDIF
+        END DO
+
       ENDIF
       l_north_nogather = .TRUE.
-
    END SUBROUTINE nemo_northcomms
 #else
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OOO_SRC/nemogcm.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OOO_SRC/nemogcm.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OOO_SRC/nemogcm.F90	(revision 5075)
@@ -54,9 +54,5 @@
    USE icbini          ! handle bergs, initialisation
    USE icbstp          ! handle bergs, calving, themodynamics and transport
-#if defined key_oasis3
    USE cpl_oasis3      ! OASIS3 coupling
-#elif defined key_oasis4
-   USE cpl_oasis4      ! OASIS4 coupling (not working)
-#endif
    USE lib_mpp         ! distributed memory computing
 #if defined key_iomput
@@ -166,22 +162,23 @@
 #if defined key_iomput
       IF( Agrif_Root() ) THEN
-# if defined key_oasis3 || defined key_oasis4
-         CALL cpl_prism_init( ilocal_comm )      ! nemo local communicator given by oasis
-         CALL xios_initialize( "oceanx",local_comm=ilocal_comm )
-# else
-         CALL  xios_initialize( "nemo",return_comm=ilocal_comm )
-# endif
+         IF( lk_cpl ) THEN
+            CALL cpl_init( ilocal_comm )                               ! nemo local communicator given by oasis
+            CALL xios_initialize( "oceanx",local_comm=ilocal_comm )    ! send nemo communicator to xios
+         ELSE
+            CALL  xios_initialize( "nemo",return_comm=ilocal_comm )    ! nemo local communicator given by xios
+         ENDIF
+      ENDIF
       ENDIF
       narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop, ilocal_comm )   ! Nodes selection
 #else
-# if defined key_oasis3 || defined key_oasis4
-      IF( Agrif_Root() ) THEN
-         CALL cpl_prism_init( ilocal_comm )                 ! nemo local communicator given by oasis
-      ENDIF
-      narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop, ilocal_comm )   ! Nodes selection (control print return in cltxt)
-# else
-      ilocal_comm = 0
-      narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop )                ! Nodes selection (control print return in cltxt)
-# endif
+      IF( lk_cpl ) THEN
+         IF( Agrif_Root() ) THEN
+            CALL cpl_init( ilocal_comm )                               ! nemo local communicator given by oasis
+         ENDIF
+         narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop, ilocal_comm )   ! Nodes selection (control print return in cltxt)
+      ELSE
+         ilocal_comm = 0
+         narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop )                ! Nodes selection (control print return in cltxt)
+      ENDIF
 #endif
       narea = narea + 1                                     ! mynode return the rank of proc (0 --> jpnij -1 )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ASM/asmbkg.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ASM/asmbkg.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ASM/asmbkg.F90	(revision 5075)
@@ -156,5 +156,9 @@
 #if defined key_lim2 || defined key_lim3
             IF(( nn_ice == 2 ) .OR. ( nn_ice == 3 )) THEN
-               CALL iom_rstput( kt, nitdin_r, inum, 'iceconc', 1.0 - frld(:,:)   )
+	       IF(ALLOCATED(frld)) THEN
+                  CALL iom_rstput( kt, nitdin_r, inum, 'iceconc', 1.0 - frld(:,:)   )
+               ELSE
+		  CALL ctl_warn('Ice concentration not written to background as ice variable frld not allocated on this timestep')
+	       ENDIF
             ENDIF
 #endif
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ASM/asminc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ASM/asminc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ASM/asminc.F90	(revision 5075)
@@ -56,14 +56,14 @@
     LOGICAL, PUBLIC, PARAMETER :: lk_asminc = .FALSE.  !: No assimilation increments
 #endif
-   LOGICAL, PUBLIC :: ln_bkgwri     !: No output of the background state fields
-   LOGICAL, PUBLIC :: ln_asmiau     !: No applying forcing with an assimilation increment
-   LOGICAL, PUBLIC :: ln_asmdin     !: No direct initialization
-   LOGICAL, PUBLIC :: ln_trainc     !: No tracer (T and S) assimilation increments
-   LOGICAL, PUBLIC :: ln_dyninc     !: No dynamics (u and v) assimilation increments
-   LOGICAL, PUBLIC :: ln_sshinc     !: No sea surface height assimilation increment
-   LOGICAL, PUBLIC :: ln_seaiceinc  !: No sea ice concentration increment
-   LOGICAL, PUBLIC :: ln_salfix     !: Apply minimum salinity check
+   LOGICAL, PUBLIC :: ln_bkgwri = .FALSE.      !: No output of the background state fields
+   LOGICAL, PUBLIC :: ln_asmiau = .FALSE.      !: No applying forcing with an assimilation increment
+   LOGICAL, PUBLIC :: ln_asmdin = .FALSE.      !: No direct initialization
+   LOGICAL, PUBLIC :: ln_trainc = .FALSE.      !: No tracer (T and S) assimilation increments
+   LOGICAL, PUBLIC :: ln_dyninc = .FALSE.      !: No dynamics (u and v) assimilation increments
+   LOGICAL, PUBLIC :: ln_sshinc = .FALSE.      !: No sea surface height assimilation increment
+   LOGICAL, PUBLIC :: ln_seaiceinc             !: No sea ice concentration increment
+   LOGICAL, PUBLIC :: ln_salfix = .FALSE.      !: Apply minimum salinity check
    LOGICAL, PUBLIC :: ln_temnofreeze = .FALSE. !: Don't allow the temperature to drop below freezing
-   INTEGER, PUBLIC :: nn_divdmp     !: Apply divergence damping filter nn_divdmp times
+   INTEGER, PUBLIC :: nn_divdmp                !: Apply divergence damping filter nn_divdmp times
 
    REAL(wp), PUBLIC, DIMENSION(:,:,:), ALLOCATABLE ::   t_bkg   , s_bkg      !: Background temperature and salinity
@@ -109,12 +109,9 @@
       !! ** Action  : 
       !!----------------------------------------------------------------------
-      INTEGER :: ji, jj, jk
-      INTEGER :: jt
-      INTEGER :: imid
-      INTEGER :: inum
+      INTEGER :: ji, jj, jk, jt  ! dummy loop indices
+      INTEGER :: imid, inum      ! local integers
+      INTEGER :: ios             ! Local integer output status for namelist read
       INTEGER :: iiauper         ! Number of time steps in the IAU period
       INTEGER :: icycper         ! Number of time steps in the cycle
-      INTEGER :: ios             ! Local integer output status for namelist read
-
       REAL(KIND=dp) :: ditend_date     ! Date YYYYMMDD.HHMMSS of final time step
       REAL(KIND=dp) :: ditbkg_date     ! Date YYYYMMDD.HHMMSS of background time step for Jb term
@@ -124,12 +121,11 @@
 
       REAL(wp) :: znorm        ! Normalization factor for IAU weights
-      REAL(wp) :: ztotwgt      ! Value of time-integrated IAU weights 
-                               ! (should be equal to one)
+      REAL(wp) :: ztotwgt      ! Value of time-integrated IAU weights (should be equal to one)
       REAL(wp) :: z_inc_dateb  ! Start date of interval on which increment is valid
       REAL(wp) :: z_inc_datef  ! End date of interval on which increment is valid
       REAL(wp) :: zdate_bkg    ! Date in background state file for DI
       REAL(wp) :: zdate_inc    ! Time axis in increments file
-
-      REAL(wp), POINTER, DIMENSION(:,:) :: hdiv
+      !
+      REAL(wp), POINTER, DIMENSION(:,:) ::   hdiv   ! 2D workspace
       !!
       NAMELIST/nam_asminc/ ln_bkgwri,                                      &
@@ -137,6 +133,5 @@
          &                 ln_asmdin, ln_asmiau,                           &
          &                 nitbkg, nitdin, nitiaustr, nitiaufin, niaufn,   &
-         &                 ln_salfix, salfixmin,                &
-         &                 nn_divdmp
+         &                 ln_salfix, salfixmin, nn_divdmp
       !!----------------------------------------------------------------------
 
@@ -144,5 +139,4 @@
       ! Read Namelist nam_asminc : assimilation increment interface
       !-----------------------------------------------------------------------
-
       ln_seaiceinc = .FALSE.
       ln_temnofreeze = .FALSE.
@@ -570,7 +564,7 @@
       ! used to prevent the applied increments taking the temperature below the local freezing point 
 
-      DO jk=1, jpkm1
-         fzptnz (:,:,jk) = tfreez( tsn(:,:,jk,jp_sal), fsdept(:,:,jk) )
-      ENDDO
+      DO jk = 1, jpkm1
+         fzptnz(:,:,jk) = eos_fzp( tsn(:,:,jk,jp_sal), fsdept(:,:,jk) )
+      END DO
 
       IF ( ln_asmiau ) THEN
@@ -587,6 +581,5 @@
             IF(lwp) THEN
                WRITE(numout,*) 
-               WRITE(numout,*) 'tra_asm_inc : Tracer IAU at time step = ', &
-                  &  kt,' with IAU weight = ', wgtiau(it)
+               WRITE(numout,*) 'tra_asm_inc : Tracer IAU at time step = ', kt,' with IAU weight = ', wgtiau(it)
                WRITE(numout,*) '~~~~~~~~~~~~'
             ENDIF
@@ -636,6 +629,5 @@
             IF (ln_temnofreeze) THEN
                ! Do not apply negative increments if the temperature will fall below freezing
-               WHERE(t_bkginc(:,:,:) > 0.0_wp .OR. &
-                  &   tsn(:,:,:,jp_tem) + t_bkginc(:,:,:) > fzptnz(:,:,:) ) 
+               WHERE( t_bkginc(:,:,:) > 0.0_wp .OR. tsn(:,:,:,jp_tem) + t_bkginc(:,:,:) > fzptnz(:,:,:) ) 
                   tsn(:,:,:,jp_tem) = t_bkg(:,:,:) + t_bkginc(:,:,:)   
                END WHERE
@@ -646,6 +638,5 @@
                ! Do not apply negative increments if the salinity will fall below a specified
                ! minimum value salfixmin
-               WHERE(s_bkginc(:,:,:) > 0.0_wp .OR. &
-                  &   tsn(:,:,:,jp_sal) + s_bkginc(:,:,:) > salfixmin ) 
+               WHERE( s_bkginc(:,:,:) > 0.0_wp .OR. tsn(:,:,:,jp_sal) + s_bkginc(:,:,:) > salfixmin ) 
                   tsn(:,:,:,jp_sal) = s_bkg(:,:,:) + s_bkginc(:,:,:)   
                END WHERE
@@ -654,15 +645,20 @@
             ENDIF
 
-            tsb(:,:,:,:) = tsn(:,:,:,:)               ! Update before fields
-
-            CALL eos( tsb, rhd, rhop, gdept_0(:,:,:) )                ! Before potential and in situ densities
-         
+            tsb(:,:,:,:) = tsn(:,:,:,:)                 ! Update before fields
+
+            CALL eos( tsb, rhd, rhop, gdept_0(:,:,:) )  ! Before potential and in situ densities
+!!gm  fabien
+!            CALL eos( tsb, rhd, rhop )                ! Before potential and in situ densities
+!!gm
+
+
             IF( ln_zps .AND. .NOT. lk_c1d ) &
-               &  CALL zps_hde( nit000, jpts, tsb, &  ! Partial steps: before horizontal derivative
-               &                gtsu, gtsv, rhd,   &  ! of T, S, rd at the bottom ocean level
-               &                gru , grv )
+               &  CALL zps_hde( nit000, jpts, tsb, gtsu, gtsv,  &        ! Partial steps: before horizontal gradient
+               &                rhd, gru , grv, aru, arv, gzu, gzv, ge3ru, ge3rv,  &             !
+               &                gtui, gtvi, grui, grvi, arui, arvi, gzui, gzvi, ge3rui, ge3rvi  )  ! of t, s, rd at the last ocean level
 
 #if defined key_zdfkpp
             CALL eos( tsn, rhd, fsdept_n(:,:,:) )                      ! Compute rhd
+!!gm fabien            CALL eos( tsn, rhd )                      ! Compute rhd
 #endif
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdy_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdy_oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdy_oce.F90	(revision 5075)
@@ -104,9 +104,10 @@
    REAL(wp),    DIMENSION(jp_bdy) ::   rn_time_dmp_out          !: Damping time scale in days at radiation outflow points
 
-#if ( defined key_lim2 || defined key_lim3 )
    CHARACTER(len=20), DIMENSION(jp_bdy) ::   cn_ice_lim       ! Choice of boundary condition for sea ice variables 
    INTEGER, DIMENSION(jp_bdy)           ::   nn_ice_lim_dta   !: = 0 use the initial state as bdy dta ; 
                                                               !: = 1 read it in a NetCDF file
-#endif
+   REAL(wp),    DIMENSION(jp_bdy) ::   rn_ice_tem             !: choice of the temperature of incoming sea ice
+   REAL(wp),    DIMENSION(jp_bdy) ::   rn_ice_sal             !: choice of the salinity    of incoming sea ice
+   REAL(wp),    DIMENSION(jp_bdy) ::   rn_ice_age             !: choice of the age         of incoming sea ice
    !
    
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydta.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydta.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydta.F90	(revision 5075)
@@ -676,5 +676,5 @@
                CALL iom_close ( inum )
                !CALL fld_clopn ( bn_a_i, nyear, nmonth, nday, ldstop=.TRUE. )
-               !CALL iom_open ( bn_a_i %clname, inum )
+               !CALL iom_open ( bn_a_i%clname, inum )
                !id1 = iom_varid ( bn_a_i%num, bn_a_i%clvar, kdimsz=zdimsz, kndims=zndims, ldstop = .FALSE. )
       	       IF ( zndims == 4 ) THEN
@@ -740,5 +740,5 @@
       jstart = 1
       DO ib_bdy = 1, nb_bdy
-         jend = nb_bdy_fld(ib_bdy) 
+         jend = jstart - 1 + nb_bdy_fld(ib_bdy) 
          CALL fld_fill( bf(jstart:jend), blf_i(jstart:jend), cn_dir_array(ib_bdy), 'bdy_dta',   &
          &              'open boundary conditions', 'nambdy_dta' )
@@ -907,4 +907,2 @@
    !!==============================================================================
 END MODULE bdydta
-
-
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn.F90	(revision 5075)
@@ -30,5 +30,5 @@
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
    USE in_out_manager  !
-   USE domvvl
+   USE domvvl          ! variable volume
 
    IMPLICIT NONE
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn2d.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn2d.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdydyn2d.F90	(revision 5075)
@@ -176,4 +176,6 @@
          spgu(ii, ij) = dta%ssh(jb)
       END DO
+
+      CALL lbc_bdy_lnk( spgu(:,:), 'T', 1., ib_bdy )
       !
       igrd = 2      ! Flather bc on u-velocity; 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyice_lim.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyice_lim.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyice_lim.F90	(revision 5075)
@@ -24,11 +24,12 @@
    USE par_ice_2
    USE ice_2           ! LIM_2 ice variables
+   USE dom_ice_2       ! sea-ice domain
 #elif defined key_lim3
    USE par_ice
    USE ice             ! LIM_3 ice variables
+   USE dom_ice         ! sea-ice domain
 #endif 
    USE par_oce         ! ocean parameters
    USE dom_oce         ! ocean space and time domain variables 
-   USE dom_ice          ! sea-ice domain
    USE sbc_oce         ! Surface boundary condition: ocean fields
    USE bdy_oce         ! ocean open boundary conditions
@@ -44,6 +45,4 @@
    PUBLIC   bdy_ice_lim_dyn ! routine called in limrhg
 
-   REAL(wp) ::   epsi20 = 1.e-20_wp  ! module constants
-   REAL(wp) ::   epsi10 = 1.e-10_wp  ! min area allowed by ice model
    !!----------------------------------------------------------------------
    !! NEMO/OPA 3.3 , NEMO Consortium (2010)
@@ -97,9 +96,6 @@
       INTEGER  ::   ji, jj, ii, ij     ! local scalar
       REAL(wp) ::   zwgt, zwgt1        ! local scalar
-      REAL(wp) ::   zinda, ztmelts, zdh
-
-      REAL(wp), PARAMETER  ::   zsal = 6.3    ! arbitrary salinity    for incoming ice
-      REAL(wp), PARAMETER  ::   ztem = 270.0  ! arbitrary temperature for incoming ice
-      REAL(wp), PARAMETER  ::   zage = 30.0   ! arbitrary age         for incoming ice
+      REAL(wp) ::   ztmelts, zdh
+
       !!------------------------------------------------------------------------------
       !
@@ -117,43 +113,4 @@
          hicif(ji,jj) = ( hicif(ji,jj) * zwgt1 + dta%hicif(jb) * zwgt ) * tmask(ji,jj,1)     ! Ice depth 
          hsnif(ji,jj) = ( hsnif(ji,jj) * zwgt1 + dta%hsnif(jb) * zwgt ) * tmask(ji,jj,1)     ! Snow depth
-
-!         zinda = 1.0 - MAX( 0.0_wp , SIGN ( 1.0_wp , - frld(ji,jj) ) ) ! 0 if no ice
-!         !------------------------------
-!         ! Sea ice surface temperature
-!         !------------------------------
-!         sist(ji,jj)   = zinda * 270.0 + ( 1.0 - zinda ) * tfu(ji,jj)
-!         !-----------------------------------------------
-!         ! Ice/snow temperatures and energy stored in brines 
-!         !-----------------------------------------------
-!         !!! TO BE CONTIUNED (as LIM3 below) !!!
-!            zindhe = MAX( 0.e0, SIGN( 1.e0, fcor(1,jj) ) )              ! = 0 for SH, =1 for NH
-! 
-!               ! Recover in situ values.
-!               zindb         = MAX( rzero, SIGN( rone, zs0a(ji,jj) - epsi06 ) )
-!               zacrith       = 1.0 - ( zindhe * acrit(1) + ( 1.0 - zindhe ) * acrit(2) )
-!               zs0a (ji,jj)  = zindb * MIN( zs0a(ji,jj), zacrith )
-!               hsnif(ji,jj)  = zindb * ( zs0sn(ji,jj) /MAX( zs0a(ji,jj), epsi16 ) )
-!               hicif(ji,jj)  = zindb * ( zs0ice(ji,jj)/MAX( zs0a(ji,jj), epsi16 ) )
-!               zindsn        = MAX( rzero, SIGN( rone, hsnif(ji,jj) - epsi06 ) )
-!               zindic        = MAX( rzero, SIGN( rone, hicif(ji,jj) - epsi03 ) )
-!               zindb         = MAX( zindsn, zindic )
-!               zs0a (ji,jj)  = zindb * zs0a(ji,jj)
-!               frld (ji,jj)  = 1.0 - zs0a(ji,jj)
-!               hsnif(ji,jj)  = zindsn * hsnif(ji,jj)
-!               hicif(ji,jj)  = zindic * hicif(ji,jj)
-!               zusvosn       = 1.0/MAX( hsnif(ji,jj) * zs0a(ji,jj), epsi16 )
-!               zusvoic       = 1.0/MAX( hicif(ji,jj) * zs0a(ji,jj), epsi16 )
-!               zignm         = MAX( rzero,  SIGN( rone, hsndif - hsnif(ji,jj) ) )
-!               zrtt          = 173.15 * rone 
-!               ztsn          =          zignm   * tbif(ji,jj,1)  &
-!                              + ( 1.0 - zignm ) * MIN( MAX( zrtt, rt0_snow * zusvosn * zs0c0(ji,jj)) , tfu(ji,jj) ) 
-!               ztic1          = MIN( MAX( zrtt, rt0_ice * zusvoic * zs0c1(ji,jj) ) , tfu(ji,jj) )
-!               ztic2          = MIN( MAX( zrtt, rt0_ice * zusvoic * zs0c2(ji,jj) ) , tfu(ji,jj) )
-! 
-!               tbif(ji,jj,1) = zindsn * ztsn  + ( 1.0 - zindsn ) * tfu(ji,jj)               
-!               tbif(ji,jj,2) = zindic * ztic1 + ( 1.0 - zindic ) * tfu(ji,jj)
-!               tbif(ji,jj,3) = zindic * ztic2 + ( 1.0 - zindic ) * tfu(ji,jj)
-!               qstoif(ji,jj) = zindb  * xlic * zs0st(ji,jj) /  MAX( zs0a(ji,jj), epsi16 )
-
       END DO 
 
@@ -217,10 +174,10 @@
             IF ( v_ice(ji  ,jj-1) > 0. .AND. vmask(ji  ,jj+1,1) == 0. ) jpbound = 1; ii = ji  ; ij = jj-1
 
-            zinda = 1.0 - MAX( 0.0_wp , SIGN ( 1.0_wp , - at_i(ii,ij) + 0.01 ) ) ! 0 if no ice
+            rswitch = 1.0 - MAX( 0.0_wp , SIGN ( 1.0_wp , - at_i(ii,ij) + 0.01 ) ) ! 0 if no ice
 
             ! concentration and thickness
-            a_i (ji,jj,jl) = a_i (ii,ij,jl) * zinda
-            ht_i(ji,jj,jl) = ht_i(ii,ij,jl) * zinda
-            ht_s(ji,jj,jl) = ht_s(ii,ij,jl) * zinda
+            a_i (ji,jj,jl) = a_i (ii,ij,jl) * rswitch
+            ht_i(ji,jj,jl) = ht_i(ii,ij,jl) * rswitch
+            ht_s(ji,jj,jl) = ht_s(ii,ij,jl) * rswitch
 
             ! Ice and snow volumes
@@ -233,13 +190,13 @@
 
                ! Ice salinity, age, temperature
-               sm_i(ji,jj,jl)   = zinda * zsal  + ( 1.0 - zinda ) * s_i_min
-               o_i(ji,jj,jl)    = zinda * zage  + ( 1.0 - zinda )
-               t_su(ji,jj,jl)   = zinda * ztem  + ( 1.0 - zinda ) * ztem
+               sm_i(ji,jj,jl)   = rswitch * rn_ice_sal(ib_bdy)  + ( 1.0 - rswitch ) * s_i_min
+               o_i(ji,jj,jl)    = rswitch * rn_ice_age(ib_bdy)  + ( 1.0 - rswitch )
+               t_su(ji,jj,jl)   = rswitch * rn_ice_tem(ib_bdy)  + ( 1.0 - rswitch ) * rn_ice_tem(ib_bdy)
                DO jk = 1, nlay_s
-                  t_s(ji,jj,jk,jl) = zinda * ztem + ( 1.0 - zinda ) * rtt
+                  t_s(ji,jj,jk,jl) = rswitch * rn_ice_tem(ib_bdy) + ( 1.0 - rswitch ) * rtt
                END DO
                DO jk = 1, nlay_i
-                  t_i(ji,jj,jk,jl) = zinda * ztem + ( 1.0 - zinda ) * rtt 
-                  s_i(ji,jj,jk,jl) = zinda * zsal + ( 1.0 - zinda ) * s_i_min
+                  t_i(ji,jj,jk,jl) = rswitch * rn_ice_tem(ib_bdy) + ( 1.0 - rswitch ) * rtt 
+                  s_i(ji,jj,jk,jl) = rswitch * rn_ice_sal(ib_bdy) + ( 1.0 - rswitch ) * s_i_min
                END DO
                
@@ -247,16 +204,22 @@
  
                ! Ice salinity, age, temperature
-               sm_i(ji,jj,jl)   = zinda * sm_i(ii,ij,jl)  + ( 1.0 - zinda ) * s_i_min
-               o_i(ji,jj,jl)    = zinda * o_i(ii,ij,jl)   + ( 1.0 - zinda )
-               t_su(ji,jj,jl)   = zinda * t_su(ii,ij,jl)  + ( 1.0 - zinda ) * rtt
+               sm_i(ji,jj,jl)   = rswitch * sm_i(ii,ij,jl)  + ( 1.0 - rswitch ) * s_i_min
+               o_i(ji,jj,jl)    = rswitch * o_i(ii,ij,jl)   + ( 1.0 - rswitch )
+               t_su(ji,jj,jl)   = rswitch * t_su(ii,ij,jl)  + ( 1.0 - rswitch ) * rtt
                DO jk = 1, nlay_s
-                  t_s(ji,jj,jk,jl) = zinda * t_s(ii,ij,jk,jl) + ( 1.0 - zinda ) * rtt
+                  t_s(ji,jj,jk,jl) = rswitch * t_s(ii,ij,jk,jl) + ( 1.0 - rswitch ) * rtt
                END DO
                DO jk = 1, nlay_i
-                  t_i(ji,jj,jk,jl) = zinda * t_i(ii,ij,jk,jl) + ( 1.0 - zinda ) * rtt
-                  s_i(ji,jj,jk,jl) = zinda * s_i(ii,ij,jk,jl) + ( 1.0 - zinda ) * s_i_min
+                  t_i(ji,jj,jk,jl) = rswitch * t_i(ii,ij,jk,jl) + ( 1.0 - rswitch ) * rtt
+                  s_i(ji,jj,jk,jl) = rswitch * s_i(ii,ij,jk,jl) + ( 1.0 - rswitch ) * s_i_min
                END DO
 
             END SELECT
+
+            ! if salinity is constant, then overwrite rn_ice_sal
+            IF( num_sal == 1 ) THEN
+               sm_i(ji,jj,jl)   = bulk_sal
+               s_i (ji,jj,:,jl) = bulk_sal
+            ENDIF
 
             ! contents
@@ -265,5 +228,5 @@
             DO jk = 1, nlay_s
                ! Snow energy of melting
-               e_s(ji,jj,jk,jl) = zinda * rhosn * ( cpic * ( rtt - t_s(ji,jj,jk,jl) ) + lfus )
+               e_s(ji,jj,jk,jl) = rswitch * rhosn * ( cpic * ( rtt - t_s(ji,jj,jk,jl) ) + lfus )
                ! Change dimensions
                e_s(ji,jj,jk,jl) = e_s(ji,jj,jk,jl) / unit_fac
@@ -274,5 +237,5 @@
                ztmelts          = - tmut * s_i(ji,jj,jk,jl) + rtt !Melting temperature in K                  
                ! heat content per unit volume
-               e_i(ji,jj,jk,jl) = zinda * rhoic * &
+               e_i(ji,jj,jk,jl) = rswitch * rhoic * &
                   (   cpic    * ( ztmelts - t_i(ji,jj,jk,jl) ) &
                   +   lfus    * ( 1.0 - (ztmelts-rtt) / MIN((t_i(ji,jj,jk,jl)-rtt),-epsi20) ) &
@@ -331,5 +294,5 @@
       INTEGER  ::   ji, jj             ! local scalar
       INTEGER  ::   ib_bdy ! Loop index
-      REAL(wp) ::   zmsk1, zmsk2, zflag, zinda 
+      REAL(wp) ::   zmsk1, zmsk2, zflag
      !!------------------------------------------------------------------------------
       !
@@ -338,5 +301,5 @@
       DO ib_bdy=1, nb_bdy
          !
-         SELECT CASE( nn_ice_lim(ib_bdy) )
+         SELECT CASE( cn_ice_lim(ib_bdy) )
 
          CASE('none')
@@ -355,5 +318,5 @@
                   ji    = idx_bdy(ib_bdy)%nbi(jb,jgrd)
                   jj    = idx_bdy(ib_bdy)%nbj(jb,jgrd)
-                  zflag = idx_bdy(ib_bdy)%flagu(jb)
+                  zflag = idx_bdy(ib_bdy)%flagu(jb,jgrd)
                   
                   IF ( ABS( zflag ) == 1. ) THEN  ! eastern and western boundaries
@@ -371,6 +334,6 @@
                   ENDIF
                   ! mask ice velocities
-                  zinda = 1.0 - MAX( 0.0_wp , SIGN ( 1.0_wp , - at_i(ji,jj) + 0.01 ) ) ! 0 if no ice
-                  u_ice(ji,jj) = zinda * u_ice(ji,jj)
+                  rswitch = 1.0 - MAX( 0.0_wp , SIGN ( 1.0_wp , - at_i(ji,jj) + 0.01 ) ) ! 0 if no ice
+                  u_ice(ji,jj) = rswitch * u_ice(ji,jj)
                   
                ENDDO
@@ -384,5 +347,5 @@
                   ji    = idx_bdy(ib_bdy)%nbi(jb,jgrd)
                   jj    = idx_bdy(ib_bdy)%nbj(jb,jgrd)
-                  zflag = idx_bdy(ib_bdy)%flagv(jb)
+                  zflag = idx_bdy(ib_bdy)%flagv(jb,jgrd)
                   
                   IF ( ABS( zflag ) == 1. ) THEN  ! northern and southern boundaries
@@ -400,6 +363,6 @@
                   ENDIF
                   ! mask ice velocities
-                  zinda = 1.0 - MAX( 0.0_wp , SIGN ( 1.0_wp , - at_i(ji,jj) + 0.01 ) ) ! 0 if no ice
-                  v_ice(ji,jj) = zinda * v_ice(ji,jj)
+                  rswitch = 1.0 - MAX( 0.0_wp , SIGN ( 1.0_wp , - at_i(ji,jj) + 0.01 ) ) ! 0 if no ice
+                  v_ice(ji,jj) = rswitch * v_ice(ji,jj)
                   
                ENDDO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyini.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyini.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyini.F90	(revision 5075)
@@ -100,7 +100,6 @@
          &             cn_dyn3d, nn_dyn3d_dta, cn_tra, nn_tra_dta,             &  
          &             ln_tra_dmp, ln_dyn3d_dmp, rn_time_dmp, rn_time_dmp_out, &
-#if ( defined key_lim2 || defined key_lim3 )
          &             cn_ice_lim, nn_ice_lim_dta,                           &
-#endif
+         &             rn_ice_tem, rn_ice_sal, rn_ice_age,                 &
          &             ln_vol, nn_volctl, nn_rimwidth
       !!
@@ -359,4 +358,7 @@
         ENDIF
         IF(lwp) WRITE(numout,*)
+        IF(lwp) WRITE(numout,*) '      tem of bdy sea-ice = ', rn_ice_tem(ib_bdy)         
+        IF(lwp) WRITE(numout,*) '      sal of bdy sea-ice = ', rn_ice_sal(ib_bdy)         
+        IF(lwp) WRITE(numout,*) '      age of bdy sea-ice = ', rn_ice_age(ib_bdy)         
 #endif
 
@@ -1152,9 +1154,9 @@
          END DO
 
-         tmask_i (:,:) = tmask(:,:,1) * tmask_i(:,:)
+         tmask_i (:,:) = ssmask(:,:) * tmask_i(:,:)
 
       ENDIF ! ln_mask_file=.TRUE.
       
-      bdytmask(:,:) = tmask(:,:,1)
+      bdytmask(:,:) = ssmask(:,:)
       IF( .not. ln_mask_file ) THEN
          ! If .not. ln_mask_file then we need to derive mask on U and V grid 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdytides.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdytides.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdytides.F90	(revision 5075)
@@ -418,7 +418,4 @@
       DO ib_bdy = 1,nb_bdy
 
-         ! line below should be simplified (runoff case)
-!! CHANUT: TO BE SORTED OUT
-!!         IF (( nn_dyn2d_dta(ib_bdy) .ge. 2 ).AND.(nn_tra(ib_bdy).NE.4)) THEN
          IF ( nn_dyn2d_dta(ib_bdy) .ge. 2 ) THEN
 
@@ -453,12 +450,12 @@
             IF ( PRESENT(kit) ) THEN
                IF ( lk_first_btstp ) THEN ! Save slow varying open boundary data:
-                  dta_bdy_s(ib_bdy)%ssh(1:ilen0(1)) = dta_bdy(ib_bdy)%ssh(1:ilen0(1))
-                  dta_bdy_s(ib_bdy)%u2d(1:ilen0(2)) = dta_bdy(ib_bdy)%u2d(1:ilen0(2))
-                  dta_bdy_s(ib_bdy)%v2d(1:ilen0(3)) = dta_bdy(ib_bdy)%v2d(1:ilen0(3))
+                  IF ( dta_bdy(ib_bdy)%ll_ssh ) dta_bdy_s(ib_bdy)%ssh(1:ilen0(1)) = dta_bdy(ib_bdy)%ssh(1:ilen0(1))
+                  IF ( dta_bdy(ib_bdy)%ll_u2d ) dta_bdy_s(ib_bdy)%u2d(1:ilen0(2)) = dta_bdy(ib_bdy)%u2d(1:ilen0(2))
+                  IF ( dta_bdy(ib_bdy)%ll_v2d ) dta_bdy_s(ib_bdy)%v2d(1:ilen0(3)) = dta_bdy(ib_bdy)%v2d(1:ilen0(3))
 
                ELSE ! Initialize arrays from slow varying open boundary data:            
-                  dta_bdy(ib_bdy)%ssh(1:ilen0(1)) = dta_bdy_s(ib_bdy)%ssh(1:ilen0(1))
-                  dta_bdy(ib_bdy)%u2d(1:ilen0(2)) = dta_bdy_s(ib_bdy)%u2d(1:ilen0(2))
-                  dta_bdy(ib_bdy)%v2d(1:ilen0(3)) = dta_bdy_s(ib_bdy)%v2d(1:ilen0(3))
+                  IF ( dta_bdy(ib_bdy)%ll_ssh ) dta_bdy(ib_bdy)%ssh(1:ilen0(1)) = dta_bdy_s(ib_bdy)%ssh(1:ilen0(1))
+                  IF ( dta_bdy(ib_bdy)%ll_u2d ) dta_bdy(ib_bdy)%u2d(1:ilen0(2)) = dta_bdy_s(ib_bdy)%u2d(1:ilen0(2))
+                  IF ( dta_bdy(ib_bdy)%ll_v2d ) dta_bdy(ib_bdy)%v2d(1:ilen0(3)) = dta_bdy_s(ib_bdy)%v2d(1:ilen0(3))
                ENDIF
             ENDIF
@@ -471,25 +468,31 @@
                z_sist = zramp * SIN( z_sarg )
                !
-               igrd=1                              ! SSH on tracer grid
-               DO ib = 1, ilen0(igrd)
-                  dta_bdy(ib_bdy)%ssh(ib) = dta_bdy(ib_bdy)%ssh(ib) + &
-                     &                      ( tides(ib_bdy)%ssh(ib,itide,1)*z_cost + &
-                     &                        tides(ib_bdy)%ssh(ib,itide,2)*z_sist )
-               END DO
-               !
-               igrd=2                              ! U grid
-               DO ib = 1, ilen0(igrd)
-                  dta_bdy(ib_bdy)%u2d(ib) = dta_bdy(ib_bdy)%u2d(ib) + &
-                     &                      ( tides(ib_bdy)%u(ib,itide,1)*z_cost + &
-                     &                        tides(ib_bdy)%u(ib,itide,2)*z_sist )
-               END DO
-               !
-               igrd=3                              ! V grid
-               DO ib = 1, ilen0(igrd) 
-                  dta_bdy(ib_bdy)%v2d(ib) = dta_bdy(ib_bdy)%v2d(ib) + &
-                     &                      ( tides(ib_bdy)%v(ib,itide,1)*z_cost + &
-                     &                        tides(ib_bdy)%v(ib,itide,2)*z_sist )
-               END DO
-            END DO
+               IF ( dta_bdy(ib_bdy)%ll_ssh ) THEN
+                  igrd=1                              ! SSH on tracer grid
+                  DO ib = 1, ilen0(igrd)
+                     dta_bdy(ib_bdy)%ssh(ib) = dta_bdy(ib_bdy)%ssh(ib) + &
+                        &                      ( tides(ib_bdy)%ssh(ib,itide,1)*z_cost + &
+                        &                        tides(ib_bdy)%ssh(ib,itide,2)*z_sist )
+                  END DO
+               ENDIF
+               !
+               IF ( dta_bdy(ib_bdy)%ll_u2d ) THEN
+                  igrd=2                              ! U grid
+                  DO ib = 1, ilen0(igrd)
+                     dta_bdy(ib_bdy)%u2d(ib) = dta_bdy(ib_bdy)%u2d(ib) + &
+                        &                      ( tides(ib_bdy)%u(ib,itide,1)*z_cost + &
+                        &                        tides(ib_bdy)%u(ib,itide,2)*z_sist )
+                  END DO
+               ENDIF
+               !
+               IF ( dta_bdy(ib_bdy)%ll_v2d ) THEN
+                  igrd=3                              ! V grid
+                  DO ib = 1, ilen0(igrd) 
+                     dta_bdy(ib_bdy)%v2d(ib) = dta_bdy(ib_bdy)%v2d(ib) + &
+                        &                      ( tides(ib_bdy)%v(ib,itide,1)*z_cost + &
+                        &                        tides(ib_bdy)%v(ib,itide,2)*z_sist )
+                  END DO
+               ENDIF
+            END DO             
          END IF
       END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyvol.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyvol.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/BDY/bdyvol.F90	(revision 5075)
@@ -17,4 +17,5 @@
    USE timing          ! Timing
    USE oce             ! ocean dynamics and tracers 
+   USE sbcisf          ! ice shelf
    USE dom_oce         ! ocean space and time domain 
    USE phycst          ! physical constants
@@ -90,5 +91,5 @@
       ! Calculate the cumulate surface Flux z_cflxemp (m3/s) over all the domain
       ! -----------------------------------------------------------------------
-      z_cflxemp = SUM ( ( emp(:,:)-rnf(:,:) ) * bdytmask(:,:) * e1t(:,:) * e2t(:,:) ) / rau0
+      z_cflxemp = SUM ( ( emp(:,:)-rnf(:,:)+rdivisf*fwfisf(:,:) ) * bdytmask(:,:) * e1t(:,:) * e2t(:,:) ) / rau0
       IF( lk_mpp )   CALL mpp_sum( z_cflxemp )     ! sum over the global domain
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/c1d.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/c1d.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/c1d.F90	(revision 5075)
@@ -27,4 +27,5 @@
    REAL(wp), PUBLIC            ::  rn_lat1d     ! Column latitude
    REAL(wp), PUBLIC            ::  rn_lon1d     ! Column longitude
+   LOGICAL , PUBLIC            ::  ln_c1d_locpt ! Localization (or not) of 1D column in a grid
 
    !!----------------------------------------------------------------------
@@ -44,5 +45,5 @@
       !!----------------------------------------------------------------------
       INTEGER ::   ios                 ! Local integer output status for namelist read
-      NAMELIST/namc1d/ rn_lat1d, rn_lon1d
+      NAMELIST/namc1d/ rn_lat1d, rn_lon1d , ln_c1d_locpt
       !!----------------------------------------------------------------------
       !
@@ -63,6 +64,7 @@
          WRITE(numout,*) '~~~~~~~~'
          WRITE(numout,*) '   Namelist namc1d : set options for the C1D model'
-         WRITE(numout,*) '      column latitude                 rn_lat1d = ', rn_lat1d
-         WRITE(numout,*) '      column longitude                rn_lon1d = ', rn_lon1d
+         WRITE(numout,*) '      column latitude                 rn_lat1d     = ', rn_lat1d
+         WRITE(numout,*) '      column longitude                rn_lon1d     = ', rn_lon1d
+         WRITE(numout,*) '      column localization in a grid   ln_c1d_locpt = ', ln_c1d_locpt
       ENDIF
       !
@@ -78,4 +80,6 @@
    LOGICAL, PUBLIC, PARAMETER ::   lk_c1d = .FALSE.   !: 1D config. flag de-activated
    REAL(wp)                   ::   rn_lat1d, rn_lon1d
+   LOGICAL , PUBLIC           ::   ln_c1d_locpt = .FALSE. 
+
 CONTAINS
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/domc1d.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/domc1d.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/domc1d.F90	(revision 5075)
@@ -43,7 +43,16 @@
       !! ** Action  : Recalculate jpizoom, jpjzoom (indices of C1D zoom)
       !!----------------------------------------------------------------------
+      NAMELIST/namdom/ nn_bathy, rn_bathy , rn_e3zps_min, rn_e3zps_rat, nn_msh, rn_hmin,   &
+         &             nn_acc   , rn_atfp     , rn_rdt      , rn_rdtmin ,                  &
+         &             rn_rdtmax, rn_rdth     , nn_closea , ln_crs,    &
+         &             jphgr_msh, &
+         &             ppglam0, ppgphi0, ppe1_deg, ppe2_deg, ppe1_m, ppe2_m, &
+         &             ppsur, ppa0, ppa1, ppkth, ppacr, ppdzmin, pphmax, ldbletanh, &
+         &             ppa2, ppkth2, ppacr2
+
       INTEGER  ::  ji, jj                          ! Dummy loop indices
       INTEGER  ::  inum                            ! Coordinate file handle (case 0)
       INTEGER  ::  ijeq                            ! Index of equator T point (case 4)
+      INTEGER  ::  ios                             ! Local integer output status for namelist read
 
       INTEGER , DIMENSION(2) ::   iloc             ! Minloc returned indices
@@ -63,4 +72,13 @@
       IF( nn_timing == 1 )   CALL timing_start('dom_c1d')
 
+      REWIND( numnam_ref )              ! Namelist namdom in reference namelist : space & time domain (bathymetry, mesh, timestep)
+      READ  ( numnam_ref, namdom, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namdom in reference namelist', lwp )
+  
+      !
+      REWIND( numnam_cfg )              ! Namelist namdom in configuration namelist : space & time domain (bathymetry, mesh, timestep)
+      READ  ( numnam_cfg, namdom, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namdom in configuration namelist', lwp )
+
       CALL wrk_alloc( jpidta, jpjdta, gphidta, glamdta, zdist )
 
@@ -80,9 +98,4 @@
          CALL iom_get( inum, jpdom_unknown, 'gphit', gphidta ) ! so use jpdom_unknown not jpdom_data
          CALL iom_close ( inum )
-
-         PRINT *,'Check dom_c1d coordinates file data read in:' !!!
-         PRINT *,'Bottom-left most glamdta is ', glamdta(1,1)    !!! Need to check
-         PRINT *,'Bottom-left most gphidta is ', gphidta(1,1)    !!! field read
-         PRINT *,'We are using nimpp,njmpp = ' , nimpp,njmpp     !!!
 
       CASE ( 1 )                 ! geographical mesh on the sphere with regular grid-spacing
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/dyndmp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/dyndmp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/dyndmp.F90	(revision 5075)
@@ -15,6 +15,4 @@
    USE dom_oce        ! ocean: domain variables
    USE c1d            ! 1D vertical configuration
-   USE trdmod         ! ocean: trends
-   USE trdmod_oce     ! ocean: trends variables
    USE tradmp         ! ocean: internal damping
    USE zdf_oce        ! ocean: vertical physics
@@ -164,5 +162,4 @@
       !! ** Action  : - (ua,va)   momentum trends updated with the damping trend
       !!----------------------------------------------------------------------
-      !
       INTEGER, INTENT(in) ::   kt                        ! ocean time-step index
       !!
@@ -236,6 +233,6 @@
       END SELECT
       !
-      !                           ! Trend diagnostic
-      IF( l_trddyn )   CALL trd_mod( utrdmp, vtrdmp, jpdyn_trd_dat, 'DYN', kt )
+!!gm      !                           ! Trend diagnostic
+!!gm      IF( l_trddyn )   CALL trd_mod( utrdmp, vtrdmp, jpdyn_trd_dat, 'DYN', kt )
       !
       !                           ! Control print
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/step_c1d.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/step_c1d.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/C1D/step_c1d.F90	(revision 5075)
@@ -72,6 +72,6 @@
       ! Ocean physics update                (ua, va, ta, sa used as workspace)
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-                         CALL bn2( tsb, rn2b )        ! before Brunt-Vaisala frequency
-                         CALL bn2( tsn, rn2  )        ! now    Brunt-Vaisala frequency
+                         CALL bn2( tsb, rab_b, rn2b ) ! before Brunt-Vaisala frequency
+                         CALL bn2( tsn, rab_n, rn2  ) ! now    Brunt-Vaisala frequency
       !  VERTICAL PHYSICS   
                          CALL zdf_bfr( kstp )         ! bottom friction
@@ -115,5 +115,5 @@
       ! Passive Tracer Model
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-                         CALL trc_stp( kstp )            ! time-stepping
+                        CALL trc_stp( kstp )       ! time-stepping
 #endif
 
@@ -121,32 +121,32 @@
       ! Active tracers                              (ua, va used as workspace)
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-                             tsa(:,:,:,:) = 0.e0                ! set tracer trends to zero
+                        tsa(:,:,:,:) = 0._wp       ! set tracer trends to zero
 
-                             CALL tra_sbc    ( kstp )        ! surface boundary condition
-      IF( ln_traqsr      )   CALL tra_qsr    ( kstp )        ! penetrative solar radiation qsr
-      IF( ln_tradmp      )   CALL tra_dmp    ( kstp )        ! internal damping trends- tracers
-      IF( lk_zdfkpp      )   CALL tra_kpp    ( kstp )        ! KPP non-local tracer fluxes
-                             CALL tra_zdf    ( kstp )        ! vertical mixing
-                             CALL tra_nxt    ( kstp )        ! tracer fields at next time step
-      IF( ln_zdfnpc      )   CALL tra_npc    ( kstp )        ! applied non penetrative convective adjustment on (t,s)
-                             CALL eos( tsb, rhd, rhop, gdept_0(:,:,:) )      ! now (swap=before) in situ density for dynhpg module
+                        CALL tra_sbc( kstp )       ! surface boundary condition
+      IF( ln_traqsr )   CALL tra_qsr( kstp )       ! penetrative solar radiation qsr
+      IF( ln_tradmp )   CALL tra_dmp( kstp )       ! internal damping trends- tracers
+      IF( lk_zdfkpp )   CALL tra_kpp( kstp )       ! KPP non-local tracer fluxes
+                        CALL tra_zdf( kstp )       ! vertical mixing
+                        CALL eos( tsn, rhd, rhop, gdept_0(:,:,:) )   ! now potential density for zdfmxl
+      IF( ln_zdfnpc )   CALL tra_npc( kstp )       ! applied non penetrative convective adjustment on (t,s)
+                        CALL tra_nxt( kstp )       ! tracer fields at next time step
 
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       ! Dynamics                                    (ta, sa used as workspace)
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-                               ua(:,:,:) = 0.e0               ! set dynamics trends to zero
-                               va(:,:,:) = 0.e0
+                        ua(:,:,:) = 0._wp          ! set dynamics trends to zero
+                        va(:,:,:) = 0._wp
 
-      IF( ln_dyndmp      )     CALL dyn_dmp    ( kstp )       ! internal damping trends- momentum
-                               CALL dyn_cor_c1d( kstp )       ! vorticity term including Coriolis
-                               CALL dyn_zdf    ( kstp )       ! vertical diffusion
-                               CALL dyn_nxt_c1d( kstp )       ! lateral velocity at next time step
+      IF( ln_dyndmp )   CALL dyn_dmp    ( kstp )   ! internal damping trends- momentum
+                        CALL dyn_cor_c1d( kstp )   ! vorticity term including Coriolis
+                        CALL dyn_zdf    ( kstp )   ! vertical diffusion
+                        CALL dyn_nxt_c1d( kstp )   ! lateral velocity at next time step
 
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       ! Control and restarts
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-                                 CALL stp_ctl( kstp, indic )
-      IF( kstp == nit000     )   CALL iom_close( numror )             ! close input  ocean restart file
-      IF( lrst_oce           )   CALL rst_write  ( kstp )             ! write output ocean restart file
+                             CALL stp_ctl( kstp, indic )
+      IF( kstp == nit000 )   CALL iom_close( numror )      ! close input  ocean restart file
+      IF( lrst_oce       )   CALL rst_write( kstp )        ! write output ocean restart file
       !
    END SUBROUTINE stp_c1d
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaar5.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaar5.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaar5.F90	(revision 5075)
@@ -104,5 +104,11 @@
          zbotpres(:,:) = zbotpres(:,:) + fse3t(:,:,jk) * zrhd(:,:,jk)
       END DO
-      IF( .NOT.lk_vvl )   zbotpres(:,:) = zbotpres(:,:) + sshn(:,:) * zrhd(:,:,1)
+      IF( .NOT.lk_vvl ) THEN
+         DO ji=1,jpi
+            DO jj=1,jpj
+               zbotpres(ji,jj) = zbotpres(ji,jj) + sshn(ji,jj) * zrhd(ji,jj,mikt(ji,jj)) + riceload(ji,jj)
+            END DO
+         END DO
+      END IF
       !                                         
       zarho = SUM( area(:,:) * zbotpres(:,:) ) 
@@ -120,5 +126,11 @@
          zbotpres(:,:) = zbotpres(:,:) + fse3t(:,:,jk) * zrhd(:,:,jk)
       END DO
-      IF( .NOT.lk_vvl )   zbotpres(:,:) = zbotpres(:,:) + sshn(:,:) * zrhd(:,:,1)
+      IF( .NOT.lk_vvl ) THEN
+         DO ji=1,jpi
+            DO jj=1,jpj
+               zbotpres(ji,jj) = zbotpres(ji,jj) + sshn(ji,jj) * zrhd(ji,jj,mikt(ji,jj)) + riceload(ji,jj)
+            END DO
+         END DO
+      END IF
       !    
       zarho = SUM( area(:,:) * zbotpres(:,:) ) 
@@ -145,6 +157,10 @@
       END DO
       IF( .NOT.lk_vvl ) THEN
-         ztemp = ztemp + SUM( zarea_ssh(:,:) * tsn(:,:,1,jp_tem) )
-         zsal  = zsal  + SUM( zarea_ssh(:,:) * tsn(:,:,1,jp_sal) )
+         DO ji=1,jpi
+            DO jj=1,jpj
+               ztemp = ztemp + zarea_ssh(ji,jj) * tsn(ji,jj,mikt(ji,jj),jp_tem) 
+               zsal  = zsal  + zarea_ssh(ji,jj) * tsn(ji,jj,mikt(ji,jj),jp_sal) 
+            END DO
+         END DO
       ENDIF
       IF( lk_mpp ) THEN  
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diafwb.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diafwb.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diafwb.F90	(revision 5075)
@@ -7,7 +7,5 @@
    !!            8.5  !  02-06  (G. Madec)  F90: Free form and module
    !!            9.0  !  05-11  (V. Garnier) Surface pressure gradient organization
-   !!----------------------------------------------------------------------
-#if ! defined key_coupled
- 
+   !!---------------------------------------------------------------------- 
    !!----------------------------------------------------------------------
    !!   Only for ORCA2 ORCA1 and ORCA025
@@ -29,6 +27,4 @@
 
    PUBLIC dia_fwb    ! routine called by step.F90
-
-   LOGICAL, PUBLIC, PARAMETER ::   lk_diafwb = .TRUE.    !: fresh water budget flag
 
    REAL(wp)               ::   a_fwf ,          &
@@ -453,15 +449,4 @@
    END SUBROUTINE dia_fwb
 
-#else
-   !!----------------------------------------------------------------------
-   !!   Default option :                                       Dummy Module
-   !!----------------------------------------------------------------------
-   LOGICAL, PUBLIC, PARAMETER ::   lk_diafwb = .FALSE.    !: fresh water budget flag
-CONTAINS
-   SUBROUTINE dia_fwb( kt )        ! Empty routine
-      WRITE(*,*) 'dia_fwb: : You should not have seen this print! error?', kt
-   END SUBROUTINE dia_fwb
-#endif
-
    !!======================================================================
 END MODULE diafwb
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaharm.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaharm.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaharm.F90	(revision 5075)
@@ -18,4 +18,5 @@
    USE daymod
    USE tide_mod
+   !
    USE in_out_manager  ! I/O units
    USE iom             ! I/0 library
@@ -34,9 +35,9 @@
    INTEGER, PARAMETER :: jpdimsparse  = jpincomax*300*24
 
-   !                            !!!namelist variables
+   !                         !!** namelist variables **
    INTEGER ::   nit000_han    ! First time step used for harmonic analysis
    INTEGER ::   nitend_han    ! Last time step used for harmonic analysis
    INTEGER ::   nstep_han     ! Time step frequency for harmonic analysis
-   INTEGER ::   nb_ana           ! Number of harmonics to analyse
+   INTEGER ::   nb_ana        ! Number of harmonics to analyse
 
    INTEGER , ALLOCATABLE, DIMENSION(:)       ::   name
@@ -119,5 +120,5 @@
             ENDIF
          END DO
-      ENDDO
+      END DO
       !
       IF(lwp) THEN
@@ -158,5 +159,5 @@
       ! ----------------------------
       ALLOCATE( ana_temp(jpi,jpj,2*nb_ana,3) )
-      ana_temp(:,:,:,:) = 0.e0
+      ana_temp(:,:,:,:) = 0._wp
 
    END SUBROUTINE dia_harm_init
@@ -179,32 +180,31 @@
       IF( nn_timing == 1 )   CALL timing_start('dia_harm')
 
-      IF ( kt == nit000 ) CALL dia_harm_init
-
-      IF ( ((kt.GE.nit000_han).AND.(kt.LE.nitend_han)).AND. &
-           (MOD(kt,nstep_han).EQ.0) ) THEN
-
-        ztime = (kt-nit000+1)*rdt 
+      IF( kt == nit000 ) CALL dia_harm_init
+
+      IF( kt >= nit000_han .AND. kt <= nitend_han .AND. MOD(kt,nstep_han) == 0 ) THEN
+
+         ztime = (kt-nit000+1) * rdt 
        
-        nhc = 0
-        DO jh = 1,nb_ana
-          DO jc = 1,2
-            nhc = nhc+1
-            ztemp =(     MOD(jc,2) * ft(jh) *COS(ana_freq(jh)*ztime + vt(jh) + ut(jh))  &
-                    +(1.-MOD(jc,2))* ft(jh) *SIN(ana_freq(jh)*ztime + vt(jh) + ut(jh)))
-
-            DO jj = 1,jpj
-              DO ji = 1,jpi
-                ! Elevation
-                ana_temp(ji,jj,nhc,1) = ana_temp(ji,jj,nhc,1) + ztemp*sshn(ji,jj)           *tmask(ji,jj,1)        
+         nhc = 0
+         DO jh = 1, nb_ana
+            DO jc = 1, 2
+               nhc = nhc+1
+               ztemp =(     MOD(jc,2) * ft(jh) *COS(ana_freq(jh)*ztime + vt(jh) + ut(jh))  &
+                  &    +(1.-MOD(jc,2))* ft(jh) *SIN(ana_freq(jh)*ztime + vt(jh) + ut(jh)))
+
+               DO jj = 1,jpj
+                  DO ji = 1,jpi
+                     ! Elevation
+                     ana_temp(ji,jj,nhc,1) = ana_temp(ji,jj,nhc,1) + ztemp*sshn(ji,jj)           *tmask_i(ji,jj)        
 #if defined key_dynspg_ts
-                ana_temp(ji,jj,nhc,2) = ana_temp(ji,jj,nhc,2) + ztemp*un_b(ji,jj)*hur(ji,jj)*umask(ji,jj,1)
-                ana_temp(ji,jj,nhc,3) = ana_temp(ji,jj,nhc,3) + ztemp*vn_b(ji,jj)*hvr(ji,jj)*vmask(ji,jj,1)
-#endif
-              END DO
-            END DO
-
-          END DO
-        END DO
-       
+                     ana_temp(ji,jj,nhc,2) = ana_temp(ji,jj,nhc,2) + ztemp*un_b(ji,jj)*hur(ji,jj)*umask_i(ji,jj)
+                     ana_temp(ji,jj,nhc,3) = ana_temp(ji,jj,nhc,3) + ztemp*vn_b(ji,jj)*hvr(ji,jj)*vmask_i(ji,jj)
+#endif
+                  END DO
+               END DO
+               !
+            END DO
+         END DO
+         !       
       END IF
 
@@ -249,6 +249,6 @@
          keq = keq + 1
          kun = 0
-         DO jh = 1,nb_ana
-            DO jc = 1,2
+         DO jh = 1, nb_ana
+            DO jc = 1, 2
                kun = kun + 1
                ksp = ksp + 1
@@ -294,9 +294,9 @@
                X1 = ana_amp(ji,jj,jh,1)
                X2 =-ana_amp(ji,jj,jh,2)
-               out_eta(ji,jj,jh       ) = X1 * tmask(ji,jj,1)
-               out_eta(ji,jj,jh+nb_ana) = X2 * tmask(ji,jj,1)
-            ENDDO
-         ENDDO
-      ENDDO
+               out_eta(ji,jj,jh       ) = X1 * tmask_i(ji,jj)
+               out_eta(ji,jj,jh+nb_ana) = X2 * tmask_i(ji,jj)
+            END DO
+         END DO
+      END DO
 
       ! ubar:
@@ -309,6 +309,6 @@
                   kun = kun + 1
                   ztmp4(kun)=ana_temp(ji,jj,kun,2)
-               ENDDO
-            ENDDO
+               END DO
+            END DO
 
             CALL SUR_DETERMINE(jj+1)
@@ -316,6 +316,6 @@
             ! Fill output array
             DO jh = 1, nb_ana
-               ana_amp(ji,jj,jh,1)=ztmp7((jh-1)*2+1)
-               ana_amp(ji,jj,jh,2)=ztmp7((jh-1)*2+2)
+               ana_amp(ji,jj,jh,1) = ztmp7((jh-1)*2+1)
+               ana_amp(ji,jj,jh,2) = ztmp7((jh-1)*2+2)
             END DO
 
@@ -326,8 +326,8 @@
          DO ji = 1, jpi
             DO jh = 1, nb_ana 
-               X1=ana_amp(ji,jj,jh,1)
+               X1= ana_amp(ji,jj,jh,1)
                X2=-ana_amp(ji,jj,jh,2)
-               out_u(ji,jj,jh) = X1 * umask(ji,jj,1)
-               out_u (ji,jj,nb_ana+jh) = X2 * umask(ji,jj,1)
+               out_u(ji,jj,       jh) = X1 * umask_i(ji,jj)
+               out_u(ji,jj,nb_ana+jh) = X2 * umask_i(ji,jj)
             ENDDO
          ENDDO
@@ -343,6 +343,6 @@
                   kun = kun + 1
                   ztmp4(kun)=ana_temp(ji,jj,kun,3)
-               ENDDO
-            ENDDO
+               END DO
+            END DO
 
             CALL SUR_DETERMINE(jj+1)
@@ -362,9 +362,9 @@
                X1=ana_amp(ji,jj,jh,1)
                X2=-ana_amp(ji,jj,jh,2)
-               out_v(ji,jj,jh)=X1 * vmask(ji,jj,1)
-               out_v(ji,jj,nb_ana+jh)=X2 * vmask(ji,jj,1)
-            ENDDO
-         ENDDO
-      ENDDO
+               out_v(ji,jj,       jh)=X1 * vmask_i(ji,jj)
+               out_v(ji,jj,nb_ana+jh)=X2 * vmask_i(ji,jj)
+            END DO
+         END DO
+      END DO
 
       CALL dia_wri_harm ! Write results in files
@@ -437,118 +437,118 @@
 #else
       DO jh = 1, nb_ana
-         CALL iom_put( TRIM(tname(jh))//'x_v', out_u(:,:,jh       ) )
-         CALL iom_put( TRIM(tname(jh))//'y_v', out_u(:,:,jh+nb_ana) )
-      END DO
-#endif
-
+         CALL iom_put( TRIM(tname(jh))//'x_v', out_v(:,:,jh       ) )
+         CALL iom_put( TRIM(tname(jh))//'y_v', out_v(:,:,jh+nb_ana) )
+      END DO
+#endif
+      !
    END SUBROUTINE dia_wri_harm
 
 
    SUBROUTINE SUR_DETERMINE(init)
-   !!---------------------------------------------------------------------------------
-   !!                      *** ROUTINE SUR_DETERMINE ***
-   !!    
-   !!    
-   !!       
-   !!---------------------------------------------------------------------------------
-   INTEGER, INTENT(in) ::   init 
-   !
-   INTEGER                         :: ji_sd, jj_sd, ji1_sd, ji2_sd, jk1_sd, jk2_sd
-   REAL(wp)                        :: zval1, zval2, zx1
-   REAL(wp), POINTER, DIMENSION(:) :: ztmpx, zcol1, zcol2
-   INTEGER , POINTER, DIMENSION(:) :: ipos2, ipivot
-   !---------------------------------------------------------------------------------
-   CALL wrk_alloc( jpincomax , ztmpx , zcol1 , zcol2 )
-   CALL wrk_alloc( jpincomax , ipos2 , ipivot        )
+      !!---------------------------------------------------------------------------------
+      !!                      *** ROUTINE SUR_DETERMINE ***
+      !!    
+      !!    
+      !!       
+      !!---------------------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   init 
+      !
+      INTEGER                         :: ji_sd, jj_sd, ji1_sd, ji2_sd, jk1_sd, jk2_sd
+      REAL(wp)                        :: zval1, zval2, zx1
+      REAL(wp), POINTER, DIMENSION(:) :: ztmpx, zcol1, zcol2
+      INTEGER , POINTER, DIMENSION(:) :: ipos2, ipivot
+      !---------------------------------------------------------------------------------
+      CALL wrk_alloc( jpincomax , ztmpx , zcol1 , zcol2 )
+      CALL wrk_alloc( jpincomax , ipos2 , ipivot        )
             
-   IF( init == 1 ) THEN
-      IF( nsparse > jpdimsparse )   CALL ctl_stop( 'STOP', 'SUR_DETERMINE : nsparse .GT. jpdimsparse')
-      IF( ninco   > jpincomax   )   CALL ctl_stop( 'STOP', 'SUR_DETERMINE : ninco .GT. jpincomax')
-      !
-      ztmp3(:,:) = 0._wp
-      !
-      DO jk1_sd = 1, nsparse
-         DO jk2_sd = 1, nsparse
-            nisparse(jk2_sd) = nisparse(jk2_sd)
-            njsparse(jk2_sd) = njsparse(jk2_sd)
-            IF( nisparse(jk2_sd) == nisparse(jk1_sd) ) THEN
-               ztmp3(njsparse(jk1_sd),njsparse(jk2_sd)) = ztmp3(njsparse(jk1_sd),njsparse(jk2_sd))  &
-                                                        + valuesparse(jk1_sd)*valuesparse(jk2_sd)
-            ENDIF
-         END DO
-      END DO
-
-      DO jj_sd = 1 ,ninco
-          ipos1(jj_sd) = jj_sd
-          ipos2(jj_sd) = jj_sd
-      ENDDO
-
-      DO ji_sd = 1 , ninco
-
-         !find greatest non-zero pivot:
-         zval1 = ABS(ztmp3(ji_sd,ji_sd))
-
-         ipivot(ji_sd) = ji_sd
-         DO jj_sd = ji_sd, ninco
-            zval2 = ABS(ztmp3(ji_sd,jj_sd))
-            IF( zval2.GE.zval1 )THEN
-               ipivot(ji_sd) = jj_sd
-               zval1         = zval2
-            ENDIF
-         ENDDO
-
-         DO ji1_sd = 1, ninco
-            zcol1(ji1_sd)               = ztmp3(ji1_sd,ji_sd)
-            zcol2(ji1_sd)               = ztmp3(ji1_sd,ipivot(ji_sd))
-            ztmp3(ji1_sd,ji_sd)         = zcol2(ji1_sd)
-            ztmp3(ji1_sd,ipivot(ji_sd)) = zcol1(ji1_sd)
-         ENDDO
-
-         ipos2(ji_sd)         = ipos1(ipivot(ji_sd))
-         ipos2(ipivot(ji_sd)) = ipos1(ji_sd)
-         ipos1(ji_sd)         = ipos2(ji_sd)
-         ipos1(ipivot(ji_sd)) = ipos2(ipivot(ji_sd))
-         zpivot(ji_sd)        = ztmp3(ji_sd,ji_sd)
-         DO jj_sd = 1, ninco
-            ztmp3(ji_sd,jj_sd) = ztmp3(ji_sd,jj_sd) / zpivot(ji_sd)
-         ENDDO
-
+      IF( init == 1 ) THEN
+         IF( nsparse > jpdimsparse )   CALL ctl_stop( 'STOP', 'SUR_DETERMINE : nsparse .GT. jpdimsparse')
+         IF( ninco   > jpincomax   )   CALL ctl_stop( 'STOP', 'SUR_DETERMINE : ninco .GT. jpincomax')
+         !
+         ztmp3(:,:) = 0._wp
+         !
+         DO jk1_sd = 1, nsparse
+            DO jk2_sd = 1, nsparse
+               nisparse(jk2_sd) = nisparse(jk2_sd)
+               njsparse(jk2_sd) = njsparse(jk2_sd)
+               IF( nisparse(jk2_sd) == nisparse(jk1_sd) ) THEN
+                  ztmp3(njsparse(jk1_sd),njsparse(jk2_sd)) = ztmp3(njsparse(jk1_sd),njsparse(jk2_sd))  &
+                     &                                     + valuesparse(jk1_sd)*valuesparse(jk2_sd)
+               ENDIF
+            END DO
+         END DO
+         !
+         DO jj_sd = 1 ,ninco
+            ipos1(jj_sd) = jj_sd
+            ipos2(jj_sd) = jj_sd
+         END DO
+         !
+         DO ji_sd = 1 , ninco
+            !
+            !find greatest non-zero pivot:
+            zval1 = ABS(ztmp3(ji_sd,ji_sd))
+            !
+            ipivot(ji_sd) = ji_sd
+            DO jj_sd = ji_sd, ninco
+               zval2 = ABS(ztmp3(ji_sd,jj_sd))
+               IF( zval2.GE.zval1 )THEN
+                  ipivot(ji_sd) = jj_sd
+                  zval1         = zval2
+               ENDIF
+            END DO
+            !
+            DO ji1_sd = 1, ninco
+               zcol1(ji1_sd)               = ztmp3(ji1_sd,ji_sd)
+               zcol2(ji1_sd)               = ztmp3(ji1_sd,ipivot(ji_sd))
+               ztmp3(ji1_sd,ji_sd)         = zcol2(ji1_sd)
+               ztmp3(ji1_sd,ipivot(ji_sd)) = zcol1(ji1_sd)
+            END DO
+            !
+            ipos2(ji_sd)         = ipos1(ipivot(ji_sd))
+            ipos2(ipivot(ji_sd)) = ipos1(ji_sd)
+            ipos1(ji_sd)         = ipos2(ji_sd)
+            ipos1(ipivot(ji_sd)) = ipos2(ipivot(ji_sd))
+            zpivot(ji_sd)        = ztmp3(ji_sd,ji_sd)
+            DO jj_sd = 1, ninco
+               ztmp3(ji_sd,jj_sd) = ztmp3(ji_sd,jj_sd) / zpivot(ji_sd)
+            END DO
+            !
+            DO ji2_sd = ji_sd+1, ninco
+               zpilier(ji2_sd,ji_sd)=ztmp3(ji2_sd,ji_sd)
+               DO jj_sd=1,ninco
+                  ztmp3(ji2_sd,jj_sd)=  ztmp3(ji2_sd,jj_sd) - ztmp3(ji_sd,jj_sd) * zpilier(ji2_sd,ji_sd)
+               END DO
+            END DO
+            !
+         END DO
+         !
+      ENDIF ! End init==1
+
+      DO ji_sd = 1, ninco
+         ztmp4(ji_sd) = ztmp4(ji_sd) / zpivot(ji_sd)
          DO ji2_sd = ji_sd+1, ninco
-            zpilier(ji2_sd,ji_sd)=ztmp3(ji2_sd,ji_sd)
-            DO jj_sd=1,ninco
-               ztmp3(ji2_sd,jj_sd)=  ztmp3(ji2_sd,jj_sd) - ztmp3(ji_sd,jj_sd) * zpilier(ji2_sd,ji_sd)
-            ENDDO
-         ENDDO
-
-      ENDDO
-
-   ENDIF ! End init==1
-
-   DO ji_sd = 1, ninco
-      ztmp4(ji_sd) = ztmp4(ji_sd) / zpivot(ji_sd)
-      DO ji2_sd = ji_sd+1, ninco
-         ztmp4(ji2_sd) = ztmp4(ji2_sd) - ztmp4(ji_sd) * zpilier(ji2_sd,ji_sd)
-      ENDDO
-   ENDDO
-
-   !system solving: 
-   ztmpx(ninco) = ztmp4(ninco) / ztmp3(ninco,ninco)
-   ji_sd = ninco
-   DO ji_sd = ninco-1, 1, -1
-      zx1=0.
-      DO jj_sd = ji_sd+1, ninco
-         zx1 = zx1 + ztmpx(jj_sd) * ztmp3(ji_sd,jj_sd)
-      ENDDO
-      ztmpx(ji_sd) = ztmp4(ji_sd)-zx1
-   ENDDO
-
-   DO jj_sd =1, ninco
-      ztmp7(ipos1(jj_sd))=ztmpx(jj_sd)
-   ENDDO
-
-   CALL wrk_dealloc( jpincomax , ztmpx , zcol1 , zcol2 )
-   CALL wrk_dealloc( jpincomax , ipos2 , ipivot        )
-
-  END SUBROUTINE SUR_DETERMINE
+            ztmp4(ji2_sd) = ztmp4(ji2_sd) - ztmp4(ji_sd) * zpilier(ji2_sd,ji_sd)
+         END DO
+      END DO
+
+      !system solving: 
+      ztmpx(ninco) = ztmp4(ninco) / ztmp3(ninco,ninco)
+      ji_sd = ninco
+      DO ji_sd = ninco-1, 1, -1
+         zx1 = 0._wp
+         DO jj_sd = ji_sd+1, ninco
+            zx1 = zx1 + ztmpx(jj_sd) * ztmp3(ji_sd,jj_sd)
+         END DO
+         ztmpx(ji_sd) = ztmp4(ji_sd)-zx1
+      END DO
+
+      DO jj_sd =1, ninco
+         ztmp7(ipos1(jj_sd))=ztmpx(jj_sd)
+      END DO
+
+      CALL wrk_dealloc( jpincomax , ztmpx , zcol1 , zcol2 )
+      CALL wrk_dealloc( jpincomax , ipos2 , ipivot        )
+      !
+   END SUBROUTINE SUR_DETERMINE
 
 #else
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diahsb.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diahsb.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diahsb.F90	(revision 5075)
@@ -9,21 +9,27 @@
 
    !!----------------------------------------------------------------------
+   !!   dia_hsb       : Diagnose the conservation of ocean heat and salt contents, and volume
+   !!   dia_hsb_rst   : Read or write DIA file in restart file
+   !!   dia_hsb_init  : Initialization of the conservation diagnostic
+   !!----------------------------------------------------------------------
    USE oce             ! ocean dynamics and tracers
    USE dom_oce         ! ocean space and time domain
    USE phycst          ! physical constants
    USE sbc_oce         ! surface thermohaline fluxes
-   USE in_out_manager  ! I/O manager
+   USE sbcrnf          ! river runoff
+   USE sbcisf          ! ice shelves
    USE domvvl          ! vertical scale factors
    USE traqsr          ! penetrative solar radiation
    USE trabbc          ! bottom boundary condition 
-   USE lib_mpp         ! distributed memory computing library
    USE trabbc          ! bottom boundary condition
    USE bdy_par         ! (for lk_bdy)
+   USE restart         ! ocean restart
+   !
+   USE iom             ! I/O manager
+   USE in_out_manager  ! I/O manager
+   USE lib_fortran     ! glob_sum
+   USE lib_mpp         ! distributed memory computing library
    USE timing          ! preformance summary
-   USE iom             ! I/O manager
-   USE lib_fortran     ! glob_sum
-   USE restart         ! ocean restart
-   USE wrk_nemo         ! work arrays
-   USE sbcrnf         ! river runoffd
+   USE wrk_nemo        ! work arrays
 
    IMPLICIT NONE
@@ -36,15 +42,15 @@
    LOGICAL, PUBLIC ::   ln_diahsb   !: check the heat and salt budgets
 
-   REAL(dp)                                ::   surf_tot                !
-   REAL(dp)                                ::   frc_t      , frc_s     , frc_v   ! global forcing trends
-   REAL(dp)                                ::   frc_wn_t      , frc_wn_s ! global forcing trends
-   REAL(dp), DIMENSION(:,:)  , ALLOCATABLE ::   surf      , ssh_ini              !
-   REAL(dp), DIMENSION(:,:,:), ALLOCATABLE ::   hc_loc_ini, sc_loc_ini, e3t_ini  !
-   REAL(dp), DIMENSION(:,:)  , ALLOCATABLE ::   ssh_hc_loc_ini, ssh_sc_loc_ini
+   REAL(wp) ::   surf_tot              ! ocean surface
+   REAL(wp) ::   frc_t, frc_s, frc_v   ! global forcing trends
+   REAL(wp) ::   frc_wn_t, frc_wn_s    ! global forcing trends
+   !
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   surf          , ssh_ini          !
+   REAL(wp), DIMENSION(:,:)  , ALLOCATABLE ::   ssh_hc_loc_ini, ssh_sc_loc_ini   !
+   REAL(wp), DIMENSION(:,:,:), ALLOCATABLE ::   hc_loc_ini, sc_loc_ini, e3t_ini  !
 
    !! * Substitutions
 #  include "domzgr_substitute.h90"
 #  include "vectopt_loop_substitute.h90"
-
    !!----------------------------------------------------------------------
    !! NEMO/OPA 3.3 , NEMO Consortium (2010)
@@ -52,5 +58,4 @@
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
    !!----------------------------------------------------------------------
-
 CONTAINS
 
@@ -67,27 +72,37 @@
       !!---------------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
-      !!
-      INTEGER    ::   jk                          ! dummy loop indice
-      REAL(dp)   ::   zdiff_hc    , zdiff_sc      ! heat and salt content variations
-      REAL(dp)   ::   zdiff_hc1   , zdiff_sc1     ! -   -   -   -   -   -   -   - 
-      REAL(dp)   ::   zdiff_v1    , zdiff_v2      ! volume variation
-      REAL(dp)   ::   zerr_hc1    , zerr_sc1       ! heat and salt content misfit
-      REAL(dp)   ::   zvol_tot                    ! volume
-      REAL(dp)   ::   z_frc_trd_t , z_frc_trd_s   !    -     -
-      REAL(dp)   ::   z_frc_trd_v                 !    -     -
-      REAL(dp)   ::   z_wn_trd_t , z_wn_trd_s   !    -     -
-      REAL(dp)   ::   z_ssh_hc , z_ssh_sc   !    -     -
+      !
+      INTEGER    ::   ji, jj, jk                  ! dummy loop indice
+      REAL(wp)   ::   zdiff_hc    , zdiff_sc      ! heat and salt content variations
+      REAL(wp)   ::   zdiff_hc1   , zdiff_sc1     !  -         -     -        - 
+      REAL(wp)   ::   zdiff_v1    , zdiff_v2      ! volume variation
+      REAL(wp)   ::   zerr_hc1    , zerr_sc1      ! heat and salt content misfit
+      REAL(wp)   ::   zvol_tot                    ! volume
+      REAL(wp)   ::   z_frc_trd_t , z_frc_trd_s   !    -     -
+      REAL(wp)   ::   z_frc_trd_v                 !    -     -
+      REAL(wp)   ::   z_wn_trd_t , z_wn_trd_s     !    -     -
+      REAL(wp)   ::   z_ssh_hc , z_ssh_sc         !    -     -
+      REAL(wp), DIMENSION(:,:), POINTER ::   z2d0, z2d1
       !!---------------------------------------------------------------------------
       IF( nn_timing == 1 )   CALL timing_start('dia_hsb')      
-
+      CALL wrk_alloc( jpi,jpj,   z2d0, z2d1 )
+      !
+      tsn(:,:,:,1) = tsn(:,:,:,1) * tmask(:,:,:) ; tsb(:,:,:,1) = tsb(:,:,:,1) * tmask(:,:,:) ;
+      tsn(:,:,:,2) = tsn(:,:,:,2) * tmask(:,:,:) ; tsb(:,:,:,2) = tsb(:,:,:,2) * tmask(:,:,:) ;
       ! ------------------------- !
       ! 1 - Trends due to forcing !
       ! ------------------------- !
-      z_frc_trd_v = r1_rau0 * glob_sum( - ( emp(:,:) - rnf(:,:) ) * surf(:,:) ) ! volume fluxes
-      z_frc_trd_t =           glob_sum( sbc_tsc(:,:,jp_tem) * surf(:,:) )       ! heat fluxes
-      z_frc_trd_s =           glob_sum( sbc_tsc(:,:,jp_sal) * surf(:,:) )       ! salt fluxes
+      z_frc_trd_v = r1_rau0 * glob_sum( - ( emp(:,:) - rnf(:,:) + rdivisf * fwfisf(:,:) ) * surf(:,:) ) ! volume fluxes
+      z_frc_trd_t =           glob_sum( sbc_tsc(:,:,jp_tem) * surf(:,:) )                               ! heat fluxes
+      z_frc_trd_s =           glob_sum( sbc_tsc(:,:,jp_sal) * surf(:,:) )                               ! salt fluxes
       ! Add runoff heat & salt input
       IF( ln_rnf    )   z_frc_trd_t = z_frc_trd_t + glob_sum( rnf_tsc(:,:,jp_tem) * surf(:,:) )
       IF( ln_rnf_sal)   z_frc_trd_s = z_frc_trd_s + glob_sum( rnf_tsc(:,:,jp_sal) * surf(:,:) )
+      ! Add geothermal ice shelf
+      IF( nn_isf .GE. 1 )  THEN
+          z_frc_trd_t = z_frc_trd_t &
+              &   + glob_sum( ( risf_tsc(:,:,jp_tem) - rdivisf * fwfisf(:,:) * (-1.9) * r1_rau0 ) * surf(:,:) )
+          z_frc_trd_s = z_frc_trd_s + (1.0_wp - rdivisf) * glob_sum( risf_tsc(:,:,jp_sal) * surf(:,:) )
+      ENDIF
 
       ! Add penetrative solar radiation
@@ -97,6 +112,13 @@
       !
       IF( .NOT. lk_vvl ) THEN
-         z_wn_trd_t = - glob_sum( surf(:,:) * wn(:,:,1) * tsb(:,:,1,jp_tem) )
-         z_wn_trd_s = - glob_sum( surf(:,:) * wn(:,:,1) * tsb(:,:,1,jp_sal) )
+         z2d0=0.0_wp ; z2d1=0.0_wp
+         DO ji=1,jpi
+            DO jj=1,jpj
+              z2d0(ji,jj) = surf(ji,jj) * wn(ji,jj,mikt(ji,jj)) * tsb(ji,jj,mikt(ji,jj),jp_tem)
+              z2d1(ji,jj) = surf(ji,jj) * wn(ji,jj,mikt(ji,jj)) * tsb(ji,jj,mikt(ji,jj),jp_sal)
+            ENDDO
+         ENDDO
+         z_wn_trd_t = - glob_sum( z2d0 ) 
+         z_wn_trd_s = - glob_sum( z2d1 )
       ENDIF
 
@@ -113,7 +135,7 @@
       ! 2 -  Content variations !
       ! ------------------------ !
-      zdiff_v2 = 0.d0
-      zdiff_hc = 0.d0
-      zdiff_sc = 0.d0
+      zdiff_v2 = 0._wp
+      zdiff_hc = 0._wp
+      zdiff_sc = 0._wp
 
       ! volume variation (calculated with ssh)
@@ -122,6 +144,13 @@
       ! heat & salt content variation (associated with ssh)
       IF( .NOT. lk_vvl ) THEN
-         z_ssh_hc = glob_sum( surf(:,:) * ( tsn(:,:,1,jp_tem) * sshn(:,:) - ssh_hc_loc_ini(:,:) ) )
-         z_ssh_sc = glob_sum( surf(:,:) * ( tsn(:,:,1,jp_sal) * sshn(:,:) - ssh_sc_loc_ini(:,:) ) )
+         z2d0 = 0._wp   ;   z2d1 = 0._wp
+         DO ji = 1, jpi
+            DO jj = 1, jpj
+              z2d0(ji,jj) = surf(ji,jj) * ( tsn(ji,jj,mikt(ji,jj),jp_tem) * sshn(ji,jj) - ssh_hc_loc_ini(ji,jj) ) 
+              z2d1(ji,jj) = surf(ji,jj) * ( tsn(ji,jj,mikt(ji,jj),jp_sal) * sshn(ji,jj) - ssh_sc_loc_ini(ji,jj) ) 
+            END DO
+         END DO
+         z_ssh_hc = glob_sum( z2d0 ) 
+         z_ssh_sc = glob_sum( z2d1 ) 
       ENDIF
 
@@ -153,8 +182,15 @@
       ! 3 - Diagnostics writing !
       ! ----------------------- !
-      zvol_tot   = 0.d0                                                   ! total ocean volume
+      zvol_tot = 0._wp                    ! total ocean volume (calculated with scale factors)
       DO jk = 1, jpkm1
          zvol_tot  = zvol_tot + glob_sum( surf(:,:) * tmask(:,:,jk) * fse3t_n(:,:,jk) )
       END DO
+
+!!gm to be added ?
+!      IF( .NOT. lk_vvl ) THEN            ! fixed volume, add the ssh contribution
+!        zvol_tot = zvol_tot + glob_sum( surf(:,:) * sshn(:,:) )
+!      ENDIF
+!!gm end
+
 
       IF( lk_vvl ) THEN
@@ -183,90 +219,10 @@
       IF( lrst_oce )   CALL dia_hsb_rst( kt, 'WRITE' )
 
+      CALL wrk_dealloc( jpi,jpj,   z2d0, z2d1 )
+
       IF( nn_timing == 1 )   CALL timing_stop('dia_hsb')
-!
+      !
    END SUBROUTINE dia_hsb
 
-
-   SUBROUTINE dia_hsb_init
-      !!---------------------------------------------------------------------------
-      !!                  ***  ROUTINE dia_hsb  ***
-      !!     
-      !! ** Purpose: Initialization for the heat salt volume budgets
-      !!	
-      !! ** Method : Compute initial heat content, salt content and volume
-      !!
-      !! ** Action : - Compute initial heat content, salt content and volume
-      !!             - Initialize forcing trends
-      !!             - Compute coefficients for conversion
-      !!---------------------------------------------------------------------------
-      INTEGER            ::   jk       ! dummy loop indice
-      INTEGER            ::   ierror   ! local integer
-      !!
-      NAMELIST/namhsb/ ln_diahsb
-      !
-      INTEGER  ::   ios
-      !!----------------------------------------------------------------------
-
-      IF(lwp) THEN
-         WRITE(numout,*)
-         WRITE(numout,*) 'dia_hsb_init : check the heat and salt budgets'
-         WRITE(numout,*) '~~~~~~~~ '
-      ENDIF
-
-      REWIND( numnam_ref )              ! Namelist namhsb in reference namelist
-      READ  ( numnam_ref, namhsb, IOSTAT = ios, ERR = 901)
-901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namhsb in reference namelist', lwp )
-
-      REWIND( numnam_cfg )              ! Namelist namhsb in configuration namelist
-      READ  ( numnam_cfg, namhsb, IOSTAT = ios, ERR = 902 )
-902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namhsb in configuration namelist', lwp )
-      IF(lwm) WRITE ( numond, namhsb )
-
-      !
-      IF(lwp) THEN                   ! Control print
-         WRITE(numout,*)
-         WRITE(numout,*) 'dia_hsb_init : check the heat and salt budgets'
-         WRITE(numout,*) '~~~~~~~~~~~~'
-         WRITE(numout,*) '   Namelist namhsb : set hsb parameters'
-         WRITE(numout,*) '      Switch for hsb diagnostic (T) or not (F)  ln_diahsb  = ', ln_diahsb
-         WRITE(numout,*)
-      ENDIF
-
-      IF( .NOT. ln_diahsb )   RETURN
-!      IF( .NOT. lk_mpp_rep ) &
-!        CALL ctl_stop (' Your global mpp_sum if performed in single precision - 64 bits -', &
-!             &         ' whereas the global sum to be precise must be done in double precision ',&
-!             &         ' please add key_mpp_rep')
-
-      ! ------------------- !
-      ! 1 - Allocate memory !
-      ! ------------------- !
-      ALLOCATE( hc_loc_ini(jpi,jpj,jpk), sc_loc_ini(jpi,jpj,jpk), &
-         &      e3t_ini(jpi,jpj,jpk), surf(jpi,jpj),  ssh_ini(jpi,jpj), STAT=ierror )
-      IF( ierror > 0 ) THEN
-         CALL ctl_stop( 'dia_hsb: unable to allocate hc_loc_ini' )   ;   RETURN
-      ENDIF
-
-      IF(.NOT. lk_vvl ) ALLOCATE( ssh_hc_loc_ini(jpi,jpj), ssh_sc_loc_ini(jpi,jpj),STAT=ierror )
-      IF( ierror > 0 ) THEN
-         CALL ctl_stop( 'dia_hsb: unable to allocate hc_loc_ini' )   ;   RETURN
-      ENDIF
-
-      ! ----------------------------------------------- !
-      ! 2 - Time independant variables and file opening !
-      ! ----------------------------------------------- !
-      IF(lwp) WRITE(numout,*) "dia_hsb: heat salt volume budgets activated"
-      IF(lwp) WRITE(numout,*) '~~~~~~~'
-      surf(:,:) = e1t(:,:) * e2t(:,:) * tmask(:,:,1) * tmask_i(:,:)      ! masked surface grid cell area
-      surf_tot  = glob_sum( surf(:,:) )                                       ! total ocean surface area
-
-      IF( lk_bdy ) CALL ctl_warn( 'dia_hsb does not take open boundary fluxes into account' )         
-      !
-      ! ---------------------------------- !
-      ! 4 - initial conservation variables !
-      ! ---------------------------------- !
-      CALL dia_hsb_rst( nit000, 'READ' )  !* read or initialize all required files
-      !
-   END SUBROUTINE dia_hsb_init
 
    SUBROUTINE dia_hsb_rst( kt, cdrw )
@@ -281,6 +237,6 @@
      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
      !
-     INTEGER ::   jk   ! 
-     INTEGER ::   id1   ! local integers
+     INTEGER ::   ji, jj, jk   ! dummy loop indices
+     INTEGER ::   id1          ! local integers
      !!----------------------------------------------------------------------
      !
@@ -317,12 +273,16 @@
              sc_loc_ini(:,:,jk) = tsn(:,:,jk,jp_sal) * fse3t_n(:,:,jk)   ! initial salt content
           END DO
-          frc_v = 0.d0                                           ! volume       trend due to forcing
-          frc_t = 0.d0                                           ! heat content   -    -   -    -   
-          frc_s = 0.d0                                           ! salt content   -    -   -    -        
+          frc_v = 0._wp                                           ! volume       trend due to forcing
+          frc_t = 0._wp                                           ! heat content   -    -   -    -   
+          frc_s = 0._wp                                           ! salt content   -    -   -    -        
           IF( .NOT. lk_vvl ) THEN
-             ssh_hc_loc_ini(:,:) = tsn(:,:,1,jp_tem) * sshn(:,:)   ! initial heat content in ssh
-             ssh_sc_loc_ini(:,:) = tsn(:,:,1,jp_sal) * sshn(:,:)   ! initial salt content in ssh
-             frc_wn_t = 0.d0                                       ! initial heat content misfit due to free surface
-             frc_wn_s = 0.d0                                       ! initial salt content misfit due to free surface
+             DO ji=1,jpi
+                DO jj=1,jpj
+                   ssh_hc_loc_ini(ji,jj) = tsn(ji,jj,mikt(ji,jj),jp_tem) * sshn(ji,jj)   ! initial heat content in ssh
+                   ssh_sc_loc_ini(ji,jj) = tsn(ji,jj,mikt(ji,jj),jp_sal) * sshn(ji,jj)   ! initial salt content in ssh
+                ENDDO
+             ENDDO
+             frc_wn_t = 0._wp                                       ! initial heat content misfit due to free surface
+             frc_wn_s = 0._wp                                       ! initial salt content misfit due to free surface
           ENDIF
        ENDIF
@@ -354,4 +314,86 @@
    END SUBROUTINE dia_hsb_rst
 
+
+   SUBROUTINE dia_hsb_init
+      !!---------------------------------------------------------------------------
+      !!                  ***  ROUTINE dia_hsb  ***
+      !!     
+      !! ** Purpose: Initialization for the heat salt volume budgets
+      !!	
+      !! ** Method : Compute initial heat content, salt content and volume
+      !!
+      !! ** Action : - Compute initial heat content, salt content and volume
+      !!             - Initialize forcing trends
+      !!             - Compute coefficients for conversion
+      !!---------------------------------------------------------------------------
+      INTEGER ::   jk       ! dummy loop indice
+      INTEGER ::   ierror   ! local integer
+      INTEGER ::   ios
+      !
+      NAMELIST/namhsb/ ln_diahsb
+      !!----------------------------------------------------------------------
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_hsb_init : check the heat and salt budgets'
+         WRITE(numout,*) '~~~~~~~~ '
+      ENDIF
+
+      REWIND( numnam_ref )              ! Namelist namhsb in reference namelist
+      READ  ( numnam_ref, namhsb, IOSTAT = ios, ERR = 901)
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namhsb in reference namelist', lwp )
+
+      REWIND( numnam_cfg )              ! Namelist namhsb in configuration namelist
+      READ  ( numnam_cfg, namhsb, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namhsb in configuration namelist', lwp )
+      IF(lwm) WRITE ( numond, namhsb )
+
+      !
+      IF(lwp) THEN                   ! Control print
+         WRITE(numout,*)
+         WRITE(numout,*) 'dia_hsb_init : check the heat and salt budgets'
+         WRITE(numout,*) '~~~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namhsb : set hsb parameters'
+         WRITE(numout,*) '      Switch for hsb diagnostic (T) or not (F)  ln_diahsb  = ', ln_diahsb
+         WRITE(numout,*)
+      ENDIF
+
+      IF( .NOT. ln_diahsb )   RETURN
+         !      IF( .NOT. lk_mpp_rep ) &
+         !        CALL ctl_stop (' Your global mpp_sum if performed in single precision - 64 bits -', &
+         !             &         ' whereas the global sum to be precise must be done in double precision ',&
+         !             &         ' please add key_mpp_rep')
+
+      ! ------------------- !
+      ! 1 - Allocate memory !
+      ! ------------------- !
+      ALLOCATE( hc_loc_ini(jpi,jpj,jpk), sc_loc_ini(jpi,jpj,jpk), &
+         &      e3t_ini(jpi,jpj,jpk), surf(jpi,jpj),  ssh_ini(jpi,jpj), STAT=ierror )
+      IF( ierror > 0 ) THEN
+         CALL ctl_stop( 'dia_hsb: unable to allocate hc_loc_ini' )   ;   RETURN
+      ENDIF
+
+      IF(.NOT. lk_vvl ) ALLOCATE( ssh_hc_loc_ini(jpi,jpj), ssh_sc_loc_ini(jpi,jpj),STAT=ierror )
+      IF( ierror > 0 ) THEN
+         CALL ctl_stop( 'dia_hsb: unable to allocate hc_loc_ini' )   ;   RETURN
+      ENDIF
+
+      ! ----------------------------------------------- !
+      ! 2 - Time independant variables and file opening !
+      ! ----------------------------------------------- !
+      IF(lwp) WRITE(numout,*) "dia_hsb: heat salt volume budgets activated"
+      IF(lwp) WRITE(numout,*) '~~~~~~~'
+      surf(:,:) = e1t(:,:) * e2t(:,:) * tmask_i(:,:)      ! masked surface grid cell area
+      surf_tot  = glob_sum( surf(:,:) )                                       ! total ocean surface area
+
+      IF( lk_bdy ) CALL ctl_warn( 'dia_hsb does not take open boundary fluxes into account' )         
+      !
+      ! ---------------------------------- !
+      ! 4 - initial conservation variables !
+      ! ---------------------------------- !
+      CALL dia_hsb_rst( nit000, 'READ' )  !* read or initialize all required files
+      !
+   END SUBROUTINE dia_hsb_init
+
    !!======================================================================
 END MODULE diahsb
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaptr.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaptr.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diaptr.F90	(revision 5075)
@@ -505,5 +505,5 @@
             btmsk(:,:,5) = MAX ( btmsk(:,:,3), btmsk(:,:,4) )          ! Indo-Pacific basin
             WHERE( gphit(:,:) < -30._wp)   ;   btm30(:,:) = 0._wp      ! mask out Southern Ocean
-            ELSE WHERE                     ;   btm30(:,:) = tmask(:,:,1)
+            ELSE WHERE                     ;   btm30(:,:) = ssmask(:,:)
             END WHERE
          ENDIF
@@ -573,6 +573,6 @@
       !!-------------------------------------------------------------------- 
       !
-      CALL wrk_alloc( jpj      , zphi , zfoo )
-      CALL wrk_alloc( jpj , jpk, z_1 )
+      CALL wrk_alloc( jpj       , zphi , zfoo )
+      CALL wrk_alloc( jpj , jpk , z_1  )
 
       ! define time axis
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diawri.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diawri.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DIA/diawri.F90	(revision 5075)
@@ -44,6 +44,4 @@
    USE in_out_manager  ! I/O manager
    USE diadimg         ! dimg direct access file format output
-   USE diaar5, ONLY :   lk_diaar5
-   USE dynadv, ONLY :   ln_dynadv_vec
    USE iom
    USE ioipsl
@@ -89,7 +87,5 @@
       INTEGER, DIMENSION(2) :: ierr
       !!----------------------------------------------------------------------
-      !
       ierr = 0
-      !
       ALLOCATE( ndex_hT(jpi*jpj) , ndex_T(jpi*jpj*jpk) ,     &
          &      ndex_hU(jpi*jpj) , ndex_U(jpi*jpj*jpk) ,     &
@@ -131,5 +127,5 @@
       REAL(wp)                     ::   zztmp, zztmpx, zztmpy   ! 
       !!
-      REAL(wp), POINTER, DIMENSION(:,:)   :: z2d       ! 2D workspace
+      REAL(wp), POINTER, DIMENSION(:,:)   :: z2d      ! 2D workspace
       REAL(wp), POINTER, DIMENSION(:,:,:) :: z3d      ! 3D workspace
       !!----------------------------------------------------------------------
@@ -149,27 +145,75 @@
          z3d(:,:,:) = tsn(:,:,:,jp_tem) * fse3t_n(:,:,:)
          CALL iom_put( "toce" , z3d                        )   ! heat content
-         CALL iom_put( "sst"  , z3d(:,:,1)                 )   ! sea surface heat content
-         z3d(:,:,1) = tsn(:,:,1,jp_tem) * z3d(:,:,1)
-         CALL iom_put( "sst2" , z3d(:,:,1)                 )   ! sea surface content of squared temperature
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               z2d(ji,jj) = tsn(ji,jj,mikt(ji,jj),jp_tem) * fse3t_n(ji,jj,mikt(ji,jj))
+            END DO
+         END DO  
+         CALL iom_put( "sst"  , z2d(:,:)                 )   ! sea surface heat content      
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               z2d(ji,jj) = tsn(ji,jj,mikt(ji,jj),jp_tem)**2 * fse3t_n(ji,jj,mikt(ji,jj))
+            END DO
+         END DO  
+         CALL iom_put( "sst2" , z2d(:,:)      )   ! sea surface content of squared temperature
          z3d(:,:,:) = tsn(:,:,:,jp_sal) * fse3t_n(:,:,:)            
          CALL iom_put( "soce" , z3d                        )   ! salinity content
-         CALL iom_put( "sss"  , z3d(:,:,1)                 )   ! sea surface salinity content
-         z3d(:,:,1) = tsn(:,:,1,jp_sal) * z3d(:,:,1)
-         CALL iom_put( "sss2" , z3d(:,:,1)                 )   ! sea surface content of squared salinity
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               z2d(ji,jj) = tsn(ji,jj,mikt(ji,jj),jp_sal) * fse3t_n(ji,jj,mikt(ji,jj))
+            END DO
+         END DO  
+         CALL iom_put( "sss"  , z2d(:,:)                 )   ! sea surface salinity content
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               z2d(ji,jj) = tsn(ji,jj,mikt(ji,jj),jp_sal)**2 * fse3t_n(ji,jj,mikt(ji,jj))
+            END DO
+         END DO  
+         CALL iom_put( "sss2" , z2d(:,:)                 )   ! sea surface content of squared salinity
       ELSE
-         CALL iom_put( "toce" , tsn(:,:,:,jp_tem)          )   ! temperature
-         CALL iom_put( "sst"  , tsn(:,:,1,jp_tem)          )   ! sea surface temperature
-         CALL iom_put( "sst2" , tsn(:,:,1,jp_tem) * tsn(:,:,1,jp_tem) ) ! square of sea surface temperature
+         CALL iom_put( "toce" , tsn(:,:,:,jp_tem)        )   ! temperature
+         IF ( iom_use("sst") ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = tsn(ji,jj,mikt(ji,jj),jp_tem)
+               END DO
+            END DO
+            CALL iom_put( "sst"  , z2d(:,:)            ) ! sea surface temperature
+         ENDIF
+         IF ( iom_use("sst2") )   CALL iom_put( "sst2" , z2d(:,:) * z2d(:,:) ) ! square of sea surface temperature
          CALL iom_put( "soce" , tsn(:,:,:,jp_sal)          )   ! salinity
-         CALL iom_put( "sss"  , tsn(:,:,1,jp_sal)          )   ! sea surface salinity
-         CALL iom_put( "sss2" , tsn(:,:,1,jp_sal) * tsn(:,:,1,jp_sal) ) ! square of sea surface salinity
+         IF ( iom_use("sss") ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = tsn(ji,jj,mikt(ji,jj),jp_sal)
+               END DO
+            END DO
+            CALL iom_put( "sss"  , z2d(:,:)            ) ! sea surface salinity
+         ENDIF
+         CALL iom_put( "sss2" , z2d(:,:) * z2d(:,:) ) ! square of sea surface salinity
       END IF
       IF( lk_vvl .AND. (.NOT. ln_dynadv_vec) ) THEN
-         CALL iom_put( "uoce" , un(:,:,:) * fse3u_n(:,:,:) )    ! i-transport
-         CALL iom_put( "voce" , vn(:,:,:) * fse3v_n(:,:,:) )    ! j-transport
+         CALL iom_put( "uoce" , umask(:,:,:) * un(:,:,:) * fse3u_n(:,:,:) )    ! i-transport
+         CALL iom_put( "voce" , vmask(:,:,:) * vn(:,:,:) * fse3v_n(:,:,:) )    ! j-transport
       ELSE
-         CALL iom_put( "uoce" , un                         )    ! i-current
-         CALL iom_put( "voce" , vn                         )    ! j-current
-      END IF
+         CALL iom_put( "uoce" , umask(:,:,:) * un(:,:,:)                  )    ! i-current
+         CALL iom_put( "voce" , vmask(:,:,:) * vn(:,:,:)                  )    ! j-current
+         IF ( iom_use("ssu") ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = un(ji,jj,miku(ji,jj))
+               END DO
+            END DO
+            CALL iom_put( "ssu"   , z2d                                    )    ! i-current
+         ENDIF
+         IF ( iom_use("ssv") ) THEN
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  z2d(ji,jj) = vn(ji,jj,mikv(ji,jj))
+               END DO
+            END DO
+            CALL iom_put( "ssv"   , z2d                                    )    ! j-current
+         ENDIF
+      ENDIF
       CALL iom_put(    "avt"  , avt                        )    ! T vert. eddy diff. coef.
       CALL iom_put(    "avm"  , avmu                       )    ! T vert. eddy visc. coef.
@@ -178,50 +222,138 @@
       ENDIF
 
-      DO jj = 2, jpjm1                                    ! sst gradient
-         DO ji = fs_2, fs_jpim1   ! vector opt.
-            zztmp      = tsn(ji,jj,1,jp_tem)
-            zztmpx     = ( tsn(ji+1,jj  ,1,jp_tem) - zztmp ) / e1u(ji,jj) + ( zztmp - tsn(ji-1,jj  ,1,jp_tem) ) / e1u(ji-1,jj  )
-            zztmpy     = ( tsn(ji  ,jj+1,1,jp_tem) - zztmp ) / e2v(ji,jj) + ( zztmp - tsn(ji  ,jj-1,1,jp_tem) ) / e2v(ji  ,jj-1)
-            z2d(ji,jj) = 0.25 * ( zztmpx * zztmpx + zztmpy * zztmpy )   &
-               &              * umask(ji,jj,1) * umask(ji-1,jj,1) * vmask(ji,jj,1) * umask(ji,jj-1,1)
-         END DO
-      END DO
-      CALL lbc_lnk( z2d, 'T', 1. )
-      CALL iom_put( "sstgrad2",  z2d               )    ! square of module of sst gradient
-!CDIR NOVERRCHK
-      z2d(:,:) = SQRT( z2d(:,:) )
-      CALL iom_put( "sstgrad" ,  z2d               )    ! module of sst gradient
-
-      IF( lk_diaar5 ) THEN
+      IF ( iom_use("sstgrad2") .OR. iom_use("sstgrad2") ) THEN
+         DO jj = 2, jpjm1                                    ! sst gradient
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               zztmp      = tsn(ji,jj,1,jp_tem)
+               zztmpx     = ( tsn(ji+1,jj  ,1,jp_tem) - zztmp ) / e1u(ji,jj) + ( zztmp - tsn(ji-1,jj  ,1,jp_tem) ) / e1u(ji-1,jj  )
+               zztmpy     = ( tsn(ji  ,jj+1,1,jp_tem) - zztmp ) / e2v(ji,jj) + ( zztmp - tsn(ji  ,jj-1,1,jp_tem) ) / e2v(ji  ,jj-1)
+               z2d(ji,jj) = 0.25 * ( zztmpx * zztmpx + zztmpy * zztmpy )   &
+                  &              * umask(ji,jj,1) * umask(ji-1,jj,1) * vmask(ji,jj,1) * umask(ji,jj-1,1)
+            END DO
+         END DO
+         CALL lbc_lnk( z2d, 'T', 1. )
+         CALL iom_put( "sstgrad2",  z2d               )    ! square of module of sst gradient
+         !CDIR NOVERRCHK<
+         z2d(:,:) = SQRT( z2d(:,:) )
+         CALL iom_put( "sstgrad" ,  z2d               )    ! module of sst gradient
+      ENDIF
+         
+      ! clem: heat and salt content
+      IF( iom_use("heatc") ) THEN
+         z2d(:,:)  = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z2d(ji,jj) = z2d(ji,jj) + fse3t(ji,jj,jk) * tsn(ji,jj,jk,jp_tem) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( z2d, 'T', 1. )
+         CALL iom_put( "heatc", (rau0 * rcp) * z2d )    ! vertically integrated heat content (J/m2)
+      ENDIF
+
+      IF( iom_use("saltc") ) THEN
+         z2d(:,:)  = 0._wp 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z2d(ji,jj) = z2d(ji,jj) + fse3t(ji,jj,jk) * tsn(ji,jj,jk,jp_sal) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( z2d, 'T', 1. )
+         CALL iom_put( "saltc", rau0 * z2d )   ! vertically integrated salt content (PSU*kg/m2)
+      ENDIF
+      !
+      IF ( iom_use("eken") ) THEN
+         rke(:,:,jk) = 0._wp                               !      kinetic energy 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zztmp   = 1._wp / ( e1e2t(ji,jj) * fse3t(ji,jj,jk) )
+                  zztmpx  = 0.5 * (  un(ji-1,jj,jk) * un(ji-1,jj,jk) * e2u(ji-1,jj) * fse3u(ji-1,jj,jk)    &
+                     &             + un(ji  ,jj,jk) * un(ji  ,jj,jk) * e2u(ji  ,jj) * fse3u(ji  ,jj,jk) )  &
+                     &          *  zztmp 
+                  !
+                  zztmpy  = 0.5 * (  vn(ji,jj-1,jk) * vn(ji,jj-1,jk) * e1v(ji,jj-1) * fse3v(ji,jj-1,jk)    &
+                     &             + vn(ji,jj  ,jk) * vn(ji,jj  ,jk) * e1v(ji,jj  ) * fse3v(ji,jj  ,jk) )  &
+                     &          *  zztmp 
+                  !
+                  rke(ji,jj,jk) = 0.5_wp * ( zztmpx + zztmpy )
+                  !
+               ENDDO
+            ENDDO
+         ENDDO
+         CALL lbc_lnk( rke, 'T', 1. )
+         CALL iom_put( "eken", rke )           
+      ENDIF
+         
+      IF( iom_use("u_masstr") .OR. iom_use("u_heattr") .OR. iom_use("u_salttr") ) THEN
          z3d(:,:,jpk) = 0.e0
          DO jk = 1, jpkm1
-            z3d(:,:,jk) = rau0 * un(:,:,jk) * e2u(:,:) * fse3u(:,:,jk)
+            z3d(:,:,jk) = rau0 * un(:,:,jk) * e2u(:,:) * fse3u(:,:,jk) * umask(:,:,jk)
          END DO
          CALL iom_put( "u_masstr", z3d )                  ! mass transport in i-direction
-         zztmp = 0.5 * rcp
+      ENDIF
+      
+      IF( iom_use("u_heattr") ) THEN
          z2d(:,:) = 0.e0 
          DO jk = 1, jpkm1
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1   ! vector opt.
-                  z2d(ji,jj) = z2d(ji,jj) + z3d(ji,jj,jk) * zztmp * ( tsn(ji,jj,jk,jp_tem) + tsn(ji+1,jj,jk,jp_tem) )
+                  z2d(ji,jj) = z2d(ji,jj) + z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_tem) + tsn(ji+1,jj,jk,jp_tem) )
                END DO
             END DO
          END DO
          CALL lbc_lnk( z2d, 'U', -1. )
-         CALL iom_put( "u_heattr", z2d )                  ! heat transport in i-direction
-         DO jk = 1, jpkm1
-            z3d(:,:,jk) = rau0 * vn(:,:,jk) * e1v(:,:) * fse3v(:,:,jk)
-         END DO
-         CALL iom_put( "v_masstr", z3d )                  ! mass transport in j-direction
+         CALL iom_put( "u_heattr", (0.5 * rcp) * z2d )    ! heat transport in i-direction
+      ENDIF
+
+      IF( iom_use("u_salttr") ) THEN
          z2d(:,:) = 0.e0 
          DO jk = 1, jpkm1
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1   ! vector opt.
-                  z2d(ji,jj) = z2d(ji,jj) + z3d(ji,jj,jk) * zztmp * ( tsn(ji,jj,jk,jp_tem) + tsn(ji,jj+1,jk,jp_tem) )
+                  z2d(ji,jj) = z2d(ji,jj) + z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_sal) + tsn(ji+1,jj,jk,jp_sal) )
                END DO
             END DO
          END DO
+         CALL lbc_lnk( z2d, 'U', -1. )
+         CALL iom_put( "u_salttr", 0.5 * z2d )            ! heat transport in i-direction
+      ENDIF
+
+      
+      IF( iom_use("v_masstr") .OR. iom_use("v_heattr") .OR. iom_use("v_salttr") ) THEN
+         z3d(:,:,jpk) = 0.e0
+         DO jk = 1, jpkm1
+            z3d(:,:,jk) = rau0 * vn(:,:,jk) * e1v(:,:) * fse3v(:,:,jk) * vmask(:,:,jk)
+         END DO
+         CALL iom_put( "v_masstr", z3d )                  ! mass transport in j-direction
+      ENDIF
+      
+      IF( iom_use("v_heattr") ) THEN
+         z2d(:,:) = 0.e0 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z2d(ji,jj) = z2d(ji,jj) + z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_tem) + tsn(ji,jj+1,jk,jp_tem) )
+               END DO
+            END DO
+         END DO
          CALL lbc_lnk( z2d, 'V', -1. )
-         CALL iom_put( "v_heattr", z2d )                  !  heat transport in i-direction
+         CALL iom_put( "v_heattr", (0.5 * rcp) * z2d )    !  heat transport in j-direction
+      ENDIF
+
+      IF( iom_use("v_salttr") ) THEN
+         z2d(:,:) = 0.e0 
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  z2d(ji,jj) = z2d(ji,jj) + z3d(ji,jj,jk) * ( tsn(ji,jj,jk,jp_sal) + tsn(ji,jj+1,jk,jp_sal) )
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( z2d, 'V', -1. )
+         CALL iom_put( "v_salttr", 0.5 * z2d )            !  heat transport in j-direction
       ENDIF
       !
@@ -489,23 +621,22 @@
          ENDIF
 
-#if ! defined key_coupled 
-         CALL histdef( nid_T, "sohefldp", "Surface Heat Flux: Damping"         , "W/m2"   ,   &  ! qrp
-            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-         CALL histdef( nid_T, "sowafldp", "Surface Water Flux: Damping"        , "Kg/m2/s",   &  ! erp
-            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-         CALL histdef( nid_T, "sosafldp", "Surface salt flux: damping"         , "Kg/m2/s",   &  ! erp * sn
-            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-#endif
-
-
-
-#if ( defined key_coupled && ! defined key_lim3 && ! defined key_lim2 ) 
-         CALL histdef( nid_T, "sohefldp", "Surface Heat Flux: Damping"         , "W/m2"   ,   &  ! qrp
-            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-         CALL histdef( nid_T, "sowafldp", "Surface Water Flux: Damping"        , "Kg/m2/s",   &  ! erp
-            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-         CALL histdef( nid_T, "sosafldp", "Surface salt flux: Damping"         , "Kg/m2/s",   &  ! erp * sn
-            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-#endif
+         IF( .NOT. lk_cpl ) THEN
+            CALL histdef( nid_T, "sohefldp", "Surface Heat Flux: Damping"         , "W/m2"   ,   &  ! qrp
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "sowafldp", "Surface Water Flux: Damping"        , "Kg/m2/s",   &  ! erp
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "sosafldp", "Surface salt flux: damping"         , "Kg/m2/s",   &  ! erp * sn
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         ENDIF
+
+         IF( lk_cpl .AND. nn_ice <= 1 ) THEN
+            CALL histdef( nid_T, "sohefldp", "Surface Heat Flux: Damping"         , "W/m2"   ,   &  ! qrp
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "sowafldp", "Surface Water Flux: Damping"        , "Kg/m2/s",   &  ! erp
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T, "sosafldp", "Surface salt flux: Damping"         , "Kg/m2/s",   &  ! erp * sn
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         ENDIF
+         
          clmx ="l_max(only(x))"    ! max index on a period
          CALL histdef( nid_T, "sobowlin", "Bowl Index"                         , "W-point",   &  ! bowl INDEX 
@@ -522,15 +653,10 @@
 #endif
 
-#if defined key_coupled 
-# if defined key_lim3
-         Must be adapted to LIM3
-# endif 
-# if defined key_lim2
-         CALL histdef( nid_T,"soicetem" , "Ice Surface Temperature"            , "K"      ,   &  ! tn_ice
-            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-         CALL histdef( nid_T,"soicealb" , "Ice Albedo"                         , "[0,1]"  ,   &  ! alb_ice
-            &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-# endif 
-#endif 
+         IF( lk_cpl .AND. nn_ice == 2 ) THEN
+            CALL histdef( nid_T,"soicetem" , "Ice Surface Temperature"            , "K"      ,   &  ! tn_ice
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+            CALL histdef( nid_T,"soicealb" , "Ice Albedo"                         , "[0,1]"  ,   &  ! alb_ice
+               &          jpi, jpj, nh_T, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+         ENDIF
 
          CALL histend( nid_T, snc4chunks=snc4set )
@@ -623,5 +749,4 @@
       ENDIF
 
-      ! Write fields on T grid
       IF( lk_vvl ) THEN
          CALL histwrite( nid_T, "votemper", it, tsn(:,:,:,jp_tem) * fse3t_n(:,:,:) , ndim_T , ndex_T  )   ! heat content
@@ -634,5 +759,4 @@
          CALL histwrite( nid_T, "sosstsst", it, tsn(:,:,1,jp_tem) , ndim_hT, ndex_hT )   ! sea surface temperature
          CALL histwrite( nid_T, "sosaline", it, tsn(:,:,1,jp_sal) , ndim_hT, ndex_hT )   ! sea surface salinity
-
       ENDIF
       IF( lk_vvl ) THEN
@@ -684,18 +808,18 @@
       ENDIF
 
-#if ! defined key_coupled
-      CALL histwrite( nid_T, "sohefldp", it, qrp           , ndim_hT, ndex_hT )   ! heat flux damping
-      CALL histwrite( nid_T, "sowafldp", it, erp           , ndim_hT, ndex_hT )   ! freshwater flux damping
-      IF( ln_ssr ) zw2d(:,:) = erp(:,:) * tsn(:,:,1,jp_sal) * tmask(:,:,1)
-      CALL histwrite( nid_T, "sosafldp", it, zw2d          , ndim_hT, ndex_hT )   ! salt flux damping
-#endif
-#if ( defined key_coupled && ! defined key_lim3 && ! defined key_lim2 ) 
-      CALL histwrite( nid_T, "sohefldp", it, qrp           , ndim_hT, ndex_hT )   ! heat flux damping
-      CALL histwrite( nid_T, "sowafldp", it, erp           , ndim_hT, ndex_hT )   ! freshwater flux damping
+      IF( .NOT. lk_cpl ) THEN
+         CALL histwrite( nid_T, "sohefldp", it, qrp           , ndim_hT, ndex_hT )   ! heat flux damping
+         CALL histwrite( nid_T, "sowafldp", it, erp           , ndim_hT, ndex_hT )   ! freshwater flux damping
          IF( ln_ssr ) zw2d(:,:) = erp(:,:) * tsn(:,:,1,jp_sal) * tmask(:,:,1)
-      CALL histwrite( nid_T, "sosafldp", it, zw2d          , ndim_hT, ndex_hT )   ! salt flux damping
-#endif
-      zw2d(:,:) = FLOAT( nmln(:,:) ) * tmask(:,:,1)
-      CALL histwrite( nid_T, "sobowlin", it, zw2d          , ndim_hT, ndex_hT )   ! ???
+         CALL histwrite( nid_T, "sosafldp", it, zw2d          , ndim_hT, ndex_hT )   ! salt flux damping
+      ENDIF
+      IF( lk_cpl .AND. nn_ice <= 1 ) THEN
+         CALL histwrite( nid_T, "sohefldp", it, qrp           , ndim_hT, ndex_hT )   ! heat flux damping
+         CALL histwrite( nid_T, "sowafldp", it, erp           , ndim_hT, ndex_hT )   ! freshwater flux damping
+         IF( ln_ssr ) zw2d(:,:) = erp(:,:) * tsn(:,:,1,jp_sal) * tmask(:,:,1)
+         CALL histwrite( nid_T, "sosafldp", it, zw2d          , ndim_hT, ndex_hT )   ! salt flux damping
+      ENDIF
+!      zw2d(:,:) = FLOAT( nmln(:,:) ) * tmask(:,:,1)
+!      CALL histwrite( nid_T, "sobowlin", it, zw2d          , ndim_hT, ndex_hT )   ! ???
 
 #if defined key_diahth
@@ -706,16 +830,9 @@
 #endif
 
-#if defined key_coupled 
-# if defined key_lim3
-      Must be adapted for LIM3
-      CALL histwrite( nid_T, "soicetem", it, tn_ice        , ndim_hT, ndex_hT )   ! surf. ice temperature
-      CALL histwrite( nid_T, "soicealb", it, alb_ice       , ndim_hT, ndex_hT )   ! ice albedo
-# endif
-# if defined key_lim2
-      CALL histwrite( nid_T, "soicetem", it, tn_ice(:,:,1) , ndim_hT, ndex_hT )   ! surf. ice temperature
-      CALL histwrite( nid_T, "soicealb", it, alb_ice(:,:,1), ndim_hT, ndex_hT )   ! ice albedo
-# endif
-#endif
-         ! Write fields on U grid
+      IF( lk_cpl .AND. nn_ice == 2 ) THEN
+         CALL histwrite( nid_T, "soicetem", it, tn_ice(:,:,1) , ndim_hT, ndex_hT )   ! surf. ice temperature
+         CALL histwrite( nid_T, "soicealb", it, alb_ice(:,:,1), ndim_hT, ndex_hT )   ! ice albedo
+      ENDIF
+
       CALL histwrite( nid_U, "vozocrtx", it, un            , ndim_U , ndex_U )    ! i-current
       IF( ln_traldf_gdia ) THEN
@@ -739,5 +856,4 @@
       CALL histwrite( nid_U, "sozotaux", it, utau          , ndim_hU, ndex_hU )   ! i-wind stress
 
-         ! Write fields on V grid
       CALL histwrite( nid_V, "vomecrty", it, vn            , ndim_V , ndex_V  )   ! j-current
       IF( ln_traldf_gdia ) THEN
@@ -754,5 +870,4 @@
       CALL histwrite( nid_V, "sometauy", it, vtau          , ndim_hV, ndex_hV )   ! j-wind stress
 
-         ! Write fields on W grid
       CALL histwrite( nid_W, "vovecrtz", it, wn             , ndim_T, ndex_T )    ! vert. current
       IF( ln_traldf_gdia ) THEN
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/daymod.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/daymod.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/daymod.F90	(revision 5075)
@@ -124,5 +124,5 @@
       
       ! control print
-      IF(lwp) WRITE(numout,'(a,i6,a,i2,a,i2,a,i6)')' ==============>> 1/2 time step before the start of the run DATE Y/M/D = ',   &
+      IF(lwp) WRITE(numout,'(a,i6,a,i2,a,i2,a,i8,a,i8)')' =======>> 1/2 time step before the start of the run DATE Y/M/D = ',   &
            &                   nyear, '/', nmonth, '/', nday, '  nsec_day:', nsec_day, '  nsec_week:', nsec_week
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dom_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dom_oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dom_oce.F90	(revision 5075)
@@ -153,4 +153,5 @@
    INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   nldit , nldjt    !: first, last indoor index for each i-domain
    INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:) ::   nleit , nlejt    !: first, last indoor index for each j-domain
+   INTEGER, PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: nfiimpp, nfipproc, nfilcit
 
    !!----------------------------------------------------------------------
@@ -175,4 +176,5 @@
    LOGICAL, PUBLIC ::   ln_zps        !: z-coordinate - partial step
    LOGICAL, PUBLIC ::   ln_sco        !: s-coordinate or hybrid z-s coordinate
+   LOGICAL, PUBLIC ::   ln_isfcav     !: presence of ISF 
 
    !! All coordinates
@@ -250,7 +252,12 @@
    INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   mbkt               !: vertical index of the bottom last T- ocean level
    INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   mbku, mbkv         !: vertical index of the bottom last U- and W- ocean level
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   bathy              !: ocean depth (meters)
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   tmask_i            !: interior domain T-point mask
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   bmask              !: land/ocean mask of barotropic stream function
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   bathy                              !: ocean depth (meters)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   tmask_i, umask_i, vmask_i, fmask_i !: interior domain T-point mask
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   bmask                              !: land/ocean mask of barotropic stream function
+
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   misfdep                 !: top first ocean level                (ISF)
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   mikt, miku, mikv, mikf  !: first wet T-, U-, V-, F- ocean level (ISF)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   risfdep                 !: Iceshelf draft                       (ISF)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ssmask                   !: surface domain T-point mask 
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:), TARGET :: tmask, umask, vmask, fmask   !: land/ocean mask at T-, U-, V- and F-pts
@@ -329,5 +336,6 @@
       ierr(:) = 0
       !
-      ALLOCATE( rdttra(jpk), r2dtra(jpk), mig(jpi), mjg(jpj), STAT=ierr(1) )
+      ALLOCATE( rdttra(jpk), r2dtra(jpk), mig(jpi), mjg(jpj), nfiimpp(jpni,jpnj),  &
+         &      nfipproc(jpni,jpnj), nfilcit(jpni,jpnj), STAT=ierr(1) )
          !
       ALLOCATE( nimppt(jpnij) , ibonit(jpnij) , nlcit(jpnij) , nlcjt(jpnij) ,     &
@@ -379,10 +387,16 @@
          &      hift  (jpi,jpj) , hifu  (jpi,jpj) , rx1 (jpi,jpj) , STAT=ierr(8) )
 
-      ALLOCATE( mbathy(jpi,jpj) , bathy(jpi,jpj) ,                     &
-         &     tmask_i(jpi,jpj) , bmask(jpi,jpj) ,                     &
+      ALLOCATE( mbathy(jpi,jpj) , bathy(jpi,jpj) ,                                      &
+         &     tmask_i(jpi,jpj) , umask_i(jpi,jpj), vmask_i(jpi,jpj), fmask_i(jpi,jpj), &
+         &     bmask(jpi,jpj)   ,                                                       &
          &     mbkt   (jpi,jpj) , mbku (jpi,jpj) , mbkv(jpi,jpj) , STAT=ierr(9) )
 
+! (ISF) Allocation of basic array   
+      ALLOCATE( misfdep(jpi,jpj) , risfdep(jpi,jpj),     &
+         &     mikt(jpi,jpj), miku(jpi,jpj), mikv(jpi,jpj) ,           &
+         &     mikf(jpi,jpj), ssmask(jpi,jpj), STAT=ierr(10) )
+
       ALLOCATE( tmask(jpi,jpj,jpk) , umask(jpi,jpj,jpk),     & 
-         &      vmask(jpi,jpj,jpk) , fmask(jpi,jpj,jpk), STAT=ierr(10) )
+         &      vmask(jpi,jpj,jpk) , fmask(jpi,jpj,jpk), STAT=ierr(11) )
 
 #if defined key_noslip_accurate
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domain.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domain.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domain.F90	(revision 5075)
@@ -111,6 +111,6 @@
       END DO
       !                                        ! Inverse of the local depth
-      hur(:,:) = 1._wp / ( hu(:,:) + 1._wp - umask(:,:,1) ) * umask(:,:,1)
-      hvr(:,:) = 1._wp / ( hv(:,:) + 1._wp - vmask(:,:,1) ) * vmask(:,:,1)
+      hur(:,:) = 1._wp / ( hu(:,:) + 1._wp - umask_i(:,:) ) * umask_i(:,:)
+      hvr(:,:) = 1._wp / ( hv(:,:) + 1._wp - vmask_i(:,:) ) * vmask_i(:,:)
 
                              CALL dom_stp      ! time step
@@ -367,24 +367,24 @@
       !
       IF(lk_mpp) THEN
-         CALL mpp_minloc( e1t(:,:), tmask(:,:,1), ze1min, iimi1,ijmi1 )
-         CALL mpp_minloc( e2t(:,:), tmask(:,:,1), ze2min, iimi2,ijmi2 )
-         CALL mpp_maxloc( e1t(:,:), tmask(:,:,1), ze1max, iima1,ijma1 )
-         CALL mpp_maxloc( e2t(:,:), tmask(:,:,1), ze2max, iima2,ijma2 )
+         CALL mpp_minloc( e1t(:,:), tmask_i(:,:), ze1min, iimi1,ijmi1 )
+         CALL mpp_minloc( e2t(:,:), tmask_i(:,:), ze2min, iimi2,ijmi2 )
+         CALL mpp_maxloc( e1t(:,:), tmask_i(:,:), ze1max, iima1,ijma1 )
+         CALL mpp_maxloc( e2t(:,:), tmask_i(:,:), ze2max, iima2,ijma2 )
       ELSE
-         ze1min = MINVAL( e1t(:,:), mask = tmask(:,:,1) == 1._wp )    
-         ze2min = MINVAL( e2t(:,:), mask = tmask(:,:,1) == 1._wp )    
-         ze1max = MAXVAL( e1t(:,:), mask = tmask(:,:,1) == 1._wp )    
-         ze2max = MAXVAL( e2t(:,:), mask = tmask(:,:,1) == 1._wp )    
-
-         iloc  = MINLOC( e1t(:,:), mask = tmask(:,:,1) == 1._wp )
+         ze1min = MINVAL( e1t(:,:), mask = tmask_i(:,:) == 1._wp )    
+         ze2min = MINVAL( e2t(:,:), mask = tmask_i(:,:) == 1._wp )    
+         ze1max = MAXVAL( e1t(:,:), mask = tmask_i(:,:) == 1._wp )    
+         ze2max = MAXVAL( e2t(:,:), mask = tmask_i(:,:) == 1._wp )    
+
+         iloc  = MINLOC( e1t(:,:), mask = tmask_i(:,:) == 1._wp )
          iimi1 = iloc(1) + nimpp - 1
          ijmi1 = iloc(2) + njmpp - 1
-         iloc  = MINLOC( e2t(:,:), mask = tmask(:,:,1) == 1._wp )
+         iloc  = MINLOC( e2t(:,:), mask = tmask_i(:,:) == 1._wp )
          iimi2 = iloc(1) + nimpp - 1
          ijmi2 = iloc(2) + njmpp - 1
-         iloc  = MAXLOC( e1t(:,:), mask = tmask(:,:,1) == 1._wp )
+         iloc  = MAXLOC( e1t(:,:), mask = tmask_i(:,:) == 1._wp )
          iima1 = iloc(1) + nimpp - 1
          ijma1 = iloc(2) + njmpp - 1
-         iloc  = MAXLOC( e2t(:,:), mask = tmask(:,:,1) == 1._wp )
+         iloc  = MAXLOC( e2t(:,:), mask = tmask_i(:,:) == 1._wp )
          iima2 = iloc(1) + nimpp - 1
          ijma2 = iloc(2) + njmpp - 1
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domcfg.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domcfg.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domcfg.F90	(revision 5075)
@@ -82,5 +82,5 @@
       !!----------------------------------------------------------------------
       !                              ! recalculate jpizoom/jpjzoom given lat/lon
-      IF( lk_c1d )  CALL dom_c1d( rn_lat1d, rn_lon1d )
+      IF( lk_c1d .AND. ln_c1d_locpt )  CALL dom_c1d( rn_lat1d, rn_lon1d )
       !
       !                        ! ============== !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domhgr.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domhgr.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domhgr.F90	(revision 5075)
@@ -638,4 +638,31 @@
       CALL iom_close( inum )
       
+! need to be define for the extended grid south of -80S
+! some point are undefined but you need to have e1 and e2 .NE. 0
+      WHERE (e1t==0.0_wp)
+         e1t=1.0e2
+      END WHERE
+      WHERE (e1v==0.0_wp)
+         e1v=1.0e2
+      END WHERE
+      WHERE (e1u==0.0_wp)
+         e1u=1.0e2
+      END WHERE
+      WHERE (e1f==0.0_wp)
+         e1f=1.0e2
+      END WHERE
+      WHERE (e2t==0.0_wp)
+         e2t=1.0e2
+      END WHERE
+      WHERE (e2v==0.0_wp)
+         e2v=1.0e2
+      END WHERE
+      WHERE (e2u==0.0_wp)
+         e2u=1.0e2
+      END WHERE
+      WHERE (e2f==0.0_wp)
+         e2f=1.0e2
+      END WHERE
+       
     END SUBROUTINE hgr_read
     
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dommsk.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dommsk.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dommsk.F90	(revision 5075)
@@ -184,4 +184,17 @@
          END DO  
       END DO  
+      
+      ! (ISF) define barotropic mask and mask the ice shelf point
+      ssmask(:,:)=tmask(:,:,1) ! at this stage ice shelf is not masked
+      
+      DO jk = 1, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF( REAL( misfdep(ji,jj) - jk, wp ) - 0.1_wp >= 0._wp )   THEN
+                  tmask(ji,jj,jk) = 0._wp
+               END IF
+            END DO  
+         END DO  
+      END DO  
 
 !!gm  ????
@@ -207,5 +220,5 @@
       ! Interior domain mask (used for global sum)
       ! --------------------
-      tmask_i(:,:) = tmask(:,:,1)
+      tmask_i(:,:) = ssmask(:,:)            ! (ISH) tmask_i = 1 even on the ice shelf
       iif = jpreci                         ! ???
       iil = nlci - jpreci + 1
@@ -250,12 +263,26 @@
          END DO
       END DO
+      ! (ISF) MIN(1,SUM(umask)) is here to check if you have effectively at least 1 wet u point
+      DO jj = 1, jpjm1
+         DO ji = 1, fs_jpim1   ! vector loop
+            umask_i(ji,jj)  = ssmask(ji,jj) * ssmask(ji+1,jj  )  * MIN(1._wp,SUM(umask(ji,jj,:)))
+            vmask_i(ji,jj)  = ssmask(ji,jj) * ssmask(ji  ,jj+1)  * MIN(1._wp,SUM(vmask(ji,jj,:)))
+         END DO
+         DO ji = 1, jpim1      ! NO vector opt.
+            fmask_i(ji,jj) =  ssmask(ji,jj  ) * ssmask(ji+1,jj  )   &
+               &            * ssmask(ji,jj+1) * ssmask(ji+1,jj+1) * MIN(1._wp,SUM(fmask(ji,jj,:)))
+         END DO
+      END DO
       CALL lbc_lnk( umask, 'U', 1._wp )      ! Lateral boundary conditions
       CALL lbc_lnk( vmask, 'V', 1._wp )
       CALL lbc_lnk( fmask, 'F', 1._wp )
+      CALL lbc_lnk( umask_i, 'U', 1._wp )      ! Lateral boundary conditions
+      CALL lbc_lnk( vmask_i, 'V', 1._wp )
+      CALL lbc_lnk( fmask_i, 'F', 1._wp )
 
 
       ! 4. ocean/land mask for the elliptic equation
       ! --------------------------------------------
-      bmask(:,:) = tmask(:,:,1)       ! elliptic equation is written at t-point
+      bmask(:,:) = ssmask(:,:)       ! elliptic equation is written at t-point
       !
       !                               ! Boundary conditions
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domvvl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domvvl.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domvvl.F90	(revision 5075)
@@ -44,16 +44,16 @@
 
    !!* Namelist nam_vvl
-   LOGICAL , PUBLIC                                      :: ln_vvl_zstar              ! zstar  vertical coordinate
-   LOGICAL , PUBLIC                                      :: ln_vvl_ztilde             ! ztilde vertical coordinate
-   LOGICAL , PUBLIC                                      :: ln_vvl_layer              ! level  vertical coordinate
-   LOGICAL , PUBLIC                                      :: ln_vvl_ztilde_as_zstar    ! ztilde vertical coordinate
-   LOGICAL , PUBLIC                                      :: ln_vvl_zstar_at_eqtor     ! ztilde vertical coordinate
-   LOGICAL , PUBLIC                                      :: ln_vvl_kepe               ! kinetic/potential energy transfer
-   !                                                                                           ! conservation: not used yet
+   LOGICAL , PUBLIC                                      :: ln_vvl_zstar = .FALSE.              ! zstar  vertical coordinate
+   LOGICAL , PUBLIC                                      :: ln_vvl_ztilde = .FALSE.             ! ztilde vertical coordinate
+   LOGICAL , PUBLIC                                      :: ln_vvl_layer = .FALSE.              ! level  vertical coordinate
+   LOGICAL , PUBLIC                                      :: ln_vvl_ztilde_as_zstar = .FALSE.    ! ztilde vertical coordinate
+   LOGICAL , PUBLIC                                      :: ln_vvl_zstar_at_eqtor = .FALSE.     ! ztilde vertical coordinate
+   LOGICAL , PUBLIC                                      :: ln_vvl_kepe = .FALSE.               ! kinetic/potential energy transfer
+   !                                                                                            ! conservation: not used yet
    REAL(wp)                                              :: rn_ahe3                   ! thickness diffusion coefficient
    REAL(wp)                                              :: rn_rst_e3t                ! ztilde to zstar restoration timescale [days]
    REAL(wp)                                              :: rn_lf_cutoff              ! cutoff frequency for low-pass filter  [days]
    REAL(wp)                                              :: rn_zdef_max               ! maximum fractional e3t deformation
-   LOGICAL , PUBLIC                                      :: ln_vvl_dbg                ! debug control prints
+   LOGICAL , PUBLIC                                      :: ln_vvl_dbg = .FALSE.      ! debug control prints
 
    !! * Module variables
@@ -169,10 +169,29 @@
       fsdept_b(:,:,1) = 0.5_wp * fse3w_b(:,:,1)
       fsdepw_b(:,:,1) = 0.0_wp
-      DO jk = 2, jpk
-         fsdept_n(:,:,jk) = fsdept_n(:,:,jk-1) + fse3w_n(:,:,jk)
-         fsdepw_n(:,:,jk) = fsdepw_n(:,:,jk-1) + fse3t_n(:,:,jk-1)
-         fsde3w_n(:,:,jk) = fsdept_n(:,:,jk  ) - sshn   (:,:)
-         fsdept_b(:,:,jk) = fsdept_b(:,:,jk-1) + fse3w_b(:,:,jk)
-         fsdepw_b(:,:,jk) = fsdepw_b(:,:,jk-1) + fse3t_b(:,:,jk-1)
+      DO jj = 1,jpj
+         DO ji = 1,jpi
+            DO jk = 2,mikt(ji,jj)-1
+               fsdept_n(ji,jj,jk) = gdept_0(ji,jj,jk)
+               fsdepw_n(ji,jj,jk) = gdepw_0(ji,jj,jk)
+               fsde3w_n(ji,jj,jk) = gdept_0(ji,jj,jk) - sshn(ji,jj)
+               fsdept_b(ji,jj,jk) = gdept_0(ji,jj,jk)
+               fsdepw_b(ji,jj,jk) = gdepw_0(ji,jj,jk)
+            END DO
+            IF (mikt(ji,jj) .GT. 1) THEN
+               jk = mikt(ji,jj)
+               fsdept_n(ji,jj,jk) = gdepw_0(ji,jj,jk) + 0.5_wp * fse3w_n(ji,jj,jk)
+               fsdepw_n(ji,jj,jk) = gdepw_0(ji,jj,jk)
+               fsde3w_n(ji,jj,jk) = fsdept_n(ji,jj,jk  ) - sshn   (ji,jj)
+               fsdept_b(ji,jj,jk) = gdepw_0(ji,jj,jk) + 0.5_wp * fse3w_b(ji,jj,jk)
+               fsdepw_b(ji,jj,jk) = gdepw_0(ji,jj,jk)
+            END IF
+            DO jk = mikt(ji,jj)+1, jpk
+               fsdept_n(ji,jj,jk) = fsdept_n(ji,jj,jk-1) + fse3w_n(ji,jj,jk)
+               fsdepw_n(ji,jj,jk) = fsdepw_n(ji,jj,jk-1) + fse3t_n(ji,jj,jk-1)
+               fsde3w_n(ji,jj,jk) = fsdept_n(ji,jj,jk  ) - sshn   (ji,jj)
+               fsdept_b(ji,jj,jk) = fsdept_b(ji,jj,jk-1) + fse3w_b(ji,jj,jk)
+               fsdepw_b(ji,jj,jk) = fsdepw_b(ji,jj,jk-1) + fse3t_b(ji,jj,jk-1)
+            END DO
+         END DO
       END DO
 
@@ -185,6 +204,6 @@
          hv_b(:,:) = hv_b(:,:) + fse3v_b(:,:,jk) * vmask(:,:,jk)
       END DO
-      hur_b(:,:) = umask(:,:,1) / ( hu_b(:,:) + 1. - umask(:,:,1) )
-      hvr_b(:,:) = vmask(:,:,1) / ( hv_b(:,:) + 1. - vmask(:,:,1) )
+      hur_b(:,:) = umask_i(:,:) / ( hu_b(:,:) + 1. - umask_i(:,:) )
+      hvr_b(:,:) = vmask_i(:,:) / ( hv_b(:,:) + 1. - vmask_i(:,:) )
 
       ! Restoring frequencies for z_tilde coordinate
@@ -293,5 +312,5 @@
       !                                                ! --------------------------------------------- !
 
-      z_scale(:,:) = ( ssha(:,:) - sshb(:,:) ) * tmask(:,:,1) / ( ht_0(:,:) + sshn(:,:) + 1. - tmask(:,:,1) )
+      z_scale(:,:) = ( ssha(:,:) - sshb(:,:) ) * ssmask(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - ssmask(:,:) )
       DO jk = 1, jpkm1
          ! formally this is the same as fse3t_a = e3t_0*(1+ssha/ht_0)
@@ -313,5 +332,5 @@
             zht  (:,:) = zht  (:,:) + fse3t_n(:,:,jk) * tmask(:,:,jk)
          END DO
-         zhdiv(:,:) = zhdiv(:,:) / ( zht(:,:) + 1. - tmask(:,:,1) )
+         zhdiv(:,:) = zhdiv(:,:) / ( zht(:,:) + 1. - tmask_i(:,:) )
 
          ! 2 - Low frequency baroclinic horizontal divergence  (z-tilde case only)
@@ -338,5 +357,5 @@
          ELSE                         ! layer case
             DO jk = 1, jpkm1
-               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) -   fse3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) )
+               tilde_e3t_a(:,:,jk) = tilde_e3t_a(:,:,jk) -   fse3t_n(:,:,jk) * ( hdivn(:,:,jk) - zhdiv(:,:) ) * tmask(:,:,jk)
             END DO
          END IF
@@ -386,6 +405,6 @@
          ! d - thickness diffusion transport: boundary conditions
          !     (stored for tracer advction and continuity equation)
-         CALL lbc_lnk( un_td , 'U' , -1.)
-         CALL lbc_lnk( vn_td , 'V' , -1.)
+         CALL lbc_lnk( un_td , 'U' , -1._wp)
+         CALL lbc_lnk( vn_td , 'V' , -1._wp)
 
          ! 4 - Time stepping of baroclinic scale factors
@@ -398,5 +417,5 @@
             z2dt = 2.0_wp * rdt
          ENDIF
-         CALL lbc_lnk( tilde_e3t_a(:,:,:), 'T', 1. )
+         CALL lbc_lnk( tilde_e3t_a(:,:,:), 'T', 1._wp )
          tilde_e3t_a(:,:,:) = tilde_e3t_b(:,:,:) + z2dt * tmask(:,:,:) * tilde_e3t_a(:,:,:)
 
@@ -453,5 +472,5 @@
             zht(:,:)  = zht(:,:) + tilde_e3t_a(:,:,jk) * tmask(:,:,jk)
          END DO
-         z_scale(:,:) =  - zht(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - tmask(:,:,1) )
+         z_scale(:,:) =  - zht(:,:) / ( ht_0(:,:) + sshn(:,:) + 1. - ssmask(:,:) )
          DO jk = 1, jpkm1
             dtilde_e3t_a(:,:,jk) = dtilde_e3t_a(:,:,jk) + fse3t_n(:,:,jk) * z_scale(:,:) * tmask(:,:,jk)
@@ -463,5 +482,5 @@
       !                                           ! ---baroclinic part--------- !
          DO jk = 1, jpkm1
-            fse3t_a(:,:,jk) = fse3t_a(:,:,jk) + dtilde_e3t_a(:,:,jk)
+            fse3t_a(:,:,jk) = fse3t_a(:,:,jk) + dtilde_e3t_a(:,:,jk) * tmask(:,:,jk)
          END DO
       ENDIF
@@ -531,6 +550,6 @@
       END DO
       !                                        ! Inverse of the local depth
-      hur_a(:,:) = 1._wp / ( hu_a(:,:) + 1._wp - umask(:,:,1) ) * umask(:,:,1)
-      hvr_a(:,:) = 1._wp / ( hv_a(:,:) + 1._wp - vmask(:,:,1) ) * vmask(:,:,1)
+      hur_a(:,:) = 1._wp / ( hu_a(:,:) + 1._wp - umask_i(:,:) ) * umask_i(:,:)
+      hvr_a(:,:) = 1._wp / ( hv_a(:,:) + 1._wp - vmask_i(:,:) ) * vmask_i(:,:)
 
       CALL wrk_dealloc( jpi, jpj, zht, z_scale, zwu, zwv, zhdiv )
@@ -570,5 +589,5 @@
       !! * Local declarations
       REAL(wp), POINTER, DIMENSION(:,:,:) :: z_e3t_def
-      INTEGER                             :: jk       ! dummy loop indices
+      INTEGER                             :: ji,jj,jk       ! dummy loop indices
       !!----------------------------------------------------------------------
 
@@ -622,8 +641,23 @@
       fsdepw_n(:,:,1) = 0.0_wp
       fsde3w_n(:,:,1) = fsdept_n(:,:,1) - sshn(:,:)
-      DO jk = 2, jpk
-         fsdept_n(:,:,jk) = fsdept_n(:,:,jk-1) + fse3w_n(:,:,jk)
-         fsdepw_n(:,:,jk) = fsdepw_n(:,:,jk-1) + fse3t_n(:,:,jk-1)
-         fsde3w_n(:,:,jk) = fsdept_n(:,:,jk  ) - sshn   (:,:)
+      DO jj = 1,jpj
+         DO ji = 1,jpi
+            DO jk = 2,mikt(ji,jj)-1
+               fsdept_n(ji,jj,jk) = gdept_0(ji,jj,jk)
+               fsdepw_n(ji,jj,jk) = gdepw_0(ji,jj,jk)
+               fsde3w_n(ji,jj,jk) = gdept_0(ji,jj,jk) - sshn(ji,jj)
+            END DO
+            IF (mikt(ji,jj) .GT. 1) THEN
+               jk = mikt(ji,jj)
+               fsdept_n(ji,jj,jk) = gdepw_0(ji,jj,jk) + 0.5_wp * fse3w_n(ji,jj,jk)
+               fsdepw_n(ji,jj,jk) = gdepw_0(ji,jj,jk)
+               fsde3w_n(ji,jj,jk) = fsdept_n(ji,jj,jk  ) - sshn   (ji,jj)
+            END IF
+            DO jk = mikt(ji,jj)+1, jpk
+               fsdept_n(ji,jj,jk) = fsdept_n(ji,jj,jk-1) + fse3w_n(ji,jj,jk)
+               fsdepw_n(ji,jj,jk) = fsdepw_n(ji,jj,jk-1) + fse3t_n(ji,jj,jk-1)
+               fsde3w_n(ji,jj,jk) = fsdept_n(ji,jj,jk  ) - sshn   (ji,jj)
+            END DO
+         END DO
       END DO
       ! Local depth and Inverse of the local depth of the water column at u- and v- points
@@ -702,5 +736,5 @@
          IF( l_is_orca ) CALL dom_vvl_orca_fix( pe3_in, pe3_out, pout )
          ! boundary conditions
-         CALL lbc_lnk( pe3_out(:,:,:), 'U', 1. )
+         CALL lbc_lnk( pe3_out(:,:,:), 'U', 1._wp )
          pe3_out(:,:,:) = pe3_out(:,:,:) + e3u_0(:,:,:)
          !               ! ------------------------------------- !
@@ -720,5 +754,5 @@
          IF( l_is_orca ) CALL dom_vvl_orca_fix( pe3_in, pe3_out, pout )
          ! boundary conditions
-         CALL lbc_lnk( pe3_out(:,:,:), 'V', 1. )
+         CALL lbc_lnk( pe3_out(:,:,:), 'V', 1._wp )
          pe3_out(:,:,:) = pe3_out(:,:,:) + e3v_0(:,:,:)
          !               ! ------------------------------------- !
@@ -738,5 +772,5 @@
          IF( l_is_orca ) CALL dom_vvl_orca_fix( pe3_in, pe3_out, pout )
          ! boundary conditions
-         CALL lbc_lnk( pe3_out(:,:,:), 'F', 1. )
+         CALL lbc_lnk( pe3_out(:,:,:), 'F', 1._wp )
          pe3_out(:,:,:) = pe3_out(:,:,:) + e3f_0(:,:,:)
          !               ! ------------------------------------- !
@@ -808,5 +842,5 @@
             id3 = iom_varid( numror, 'tilde_e3t_b', ldstop = .FALSE. )
             id4 = iom_varid( numror, 'tilde_e3t_n', ldstop = .FALSE. )
-            id5 = iom_varid( numror, 'hdif_lf', ldstop = .FALSE. )
+            id5 = iom_varid( numror, 'hdiv_lf', ldstop = .FALSE. )
             !                             ! --------- !
             !                             ! all cases !
@@ -815,11 +849,25 @@
                CALL iom_get( numror, jpdom_autoglo, 'fse3t_b', fse3t_b(:,:,:) )
                CALL iom_get( numror, jpdom_autoglo, 'fse3t_n', fse3t_n(:,:,:) )
+               ! needed to restart if land processor not computed 
+               IF(lwp) write(numout,*) 'dom_vvl_rst : fse3t_b and fse3t_n found in restart files'
+               WHERE ( tmask(:,:,:) == 0.0_wp ) 
+                  fse3t_n(:,:,:) = e3t_0(:,:,:)
+                  fse3t_b(:,:,:) = e3t_0(:,:,:)
+               END WHERE
                IF( neuler == 0 ) THEN
                   fse3t_b(:,:,:) = fse3t_n(:,:,:)
                ENDIF
             ELSE IF( id1 > 0 ) THEN
+               IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : fse3t_n not found in restart files'
+               IF(lwp) write(numout,*) 'fse3t_n set equal to fse3t_b.'
+               IF(lwp) write(numout,*) 'neuler is forced to 0'
+               CALL iom_get( numror, jpdom_autoglo, 'fse3t_b', fse3t_b(:,:,:) )
+               fse3t_n(:,:,:) = fse3t_b(:,:,:)
+               neuler = 0
+            ELSE IF( id2 > 0 ) THEN
                IF(lwp) write(numout,*) 'dom_vvl_rst WARNING : fse3t_b not found in restart files'
                IF(lwp) write(numout,*) 'fse3t_b set equal to fse3t_n.'
                IF(lwp) write(numout,*) 'neuler is forced to 0'
+               CALL iom_get( numror, jpdom_autoglo, 'fse3t_n', fse3t_n(:,:,:) )
                fse3t_b(:,:,:) = fse3t_n(:,:,:)
                neuler = 0
@@ -830,5 +878,5 @@
                DO jk=1,jpk
                   fse3t_n(:,:,jk) =  e3t_0(:,:,jk) * ( ht_0(:,:) + sshn(:,:) ) &
-                      &                            / ( ht_0(:,:) + 1._wp - tmask(:,:,1) ) * tmask(:,:,jk) &
+                      &                            / ( ht_0(:,:) + 1._wp - ssmask(:,:) ) * tmask(:,:,jk) &
                       &            + e3t_0(:,:,jk) * (1._wp -tmask(:,:,jk))
                END DO
@@ -964,4 +1012,5 @@
 
       IF( ioptio /= 1 )   CALL ctl_stop( 'Choose ONE vertical coordinate in namelist nam_vvl' )
+      IF( .NOT. ln_vvl_zstar .AND. nn_isf .NE. 0) CALL ctl_stop( 'Only vvl_zstar has been tested with ice shelf cavity' )
 
       IF(lwp) THEN                   ! Print the choice
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domwri.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domwri.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domwri.F90	(revision 5075)
@@ -132,14 +132,34 @@
       
       CALL dom_uniq( zprw, 'T' )
-      zprt = tmask(:,:,1) * zprw                               !    ! unique point mask
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            jk=mikt(ji,jj) 
+            zprt(ji,jj) = tmask(ji,jj,jk) * zprw(ji,jj)                        !    ! unique point mask
+         END DO
+      END DO                             !    ! unique point mask
       CALL iom_rstput( 0, 0, inum2, 'tmaskutil', zprt, ktype = jp_i1 )  
       CALL dom_uniq( zprw, 'U' )
-      zprt = umask(:,:,1) * zprw
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            jk=miku(ji,jj) 
+            zprt(ji,jj) = umask(ji,jj,jk) * zprw(ji,jj)                        !    ! unique point mask
+         END DO
+      END DO
       CALL iom_rstput( 0, 0, inum2, 'umaskutil', zprt, ktype = jp_i1 )  
       CALL dom_uniq( zprw, 'V' )
-      zprt = vmask(:,:,1) * zprw
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            jk=mikv(ji,jj) 
+            zprt(ji,jj) = vmask(ji,jj,jk) * zprw(ji,jj)                        !    ! unique point mask
+         END DO
+      END DO
       CALL iom_rstput( 0, 0, inum2, 'vmaskutil', zprt, ktype = jp_i1 )  
       CALL dom_uniq( zprw, 'F' )
-      zprt = fmask(:,:,1) * zprw
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            jk=mikf(ji,jj) 
+            zprt(ji,jj) = fmask(ji,jj,jk) * zprw(ji,jj)                        !    ! unique point mask
+         END DO
+      END DO
       CALL iom_rstput( 0, 0, inum2, 'fmaskutil', zprt, ktype = jp_i1 )  
 
@@ -168,6 +188,10 @@
       
       ! note that mbkt is set to 1 over land ==> use surface tmask
-      zprt(:,:) = tmask(:,:,1) * REAL( mbkt(:,:) , wp )
+      zprt(:,:) = ssmask(:,:) * REAL( mbkt(:,:) , wp )
       CALL iom_rstput( 0, 0, inum4, 'mbathy', zprt, ktype = jp_i2 )     !    ! nb of ocean T-points
+      zprt(:,:) = ssmask(:,:) * REAL( mikt(:,:) , wp )
+      CALL iom_rstput( 0, 0, inum4, 'misf', zprt, ktype = jp_i2 )       !    ! nb of ocean T-points
+      zprt(:,:) = ssmask(:,:) * REAL( risfdep(:,:) , wp )
+      CALL iom_rstput( 0, 0, inum4, 'isfdraft', zprt, ktype = jp_r4 )       !    ! nb of ocean T-points
             
       IF( ln_sco ) THEN                                         ! s-coordinate
@@ -203,6 +227,6 @@
             DO jj = 1,jpj   
                DO ji = 1,jpi
-                  e3tp(ji,jj) = e3t_0(ji,jj,mbkt(ji,jj)) * tmask(ji,jj,1)
-                  e3wp(ji,jj) = e3w_0(ji,jj,mbkt(ji,jj)) * tmask(ji,jj,1)
+                  e3tp(ji,jj) = e3t_0(ji,jj,mbkt(ji,jj)) * ssmask(ji,jj)
+                  e3wp(ji,jj) = e3w_0(ji,jj,mbkt(ji,jj)) * ssmask(ji,jj)
                END DO
             END DO
@@ -228,6 +252,6 @@
             DO jj = 1,jpj   
                DO ji = 1,jpi
-                  zprt(ji,jj) = gdept_0(ji,jj,mbkt(ji,jj)  ) * tmask(ji,jj,1)
-                  zprw(ji,jj) = gdepw_0(ji,jj,mbkt(ji,jj)+1) * tmask(ji,jj,1)
+                  zprt(ji,jj) = gdept_0(ji,jj,mbkt(ji,jj)  ) * ssmask(ji,jj)
+                  zprw(ji,jj) = gdepw_0(ji,jj,mbkt(ji,jj)+1) * ssmask(ji,jj)
                END DO
             END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domzgr.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domzgr.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/domzgr.F90	(revision 5075)
@@ -35,4 +35,5 @@
    USE oce               ! ocean variables
    USE dom_oce           ! ocean domain
+   USE sbc_oce           ! surface variable (isf)
    USE closea            ! closed seas
    USE c1d               ! 1D vertical configuration
@@ -101,5 +102,5 @@
       INTEGER ::   ios
       !
-      NAMELIST/namzgr/ ln_zco, ln_zps, ln_sco
+      NAMELIST/namzgr/ ln_zco, ln_zps, ln_sco, ln_isfcav
       !!----------------------------------------------------------------------
       !
@@ -120,7 +121,8 @@
          WRITE(numout,*) '~~~~~~~'
          WRITE(numout,*) '          Namelist namzgr : set vertical coordinate'
-         WRITE(numout,*) '             z-coordinate - full steps      ln_zco = ', ln_zco
-         WRITE(numout,*) '             z-coordinate - partial steps   ln_zps = ', ln_zps
-         WRITE(numout,*) '             s- or hybrid z-s-coordinate    ln_sco = ', ln_sco
+         WRITE(numout,*) '             z-coordinate - full steps      ln_zco    = ', ln_zco
+         WRITE(numout,*) '             z-coordinate - partial steps   ln_zps    = ', ln_zps
+         WRITE(numout,*) '             s- or hybrid z-s-coordinate    ln_sco    = ', ln_sco
+         WRITE(numout,*) '             ice shelf cavities             ln_isfcav = ', ln_isfcav
       ENDIF
 
@@ -145,4 +147,5 @@
       IF( .NOT.lk_c1d )   CALL zgr_bat_ctl      ! check bathymetry (mbathy) and suppress isolated ocean points
                           CALL zgr_bot_level    ! deepest ocean level for t-, u- and v-points
+                          CALL zgr_top_level    ! shallowest ocean level for T-, U-, V- points
       !
       IF( lk_c1d ) THEN                         ! 1D config.: same mbathy value over the 3x3 domain
@@ -295,4 +298,16 @@
       ENDIF
 
+! need to be like this to compute the pressure gradient with ISF. If not, level beneath the ISF are not aligned (sum(e3t) /= depth)
+! define e3t_0 and e3w_0 as the differences between gdept and gdepw respectively
+      DO jk = 1, jpkm1
+         e3t_1d(jk) = gdepw_1d(jk+1)-gdepw_1d(jk) 
+      END DO
+      e3t_1d(jpk) = e3t_1d(jpk-1)   ! we don't care because this level is masked in NEMO
+
+      DO jk = 2, jpk
+         e3w_1d(jk) = gdept_1d(jk) - gdept_1d(jk-1) 
+      END DO
+      e3w_1d(1  ) = 2._wp * (gdept_1d(1) - gdepw_1d(1)) 
+
 !!gm BUG in s-coordinate this does not work!
       ! deepest/shallowest W level Above/Below ~10m
@@ -350,16 +365,14 @@
       INTEGER  ::   ji, jj, jl, jk            ! dummy loop indices
       INTEGER  ::   inum                      ! temporary logical unit
+      INTEGER  ::   ierror                    ! error flag
       INTEGER  ::   ii_bump, ij_bump, ih      ! bump center position
       INTEGER  ::   ii0, ii1, ij0, ij1, ik    ! local indices
       REAL(wp) ::   r_bump , h_bump , h_oce   ! bump characteristics 
       REAL(wp) ::   zi, zj, zh, zhmin         ! local scalars
-      INTEGER , POINTER, DIMENSION(:,:) ::   idta   ! global domain integer data
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zdta   ! global domain scalar data
+      INTEGER , ALLOCATABLE, DIMENSION(:,:) ::   idta   ! global domain integer data
+      REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   zdta   ! global domain scalar data
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('zgr_bat')
-      !
-      CALL wrk_alloc( jpidta, jpjdta, idta )
-      CALL wrk_alloc( jpidta, jpjdta, zdta )
       !
       IF(lwp) WRITE(numout,*)
@@ -370,4 +383,9 @@
          !                                            ! ================== !
          !                                            ! global domain level and meter bathymetry (idta,zdta)
+         !
+         ALLOCATE( idta(jpidta,jpjdta), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'zgr_bat: unable to allocate idta array' )
+         ALLOCATE( zdta(jpidta,jpjdta), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'zgr_bat: unable to allocate zdta array' )
          !
          IF( ntopo == 0 ) THEN                        ! flat basin
@@ -450,4 +468,30 @@
             END DO
          END DO
+         risfdep(:,:)=0.e0
+         misfdep(:,:)=1
+         !
+         ! (ISF) TODO build ice draft netcdf file for isomip and build the corresponding part of code
+         IF( cp_cfg == "isomip" ) THEN 
+	        ! 
+	        risfdep(:,:)=200.e0 
+	        misfdep(:,:)=1 
+	        ij0 = 1 ; ij1 = 40 
+	        DO jj = mj0(ij0), mj1(ij1) 
+	           risfdep(:,jj)=700.0_wp-(gphit(:,jj)+80.0_wp)*125.0_wp 
+                END DO 
+            WHERE( bathy(:,:) <= 0._wp )  risfdep(:,:) = 0._wp 
+	        ! 
+         ELSEIF ( cp_cfg == "isomip2" ) THEN
+         ! 
+            risfdep(:,:)=0.e0
+            misfdep(:,:)=1
+            ij0 = 1 ; ij1 = 40
+            DO jj = mj0(ij0), mj1(ij1)
+               risfdep(:,jj)=700.0_wp-(gphit(:,jj)+80.0_wp)*125.0_wp
+            END DO
+            WHERE( bathy(:,:) <= 0._wp )  risfdep(:,:) = 0._wp
+         END IF
+         !
+         DEALLOCATE( idta, zdta )
          !
          !                                            ! ================ !
@@ -492,5 +536,14 @@
             CALL iom_get  ( inum, jpdom_data, 'Bathymetry', bathy )
             CALL iom_close( inum )
-            !                                                
+            !  
+            risfdep(:,:)=0._wp         
+            misfdep(:,:)=1             
+            IF ( ln_isfcav ) THEN
+               CALL iom_open ( 'isf_draft_meter.nc', inum ) 
+               CALL iom_get  ( inum, jpdom_data, 'isf_draft', risfdep )
+               CALL iom_close( inum )
+               WHERE( bathy(:,:) <= 0._wp )  risfdep(:,:) = 0._wp
+            END IF
+            !       
             IF( cp_cfg == "orca" .AND. jp_cfg == 2 ) THEN    ! ORCA R2 configuration
                !
@@ -530,4 +583,9 @@
       !                       
       IF ( .not. ln_sco ) THEN                                !==  set a minimum depth  ==!
+         ! patch to avoid case bathy = ice shelf draft and bathy between 0 and zhmin
+         WHERE (bathy == risfdep)
+            bathy   = 0.0_wp ; risfdep = 0.0_wp
+         END WHERE
+         ! end patch
          IF( rn_hmin < 0._wp ) THEN    ;   ik = - INT( rn_hmin )                                      ! from a nb of level
          ELSE                          ;   ik = MINLOC( gdepw_1d, mask = gdepw_1d > rn_hmin, dim = 1 )  ! from a depth
@@ -539,7 +597,4 @@
          IF(lwp) write(numout,*) 'Minimum ocean depth: ', zhmin, ' minimum number of ocean levels : ', ik
       ENDIF
-      !
-      CALL wrk_dealloc( jpidta, jpjdta, idta )
-      CALL wrk_dealloc( jpidta, jpjdta, zdta )
       !
       IF( nn_timing == 1 )  CALL timing_stop('zgr_bat')
@@ -783,4 +838,49 @@
    END SUBROUTINE zgr_bot_level
 
+      SUBROUTINE zgr_top_level
+      !!----------------------------------------------------------------------
+      !!                    ***  ROUTINE zgr_bot_level  ***
+      !!
+      !! ** Purpose :   defines the vertical index of ocean top (mik. arrays)
+      !!
+      !! ** Method  :   computes from misfdep with a minimum value of 1
+      !!
+      !! ** Action  :   mikt, miku, mikv :   vertical indices of the shallowest 
+      !!                                     ocean level at t-, u- & v-points
+      !!                                     (min value = 1)
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER ::   ji, jj   ! dummy loop indices
+      REAL(wp), POINTER, DIMENSION(:,:) ::  zmik
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )  CALL timing_start('zgr_top_level')
+      !
+      CALL wrk_alloc( jpi, jpj, zmik )
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '    zgr_top_level : ocean top k-index of T-, U-, V- and W-levels '
+      IF(lwp) WRITE(numout,*) '    ~~~~~~~~~~~~~'
+      !
+      mikt(:,:) = MAX( misfdep(:,:) , 1 )    ! top k-index of T-level (=1)
+      !                                      ! top k-index of W-level (=mikt)
+      DO jj = 1, jpjm1                       ! top k-index of U- (U-) level
+         DO ji = 1, jpim1
+            miku(ji,jj) = MAX(  mikt(ji+1,jj  ) , mikt(ji,jj)  )
+            mikv(ji,jj) = MAX(  mikt(ji  ,jj+1) , mikt(ji,jj)  )
+            mikf(ji,jj) = MAX(  mikt(ji  ,jj+1) , mikt(ji,jj), mikt(ji+1,jj  ), mikt(ji+1,jj+1)  )
+         END DO
+      END DO
+
+      ! converte into REAL to use lbc_lnk ; impose a min value of 1 as a zero can be set in lbclnk 
+      zmik(:,:) = REAL( miku(:,:), wp )   ;   CALL lbc_lnk(zmik,'U',1.)   ;   miku  (:,:) = MAX( INT( zmik(:,:) ), 1 )
+      zmik(:,:) = REAL( mikv(:,:), wp )   ;   CALL lbc_lnk(zmik,'V',1.)   ;   mikv  (:,:) = MAX( INT( zmik(:,:) ), 1 )
+      zmik(:,:) = REAL( mikf(:,:), wp )   ;   CALL lbc_lnk(zmik,'F',1.)   ;   mikf  (:,:) = MAX( INT( zmik(:,:) ), 1 )
+      !
+      CALL wrk_dealloc( jpi, jpj, zmik )
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('zgr_top_level')
+      !
+   END SUBROUTINE zgr_top_level
 
    SUBROUTINE zgr_zco
@@ -861,12 +961,17 @@
       !!----------------------------------------------------------------------
       !!
-      INTEGER  ::   ji, jj, jk       ! dummy loop indices
+      INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
       INTEGER  ::   ik, it           ! temporary integers
+      INTEGER  ::   id, jd, nprocd
+      INTEGER  ::   icompt, ibtest, ibtestim1, ibtestip1, ibtestjm1, ibtestjp1   ! (ISF)
       LOGICAL  ::   ll_print         ! Allow  control print for debugging
       REAL(wp) ::   ze3tp , ze3wp    ! Last ocean level thickness at T- and W-points
       REAL(wp) ::   zdepwp, zdepth   ! Ajusted ocean depth to avoid too small e3t
-      REAL(wp) ::   zmax             ! Maximum depth
+      REAL(wp) ::   zmax, zmin       ! Maximum and minimum depth
       REAL(wp) ::   zdiff            ! temporary scalar
       REAL(wp) ::   zrefdep          ! temporary scalar
+      REAL(wp) ::   zbathydiff, zrisfdepdiff 
+      REAL(wp), POINTER, DIMENSION(:,:)   ::   zrisfdep, zbathy, zmask   ! 3D workspace (ISH)
+      INTEGER , POINTER, DIMENSION(:,:)   ::   zmbathy, zmisfdep   ! 3D workspace (ISH)
       REAL(wp), POINTER, DIMENSION(:,:,:) ::  zprt
       !!---------------------------------------------------------------------
@@ -875,4 +980,6 @@
       !
       CALL wrk_alloc( jpi, jpj, jpk, zprt )
+      CALL wrk_alloc( jpi, jpj, zbathy, zmask, zrisfdep)
+      CALL wrk_alloc( jpi, jpj, zmbathy, zmisfdep)
       !
       IF(lwp) WRITE(numout,*)
@@ -889,5 +996,4 @@
       ENDIF
 
-
       ! bathymetry in level (from bathy_meter)
       ! ===================
@@ -906,4 +1012,466 @@
          WHERE( 0._wp < bathy(:,:) .AND. bathy(:,:) <= zdepth )   mbathy(:,:) = jk-1
       END DO
+      ! (ISF) compute misfdep
+      WHERE( risfdep(:,:) == 0._wp .AND. bathy(:,:) .NE. 0) ;   misfdep(:,:) = 1   ! open water : set misfdep to 1  
+      ELSEWHERE                      ;                          misfdep(:,:) = 2   ! iceshelf : initialize misfdep to second level 
+      END WHERE  
+
+      ! Compute misfdep for ocean points (i.e. first wet level) 
+      ! find the first ocean level such that the first level thickness 
+      ! is larger than the bot_level of e3zps_min and e3zps_rat * e3t_0 (where 
+      ! e3t_0 is the reference level thickness 
+      DO jk = 2, jpkm1 
+         zdepth = gdepw_1d(jk+1) - MIN( e3zps_min, e3t_1d(jk)*e3zps_rat ) 
+         WHERE( 0._wp < risfdep(:,:) .AND. risfdep(:,:) >= zdepth )   misfdep(:,:) = jk+1 
+      END DO 
+      WHERE (risfdep(:,:) <= e3t_1d(1) .AND. risfdep(:,:) .GT. 0._wp)
+         risfdep(:,:) = 0. ; misfdep(:,:) = 1
+      END WHERE
+ 
+! basic check for the compatibility of bathy and risfdep. I think it should be offline because it is not perfect and cannot solved all the situation
+      icompt = 0 
+! run the bathy check 10 times to be sure all the modif in the bathy or iceshelf draft are compatible together
+      DO jl = 1, 10     
+         WHERE (bathy(:,:) .EQ. risfdep(:,:) )
+            misfdep(:,:) = 0 ; risfdep(:,:) = 0._wp
+            mbathy (:,:) = 0 ; bathy  (:,:) = 0._wp
+         END WHERE
+         WHERE (mbathy(:,:) <= 0) 
+            misfdep(:,:) = 0; risfdep(:,:) = 0._wp 
+            mbathy (:,:) = 0; bathy  (:,:) = 0._wp
+         ENDWHERE
+         IF( lk_mpp ) THEN
+            zbathy(:,:) = FLOAT( misfdep(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            misfdep(:,:) = INT( zbathy(:,:) )
+            CALL lbc_lnk( risfdep, 'T', 1. )
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF
+         IF( nperio == 1 .OR. nperio  ==  4 .OR. nperio  ==  6 ) THEN 
+            misfdep( 1 ,:) = misfdep(jpim1,:)           ! local domain is cyclic east-west 
+            misfdep(jpi,:) = misfdep(  2  ,:) 
+         ENDIF
+ 
+         IF( nperio == 1 .OR. nperio  ==  4 .OR. nperio  ==  6 ) THEN
+            mbathy( 1 ,:) = mbathy(jpim1,:)             ! local domain is cyclic east-west
+            mbathy(jpi,:) = mbathy(  2  ,:)
+         ENDIF
+ 
+         ! split last cell if possible (only where water column is 2 cell or less)
+         DO jk = jpkm1, 1, -1
+            zmax = gdepw_1d(jk) + MIN( e3zps_min, e3t_1d(jk)*e3zps_rat )
+            WHERE( gdepw_1d(jk) < bathy(:,:) .AND. bathy(:,:) <= zmax .AND. misfdep + 1 >= mbathy)
+               mbathy(:,:) = jk
+               bathy(:,:)  = zmax
+            END WHERE
+         END DO
+ 
+         ! split top cell if possible (only where water column is 2 cell or less)
+         DO jk = 2, jpkm1
+            zmax = gdepw_1d(jk+1) - MIN( e3zps_min, e3t_1d(jk)*e3zps_rat )
+            WHERE( gdepw_1d(jk+1) > risfdep(:,:) .AND. risfdep(:,:) >= zmax .AND. misfdep + 1 >= mbathy)
+               misfdep(:,:) = jk
+               risfdep(:,:) = zmax
+            END WHERE
+         END DO
+ 
+ 
+ ! Case where bathy and risfdep compatible but not the level variable mbathy/misfdep because of partial cell condition
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! find the minimum change option:
+               ! test bathy
+               IF (risfdep(ji,jj) .GT. 1) THEN
+               zbathydiff =ABS(bathy(ji,jj)   - (gdepw_1d(mbathy (ji,jj)+1) &
+                 &   + MIN( e3zps_min, e3t_1d(mbathy (ji,jj)+1)*e3zps_rat )))
+               zrisfdepdiff=ABS(risfdep(ji,jj) - (gdepw_1d(misfdep(ji,jj)  ) &
+                 &   - MIN( e3zps_min, e3t_1d(misfdep(ji,jj)-1)*e3zps_rat )))
+ 
+                  IF (bathy(ji,jj) .GT. risfdep(ji,jj) .AND. mbathy(ji,jj) .LT. misfdep(ji,jj)) THEN
+                     IF (zbathydiff .LE. zrisfdepdiff) THEN
+                        bathy(ji,jj) = gdepw_1d(mbathy(ji,jj)) + MIN( e3zps_min, e3t_1d(mbathy(ji,jj)+1)*e3zps_rat )
+                        mbathy(ji,jj)= mbathy(ji,jj) + 1
+                     ELSE
+                        risfdep(ji,jj) = gdepw_1d(misfdep(ji,jj)) - MIN( e3zps_min, e3t_1d(misfdep(ji,jj)-1)*e3zps_rat )
+                        misfdep(ji,jj) = misfdep(ji,jj) - 1
+                     END IF
+                  END IF
+               END IF
+            END DO
+         END DO
+ 
+          ! At least 2 levels for water thickness at T, U, and V point.
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ! find the minimum change option:
+               ! test bathy
+               IF( misfdep(ji,jj) == mbathy(ji,jj) .AND. mbathy(ji,jj) .GT. 1) THEN
+                  zbathydiff  =ABS(bathy(ji,jj)  - (gdepw_1d(mbathy (ji,jj)+1)&
+                    & + MIN( e3zps_min,e3t_1d(mbathy (ji,jj)+1)*e3zps_rat )))
+                  zrisfdepdiff=ABS(risfdep(ji,jj) - (gdepw_1d(misfdep(ji,jj)  )  &
+                    & - MIN( e3zps_min,e3t_1d(misfdep(ji,jj)-1)*e3zps_rat )))
+                  IF (zbathydiff .LE. zrisfdepdiff) THEN
+                     mbathy(ji,jj) = mbathy(ji,jj) + 1
+                     bathy(ji,jj)  = gdepw_1d(mbathy (ji,jj)) + MIN( e3zps_min, e3t_1d(mbathy(ji,jj) +1)*e3zps_rat )
+                  ELSE
+                     misfdep(ji,jj)= misfdep(ji,jj) - 1
+                     risfdep(ji,jj) = gdepw_1d(misfdep(ji,jj)+1) - MIN( e3zps_min, e3t_1d(misfdep(ji,jj))*e3zps_rat )
+                  END IF
+               ENDIF
+            END DO
+         END DO
+ 
+ ! point V mbathy(ji,jj) EQ misfdep(ji,jj+1) 
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               IF( misfdep(ji,jj+1) == mbathy(ji,jj) .AND. mbathy(ji,jj) .GT. 1) THEN
+                  zbathydiff =ABS(bathy(ji,jj    ) - (gdepw_1d(mbathy (ji,jj)+1)   &
+                    &   + MIN( e3zps_min, e3t_1d(mbathy (ji,jj  )+1)*e3zps_rat )))
+                  zrisfdepdiff=ABS(risfdep(ji,jj+1) - (gdepw_1d(misfdep(ji,jj+1))  &
+                    &  - MIN( e3zps_min, e3t_1d(misfdep(ji,jj+1)-1)*e3zps_rat )))
+                  IF (zbathydiff .LE. zrisfdepdiff) THEN
+                     mbathy(ji,jj) = mbathy(ji,jj) + 1
+                     bathy(ji,jj)  = gdepw_1d(mbathy (ji,jj  )) &
+                   &    + MIN( e3zps_min, e3t_1d(mbathy(ji,jj   )+1)*e3zps_rat )
+                  ELSE
+                     misfdep(ji,jj+1)  = misfdep(ji,jj+1) - 1
+                     risfdep (ji,jj+1) = gdepw_1d(misfdep(ji,jj+1)+1) &
+                   &   - MIN( e3zps_min, e3t_1d(misfdep(ji,jj+1))*e3zps_rat )
+                  END IF
+               ENDIF
+            END DO
+         END DO
+ 
+         IF( lk_mpp ) THEN
+            zbathy(:,:) = FLOAT( misfdep(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            misfdep(:,:) = INT( zbathy(:,:) )
+            CALL lbc_lnk( risfdep, 'T', 1. )
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF
+ ! point V misdep(ji,jj) EQ mbathy(ji,jj+1) 
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               IF( misfdep(ji,jj) == mbathy(ji,jj+1) .AND. mbathy(ji,jj) .GT. 1) THEN
+                  zbathydiff =ABS(  bathy(ji,jj+1) - (gdepw_1d(mbathy (ji,jj+1)+1) &
+                   &   + MIN( e3zps_min, e3t_1d(mbathy (ji,jj+1)+1)*e3zps_rat )))
+                  zrisfdepdiff=ABS(risfdep(ji,jj  ) - (gdepw_1d(misfdep(ji,jj  )  )  &
+                   &   - MIN( e3zps_min, e3t_1d(misfdep(ji,jj  )-1)*e3zps_rat )))
+                  IF (zbathydiff .LE. zrisfdepdiff) THEN
+                     mbathy (ji,jj+1) = mbathy(ji,jj+1) + 1
+                     bathy  (ji,jj+1) = gdepw_1d(mbathy (ji,jj+1)  ) + MIN( e3zps_min, e3t_1d(mbathy (ji,jj+1)+1)*e3zps_rat )
+                  ELSE
+                     misfdep(ji,jj)   = misfdep(ji,jj) - 1
+                     risfdep(ji,jj)   = gdepw_1d(misfdep(ji,jj  )+1) - MIN( e3zps_min, e3t_1d(misfdep(ji,jj  )  )*e3zps_rat )
+                  END IF
+               ENDIF
+            END DO
+         END DO
+ 
+ 
+         IF( lk_mpp ) THEN 
+            zbathy(:,:) = FLOAT( misfdep(:,:) ) 
+            CALL lbc_lnk( zbathy, 'T', 1. ) 
+            misfdep(:,:) = INT( zbathy(:,:) ) 
+            CALL lbc_lnk( risfdep, 'T', 1. ) 
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF 
+ 
+ ! point U mbathy(ji,jj) EQ misfdep(ji,jj+1) 
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               IF( misfdep(ji+1,jj) == mbathy(ji,jj) .AND. mbathy(ji,jj) .GT. 1) THEN
+                  zbathydiff =ABS(  bathy(ji  ,jj) - (gdepw_1d(mbathy (ji,jj)+1) &
+                    &   + MIN( e3zps_min, e3t_1d(mbathy (ji  ,jj)+1)*e3zps_rat )))
+                  zrisfdepdiff=ABS(risfdep(ji+1,jj) - (gdepw_1d(misfdep(ji+1,jj)) &
+                    &  - MIN( e3zps_min, e3t_1d(misfdep(ji+1,jj)-1)*e3zps_rat )))
+                  IF (zbathydiff .LE. zrisfdepdiff) THEN
+                     mbathy(ji,jj) = mbathy(ji,jj) + 1
+                     bathy(ji,jj)  = gdepw_1d(mbathy (ji,jj)) + MIN( e3zps_min, e3t_1d(mbathy(ji,jj) +1)*e3zps_rat )
+                  ELSE
+                     misfdep(ji+1,jj)= misfdep(ji+1,jj) - 1
+                     risfdep(ji+1,jj) = gdepw_1d(misfdep(ji+1,jj)+1) - MIN( e3zps_min, e3t_1d(misfdep(ji+1,jj))*e3zps_rat )
+                  END IF
+               ENDIF
+            ENDDO
+         ENDDO
+ 
+         IF( lk_mpp ) THEN 
+            zbathy(:,:) = FLOAT( misfdep(:,:) ) 
+            CALL lbc_lnk( zbathy, 'T', 1. ) 
+            misfdep(:,:) = INT( zbathy(:,:) ) 
+            CALL lbc_lnk( risfdep, 'T', 1. ) 
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF 
+ 
+ ! point U misfdep(ji,jj) EQ bathy(ji,jj+1) 
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               IF( misfdep(ji,jj) == mbathy(ji+1,jj) .AND. mbathy(ji,jj) .GT. 1) THEN
+                  zbathydiff =ABS(  bathy(ji+1,jj) - (gdepw_1d(mbathy (ji+1,jj)+1) &
+                      &   + MIN( e3zps_min, e3t_1d(mbathy (ji+1,jj)+1)*e3zps_rat )))
+                  zrisfdepdiff=ABS(risfdep(ji  ,jj) - (gdepw_1d(misfdep(ji  ,jj)  )  &
+                      &  - MIN( e3zps_min, e3t_1d(misfdep(ji  ,jj)-1)*e3zps_rat )))
+                  IF (zbathydiff .LE. zrisfdepdiff) THEN
+                     mbathy(ji+1,jj)  = mbathy (ji+1,jj) + 1
+                     bathy (ji+1,jj)  = gdepw_1d(mbathy (ji+1,jj)  )  &
+                      &   + MIN( e3zps_min, e3t_1d(mbathy (ji+1,jj) +1)*e3zps_rat )
+                  ELSE
+                     misfdep(ji,jj)   = misfdep(ji  ,jj) - 1
+                     risfdep(ji,jj)   = gdepw_1d(misfdep(ji  ,jj)+1) &
+                      &   - MIN( e3zps_min, e3t_1d(misfdep(ji  ,jj)   )*e3zps_rat )
+                  END IF
+               ENDIF
+            ENDDO
+         ENDDO
+ 
+         IF( lk_mpp ) THEN
+            zbathy(:,:) = FLOAT( misfdep(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            misfdep(:,:) = INT( zbathy(:,:) )
+            CALL lbc_lnk( risfdep, 'T', 1. )
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF
+      END DO
+      ! end dig bathy/ice shelf to be compatible
+      ! now fill single point in "coastline" of ice shelf, bathy, hole, and test again one cell tickness
+      DO jl = 1,20
+ 
+ ! remove single point "bay" on isf coast line in the ice shelf draft'
+         DO jk = 1, jpk
+            WHERE (misfdep==0) misfdep=jpk
+            zmask=0
+            WHERE (misfdep .LE. jk) zmask=1
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  IF (misfdep(ji,jj) .EQ. jk) THEN
+                     ibtest = zmask(ji-1,jj) + zmask(ji+1,jj) + zmask(ji,jj-1) + zmask(ji,jj+1)
+                     IF (ibtest .LE. 1) THEN
+                        risfdep(ji,jj)=gdepw_1d(jk+1) ; misfdep(ji,jj)=jk+1
+                        IF (misfdep(ji,jj) .GT. mbathy(ji,jj)) misfdep(ji,jj) = jpk
+                     END IF
+                  END IF
+               END DO
+            END DO
+         END DO
+         WHERE (misfdep==jpk)
+             misfdep=0 ; risfdep=0. ; mbathy=0 ; bathy=0.
+         END WHERE
+         IF( lk_mpp ) THEN
+            zbathy(:,:) = FLOAT( misfdep(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            misfdep(:,:) = INT( zbathy(:,:) )
+            CALL lbc_lnk( risfdep, 'T', 1. )
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF
+ 
+ ! remove single point "bay" on bathy coast line beneath an ice shelf'
+         DO jk = jpk,1,-1
+            zmask=0
+            WHERE (mbathy .GE. jk ) zmask=1
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  IF (mbathy(ji,jj) .EQ. jk .AND. misfdep(ji,jj) .GE. 2) THEN
+                     ibtest = zmask(ji-1,jj) + zmask(ji+1,jj) + zmask(ji,jj-1) + zmask(ji,jj+1)
+                     IF (ibtest .LE. 1) THEN
+                        bathy(ji,jj)=gdepw_1d(jk) ; mbathy(ji,jj)=jk-1
+                        IF (misfdep(ji,jj) .GT. mbathy(ji,jj)) mbathy(ji,jj) = 0
+                     END IF
+                  END IF
+               END DO
+            END DO
+         END DO
+         WHERE (mbathy==0)
+             misfdep=0 ; risfdep=0. ; mbathy=0 ; bathy=0.
+         END WHERE
+         IF( lk_mpp ) THEN
+            zbathy(:,:) = FLOAT( misfdep(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            misfdep(:,:) = INT( zbathy(:,:) )
+            CALL lbc_lnk( risfdep, 'T', 1. )
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF
+ 
+ ! fill hole in ice shelf
+         zmisfdep = misfdep
+         zrisfdep = risfdep
+         WHERE (zmisfdep .LE. 1) zmisfdep=jpk
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               ibtestim1 = zmisfdep(ji-1,jj  ) ; ibtestip1 = zmisfdep(ji+1,jj  )
+               ibtestjm1 = zmisfdep(ji  ,jj-1) ; ibtestjp1 = zmisfdep(ji  ,jj+1)
+               IF( zmisfdep(ji,jj) .GE. mbathy(ji-1,jj  ) ) ibtestim1 = jpk!MAX(0, mbathy(ji-1,jj  ) - 1)
+               IF( zmisfdep(ji,jj) .GE. mbathy(ji+1,jj  ) ) ibtestip1 = jpk!MAX(0, mbathy(ji+1,jj  ) - 1)
+               IF( zmisfdep(ji,jj) .GE. mbathy(ji  ,jj-1) ) ibtestjm1 = jpk!MAX(0, mbathy(ji  ,jj-1) - 1)
+               IF( zmisfdep(ji,jj) .GE. mbathy(ji  ,jj+1) ) ibtestjp1 = jpk!MAX(0, mbathy(ji  ,jj+1) - 1)
+               ibtest=MIN(ibtestim1, ibtestip1, ibtestjm1, ibtestjp1)
+               IF( ibtest == jpk .AND. misfdep(ji,jj) .GE. 2) THEN
+                  mbathy(ji,jj) = 0 ; bathy(ji,jj) = 0.0_wp ; misfdep(ji,jj) = 0 ; risfdep(ji,jj) = 0.0_wp
+               END IF
+               IF( zmisfdep(ji,jj) < ibtest .AND. misfdep(ji,jj) .GE. 2) THEN
+                  misfdep(ji,jj) = ibtest
+                  risfdep(ji,jj) = gdepw_1d(ibtest)
+               ENDIF
+            ENDDO
+         ENDDO
+ 
+         IF( lk_mpp ) THEN 
+            zbathy(:,:) = FLOAT( misfdep(:,:) ) 
+            CALL lbc_lnk( zbathy, 'T', 1. ) 
+            misfdep(:,:) = INT( zbathy(:,:) ) 
+            CALL lbc_lnk( risfdep, 'T', 1. ) 
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF 
+ !
+ !! fill hole in bathymetry
+         zmbathy (:,:)=mbathy (:,:)
+         DO jj = 2, jpjm1
+            DO ji = 2, jpim1
+               ibtestim1 = zmbathy(ji-1,jj  ) ; ibtestip1 = zmbathy(ji+1,jj  )
+               ibtestjm1 = zmbathy(ji  ,jj-1) ; ibtestjp1 = zmbathy(ji  ,jj+1)
+               IF( zmbathy(ji,jj) .LT. misfdep(ji-1,jj  ) ) ibtestim1 = 0!MIN(jpk-1, misfdep(ji-1,jj  ) + 1)
+               IF( zmbathy(ji,jj) .LT. misfdep(ji+1,jj  ) ) ibtestip1 = 0
+               IF( zmbathy(ji,jj) .LT. misfdep(ji  ,jj-1) ) ibtestjm1 = 0
+               IF( zmbathy(ji,jj) .LT. misfdep(ji  ,jj+1) ) ibtestjp1 = 0
+               ibtest=MAX(ibtestim1, ibtestip1, ibtestjm1, ibtestjp1)
+               IF( ibtest == 0 ) THEN
+                  mbathy(ji,jj) = 0 ; bathy(ji,jj) = 0.0_wp ; misfdep(ji,jj) = 0 ; risfdep(ji,jj) = 0.0_wp ;
+               END IF
+               IF( ibtest < zmbathy(ji,jj) .AND. misfdep(ji,jj) .GE. 2) THEN
+                  mbathy(ji,jj) = ibtest
+                  bathy(ji,jj)  = gdepw_1d(ibtest+1) 
+               ENDIF
+            END DO
+         END DO
+         IF( lk_mpp ) THEN 
+            zbathy(:,:) = FLOAT( misfdep(:,:) ) 
+            CALL lbc_lnk( zbathy, 'T', 1. ) 
+            misfdep(:,:) = INT( zbathy(:,:) ) 
+            CALL lbc_lnk( risfdep, 'T', 1. ) 
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF 
+ ! if not compatible after all check (ie U point water column less than 2 cells), mask U
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               IF (mbathy(ji,jj) == misfdep(ji+1,jj) .AND. mbathy(ji,jj) .GE. 1 .AND. mbathy(ji+1,jj) .GE. 1) THEN
+                  mbathy(ji,jj)  = mbathy(ji,jj) - 1 ; bathy(ji,jj)   = gdepw_1d(mbathy(ji,jj)+1) ;
+               END IF
+            END DO
+         END DO
+         IF( lk_mpp ) THEN 
+            zbathy(:,:) = FLOAT( misfdep(:,:) ) 
+            CALL lbc_lnk( zbathy, 'T', 1. ) 
+            misfdep(:,:) = INT( zbathy(:,:) ) 
+            CALL lbc_lnk( risfdep, 'T', 1. ) 
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF 
+ ! if not compatible after all check (ie U point water column less than 2 cells), mask U
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               IF (misfdep(ji,jj) == mbathy(ji+1,jj) .AND. mbathy(ji,jj) .GE. 1 .AND. mbathy(ji+1,jj) .GE. 1) THEN
+                  mbathy(ji+1,jj)  = mbathy(ji+1,jj) - 1;   bathy(ji+1,jj)   = gdepw_1d(mbathy(ji+1,jj)+1) ;
+               END IF
+            END DO
+         END DO
+         IF( lk_mpp ) THEN 
+            zbathy(:,:) = FLOAT( misfdep(:,:) ) 
+            CALL lbc_lnk( zbathy, 'T', 1. ) 
+            misfdep(:,:) = INT( zbathy(:,:) ) 
+            CALL lbc_lnk( risfdep, 'T', 1. ) 
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF 
+ ! if not compatible after all check (ie V point water column less than 2 cells), mask V
+         DO jj = 1, jpjm1
+            DO ji = 1, jpi
+               IF (mbathy(ji,jj) == misfdep(ji,jj+1) .AND. mbathy(ji,jj) .GE. 1 .AND. mbathy(ji,jj+1) .GE. 1) THEN
+                  mbathy(ji,jj)  = mbathy(ji,jj) - 1 ; bathy(ji,jj)   = gdepw_1d(mbathy(ji,jj)+1) ;
+               END IF
+            END DO
+         END DO
+         IF( lk_mpp ) THEN 
+            zbathy(:,:) = FLOAT( misfdep(:,:) ) 
+            CALL lbc_lnk( zbathy, 'T', 1. ) 
+            misfdep(:,:) = INT( zbathy(:,:) ) 
+            CALL lbc_lnk( risfdep, 'T', 1. ) 
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF 
+ ! if not compatible after all check (ie V point water column less than 2 cells), mask V
+         DO jj = 1, jpjm1
+            DO ji = 1, jpi
+               IF (misfdep(ji,jj) == mbathy(ji,jj+1) .AND. mbathy(ji,jj) .GE. 1 .AND. mbathy(ji,jj+1) .GE. 1) THEN
+                  mbathy(ji,jj+1)  = mbathy(ji,jj+1) - 1 ; bathy(ji,jj+1)   = gdepw_1d(mbathy(ji,jj+1)+1) ;
+               END IF
+            END DO
+         END DO
+         IF( lk_mpp ) THEN 
+            zbathy(:,:) = FLOAT( misfdep(:,:) ) 
+            CALL lbc_lnk( zbathy, 'T', 1. ) 
+            misfdep(:,:) = INT( zbathy(:,:) ) 
+            CALL lbc_lnk( risfdep, 'T', 1. ) 
+            CALL lbc_lnk( bathy, 'T', 1. )
+            zbathy(:,:) = FLOAT( mbathy(:,:) )
+            CALL lbc_lnk( zbathy, 'T', 1. )
+            mbathy(:,:) = INT( zbathy(:,:) )
+         ENDIF 
+ ! if not compatible after all check, mask T
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF (mbathy(ji,jj) <= misfdep(ji,jj)) THEN
+                  misfdep(ji,jj) = 0 ; risfdep(ji,jj) = 0._wp ; mbathy(ji,jj)  = 0 ; bathy(ji,jj)   = 0._wp ;
+               END IF
+            END DO
+         END DO
+ 
+         WHERE (mbathy(:,:) == 1)
+            mbathy = 0; bathy = 0.0_wp ; misfdep = 0 ; risfdep = 0.0_wp
+         END WHERE
+      END DO 
+! end check compatibility ice shelf/bathy
+      ! remove very shallow ice shelf (less than ~ 10m if 75L)
+      WHERE (misfdep(:,:) <= 5)
+         misfdep = 1; risfdep = 0.0_wp;
+      END WHERE
+
+      IF( icompt == 0 ) THEN 
+         IF(lwp) WRITE(numout,*)'     no points with ice shelf too close to bathymetry' 
+      ELSE 
+         IF(lwp) WRITE(numout,*)'    ',icompt,' ocean grid points with ice shelf thickness reduced to avoid bathymetry' 
+      ENDIF 
 
       ! Scale factors and depth at T- and W-points
@@ -938,7 +1506,7 @@
 !gm Bug?  check the gdepw_1d
                   !       ... on ik
-                  gdept_0(ji,jj,ik) = gdepw_1d(ik) + ( gdepw_0   (ji,jj,ik+1) - gdepw_1d(ik) )   &
-                     &                           * ((gdept_1d(      ik  ) - gdepw_1d(ik) )   &
-                     &                           / ( gdepw_1d(      ik+1) - gdepw_1d(ik) ))
+                  gdept_0(ji,jj,ik) = gdepw_1d(ik) + ( gdepw_0(ji,jj,ik+1) - gdepw_1d(ik) )   &
+                     &                             * ((gdept_1d(     ik  ) - gdepw_1d(ik) )   &
+                     &                             / ( gdepw_1d(     ik+1) - gdepw_1d(ik) ))
                   e3t_0(ji,jj,ik) = e3t_1d (ik) * ( gdepw_0 (ji,jj,ik+1) - gdepw_1d(ik) )   & 
                      &                          / ( gdepw_1d(      ik+1) - gdepw_1d(ik) ) 
@@ -973,4 +1541,52 @@
          END DO
       END DO
+      !
+      ! (ISF) Definition of e3t, u, v, w for ISF case
+      DO jj = 1, jpj 
+         DO ji = 1, jpi 
+            ik = misfdep(ji,jj) 
+            IF( ik > 1 ) THEN               ! ice shelf point only 
+               IF( risfdep(ji,jj) < gdepw_1d(ik) )  risfdep(ji,jj)= gdepw_1d(ik) 
+               gdepw_0(ji,jj,ik) = risfdep(ji,jj) 
+!gm Bug?  check the gdepw_0 
+               !       ... on ik 
+               gdept_0(ji,jj,ik) = gdepw_1d(ik+1) - ( gdepw_1d(ik+1) - gdepw_0(ji,jj,ik) )   & 
+                  &                               * ( gdepw_1d(ik+1) - gdept_1d(ik)      )   & 
+                  &                               / ( gdepw_1d(ik+1) - gdepw_1d(ik)      ) 
+               e3t_0  (ji,jj,ik  ) = gdepw_1d(ik+1) - gdepw_0(ji,jj,ik) 
+               e3w_0  (ji,jj,ik+1) = gdept_1d(ik+1) - gdept_0(ji,jj,ik)
+
+               IF( ik + 1 == mbathy(ji,jj) ) THEN               ! ice shelf point only (2 cell water column) 
+                  e3w_0  (ji,jj,ik+1) = gdept_0(ji,jj,ik+1) - gdept_0(ji,jj,ik) 
+                ENDIF 
+               !       ... on ik / ik-1 
+               e3w_0  (ji,jj,ik  ) = 2._wp * (gdept_0(ji,jj,ik) - gdepw_0(ji,jj,ik)) 
+               e3t_0  (ji,jj,ik-1) = gdepw_0(ji,jj,ik) - gdepw_1d(ik-1)
+! The next line isn't required and doesn't affect results - included for consistency with bathymetry code 
+               gdept_0(ji,jj,ik-1) = gdept_1d(ik-1)
+            ENDIF 
+         END DO 
+      END DO 
+      ! 
+      it = 0 
+      DO jj = 1, jpj 
+         DO ji = 1, jpi 
+            ik = misfdep(ji,jj) 
+            IF( ik > 1 ) THEN               ! ice shelf point only 
+               e3tp (ji,jj) = e3t_0(ji,jj,ik  ) 
+               e3wp (ji,jj) = e3w_0(ji,jj,ik+1 ) 
+               ! test 
+               zdiff= gdept_0(ji,jj,ik) - gdepw_0(ji,jj,ik  ) 
+               IF( zdiff <= 0. .AND. lwp ) THEN  
+                  it = it + 1 
+                  WRITE(numout,*) ' it      = ', it, ' ik      = ', ik, ' (i,j) = ', ji, jj 
+                  WRITE(numout,*) ' risfdep = ', risfdep(ji,jj) 
+                  WRITE(numout,*) ' gdept = ', gdept_0(ji,jj,ik), ' gdepw = ', gdepw_0(ji,jj,ik+1), ' zdiff = ', zdiff 
+                  WRITE(numout,*) ' e3tp  = ', e3tp(ji,jj), ' e3wp  = ', e3wp(ji,jj) 
+               ENDIF 
+            ENDIF 
+         END DO 
+      END DO 
+      ! END (ISF)
 
       ! Scale factors and depth at U-, V-, UW and VW-points
@@ -991,4 +1607,17 @@
          END DO
       END DO
+      ! (ISF) define e3uw
+      DO jk = 2,jpk                          
+         DO jj = 1, jpjm1 
+            DO ji = 1, fs_jpim1   ! vector opt. 
+               e3uw_0(ji,jj,jk) = MIN( gdept_0(ji,jj,jk), gdept_0(ji+1,jj  ,jk) ) &
+                 &   - MAX( gdept_0(ji,jj,jk-1), gdept_0(ji+1,jj  ,jk-1) )
+               e3vw_0(ji,jj,jk) = MIN( gdept_0(ji,jj,jk), gdept_0(ji  ,jj+1,jk) ) &
+                 &   - MAX( gdept_0(ji,jj,jk-1), gdept_0(ji  ,jj+1,jk-1) )
+            END DO 
+         END DO 
+      END DO
+      !End (ISF)
+      
       CALL lbc_lnk( e3u_0 , 'U', 1._wp )   ;   CALL lbc_lnk( e3uw_0, 'U', 1._wp )   ! lateral boundary conditions
       CALL lbc_lnk( e3v_0 , 'V', 1._wp )   ;   CALL lbc_lnk( e3vw_0, 'V', 1._wp )
@@ -1032,9 +1661,17 @@
      
       ! Compute gdep3w_0 (vertical sum of e3w)
-      gdep3w_0(:,:,1) = 0.5_wp * e3w_0(:,:,1)
-      DO jk = 2, jpk
-         gdep3w_0(:,:,jk) = gdep3w_0(:,:,jk-1) + e3w_0(:,:,jk) 
-      END DO
-        
+      WHERE (misfdep == 0) misfdep = 1
+      DO jj = 1,jpj
+         DO ji = 1,jpi
+            gdep3w_0(ji,jj,1) = 0.5_wp * e3w_0(ji,jj,1)
+            DO jk = 2, misfdep(ji,jj)
+               gdep3w_0(ji,jj,jk) = gdep3w_0(ji,jj,jk-1) + e3w_0(ji,jj,jk) 
+            END DO
+            IF (misfdep(ji,jj) .GE. 2) gdep3w_0(ji,jj,misfdep(ji,jj)) = risfdep(ji,jj) + 0.5_wp * e3w_0(ji,jj,misfdep(ji,jj))
+            DO jk = misfdep(ji,jj) + 1, jpk
+               gdep3w_0(ji,jj,jk) = gdep3w_0(ji,jj,jk-1) + e3w_0(ji,jj,jk) 
+            END DO
+        END DO
+      END DO
       !                                               ! ================= !
       IF(lwp .AND. ll_print) THEN                     !   Control print   !
@@ -1066,4 +1703,6 @@
       !
       CALL wrk_dealloc( jpi, jpj, jpk, zprt )
+      CALL wrk_dealloc( jpi, jpj, zmask, zbathy, zrisfdep )
+      CALL wrk_dealloc( jpi, jpj, zmisfdep, zmbathy )
       !
       IF( nn_timing == 1 )  CALL timing_stop('zgr_zps')
@@ -1445,6 +2084,6 @@
             DO jk = 1, jpkm1
                IF( scobot(ji,jj) >= fsdept(ji,jj,jk) )   mbathy(ji,jj) = MAX( 2, jk )
-               IF( scobot(ji,jj) == 0._wp            )   mbathy(ji,jj) = 0
-            END DO
+            END DO
+            IF( scobot(ji,jj) == 0._wp               )   mbathy(ji,jj) = 0
          END DO
       END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dtatsd.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dtatsd.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/dtatsd.F90	(revision 5075)
@@ -263,4 +263,10 @@
                      ptsd(ji,jj,ik,jp_sal) = (1.-zl) * ptsd(ji,jj,ik,jp_sal) + zl * ptsd(ji,jj,ik-1,jp_sal)
                   ENDIF
+                  ik = mikt(ji,jj)
+                  IF( ik > 1 ) THEN
+                     zl = ( gdept_0(ji,jj,ik) - gdept_1d(ik) ) / ( gdept_1d(ik+1) - gdept_1d(ik) ) 
+                     ptsd(ji,jj,ik,jp_tem) = (1.-zl) * ptsd(ji,jj,ik,jp_tem) + zl * ptsd(ji,jj,ik+1,jp_tem)
+                     ptsd(ji,jj,ik,jp_sal) = (1.-zl) * ptsd(ji,jj,ik,jp_sal) + zl * ptsd(ji,jj,ik+1,jp_sal)
+                  END IF
                END DO
             END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/istate.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/istate.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/istate.F90	(revision 5075)
@@ -34,6 +34,4 @@
    USE dtatsd          ! data temperature and salinity   (dta_tsd routine)
    USE dtauvd          ! data: U & V current             (dta_uvd routine)
-   USE in_out_manager  ! I/O manager
-   USE iom             ! I/O library
    USE zpshde          ! partial step: hor. derivative (zps_hde routine)
    USE eosbn2          ! equation of state            (eos bn2 routine)
@@ -42,4 +40,7 @@
    USE dynspg_flt      ! filtered free surface
    USE sol_oce         ! ocean solver variables
+   !
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O library
    USE lib_mpp         ! MPP library
    USE restart         ! restart
@@ -56,5 +57,5 @@
 #  include "vectopt_loop_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! NEMO/OPA 3.7 , NEMO Consortium (2014)
    !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -73,8 +74,8 @@
       !!----------------------------------------------------------------------
       !
-      IF( nn_timing == 1 )  CALL timing_start('istate_init')
-      !
-
-      IF(lwp) WRITE(numout,*)
+      IF( nn_timing == 1 )   CALL timing_start('istate_init')
+      !
+
+      IF(lwp) WRITE(numout,*) ' '
       IF(lwp) WRITE(numout,*) 'istate_ini : Initialization of the dynamics and tracers'
       IF(lwp) WRITE(numout,*) '~~~~~~~~~~'
@@ -83,8 +84,10 @@
       IF( lk_c1d ) CALL dta_uvd_init          ! Initialization of U & V input data
 
-      rhd  (:,:,:  ) = 0.e0
-      rhop (:,:,:  ) = 0.e0
-      rn2  (:,:,:  ) = 0.e0 
-      tsa  (:,:,:,:) = 0.e0    
+      rhd  (:,:,:  ) = 0._wp
+      rhop (:,:,:  ) = 0._wp
+      rn2  (:,:,:  ) = 0._wp
+      tsa  (:,:,:,:) = 0._wp   
+      rab_b(:,:,:,:) = 0._wp
+      rab_n(:,:,:,:) = 0._wp
 
       IF( ln_rstart ) THEN                    ! Restart from a file
@@ -110,4 +113,9 @@
          ELSEIF( cp_cfg == 'gyre' ) THEN         
             CALL istate_gyre                     ! GYRE  configuration : start from pre-defined T-S fields
+        ELSEIF( cp_cfg == 'isomip' .OR. cp_cfg == 'isomip2') THEN
+            IF(lwp) WRITE(numout,*) 'Initialization of T+S for ISOMIP domain' 
+            tsn(:,:,:,jp_tem)=-1.9*tmask(:,:,:)          ! ISOMIP configuration : start from constant T+S fields 
+            tsn(:,:,:,jp_sal)=34.4*tmask(:,:,:)
+            tsb(:,:,:,:)=tsn(:,:,:,:)  
          ELSE                                    ! Initial T-S, U-V fields read in files
             IF ( ln_tsd_init ) THEN              ! read 3D T and S data at nit000
@@ -129,6 +137,7 @@
          CALL eos( tsb, rhd, rhop, gdept_0(:,:,:) )        ! before potential and in situ densities
 #if ! defined key_c1d
-         IF( ln_zps )   CALL zps_hde( nit000, jpts, tsb, gtsu, gtsv,  & ! zps: before hor. gradient
-            &                                       rhd, gru , grv  )   ! of t,s,rd at ocean bottom
+         IF( ln_zps )    CALL zps_hde( nit000, jpts, tsb, gtsu, gtsv,  &        ! Partial steps: before horizontal gradient
+            &                                      rhd, gru , grv, aru, arv, gzu, gzv, ge3ru, ge3rv,  &             !
+            &                                      gtui, gtvi, grui, grvi, arui, arvi, gzui, gzvi, ge3rui, ge3rvi  )  ! of t, s, rd at the last ocean level
 #endif
          !   
@@ -162,11 +171,6 @@
       !
       DO jk = 1, jpkm1
-#if defined key_vectopt_loop
-         DO jj = 1, 1         !Vector opt. => forced unrolling
-            DO ji = 1, jpij
-#else 
          DO jj = 1, jpj
             DO ji = 1, jpi
-#endif                  
                un_b(ji,jj) = un_b(ji,jj) + fse3u_n(ji,jj,jk) * un(ji,jj,jk) * umask(ji,jj,jk)
                vn_b(ji,jj) = vn_b(ji,jj) + fse3v_n(ji,jj,jk) * vn(ji,jj,jk) * vmask(ji,jj,jk)
@@ -185,7 +189,8 @@
       !
       !
-      IF( nn_timing == 1 )  CALL timing_stop('istate_init')
+      IF( nn_timing == 1 )   CALL timing_stop('istate_init')
       !
    END SUBROUTINE istate_init
+
 
    SUBROUTINE istate_t_s
@@ -219,4 +224,5 @@
    END SUBROUTINE istate_t_s
 
+
    SUBROUTINE istate_eel
       !!----------------------------------------------------------------------
@@ -233,5 +239,5 @@
       USE divcur     ! hor. divergence & rel. vorticity      (div_cur routine)
       USE iom
- 
+      !
       INTEGER  ::   inum              ! temporary logical unit
       INTEGER  ::   ji, jj, jk        ! dummy loop indices
@@ -244,5 +250,5 @@
       REAL(wp), DIMENSION(jpiglo,jpjglo) ::   zssh  ! initial ssh over the global domain
       !!----------------------------------------------------------------------
-
+      !
       SELECT CASE ( jp_cfg ) 
          !                                              ! ====================
@@ -375,12 +381,12 @@
       INTEGER, PARAMETER ::   ntsinit = 0   ! (0/1) (analytical/input data files) T&S initialization
       !!----------------------------------------------------------------------
-
+      !
       SELECT CASE ( ntsinit)
-
+      !
       CASE ( 0 )                  ! analytical T/S profil deduced from LEVITUS
          IF(lwp) WRITE(numout,*)
          IF(lwp) WRITE(numout,*) 'istate_gyre : initial analytical T and S profil deduced from LEVITUS '
          IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
-
+         !
          DO jk = 1, jpk
             DO jj = 1, jpj
@@ -407,5 +413,5 @@
             END DO
          END DO
-
+         !
       CASE ( 1 )                  ! T/S data fields read in dta_tem.nc/data_sal.nc files
          IF(lwp) WRITE(numout,*)
@@ -431,7 +437,7 @@
          tsn(:,:,:,jp_sal) = tsn(:,:,:,jp_sal) * tmask(:,:,:) 
          tsb(:,:,:,jp_sal) = tsn(:,:,:,jp_sal)
-
+         !
       END SELECT
-
+      !
       IF(lwp) THEN
          WRITE(numout,*)
@@ -440,6 +446,7 @@
          WRITE(numout, "(10x, i4, 3f10.2)" ) ( jk, gdept_1d(jk), tsn(2,2,jk,jp_tem), tsn(2,2,jk,jp_sal), jk = 1, jpk )
       ENDIF
-
+      !
    END SUBROUTINE istate_gyre
+
 
    SUBROUTINE istate_uvg
@@ -457,5 +464,5 @@
       USE divcur          ! hor. divergence & rel. vorticity      (div_cur routine)
       USE lbclnk          ! ocean lateral boundary condition (or mpp link)
-
+      !
       INTEGER ::   ji, jj, jk        ! dummy loop indices
       INTEGER ::   indic             ! ???
@@ -567,3 +574,2 @@
    !!=====================================================================
 END MODULE istate
-
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/phycst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/phycst.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DOM/phycst.F90	(revision 5075)
@@ -47,12 +47,7 @@
    REAL(wp), PUBLIC ::   rt0_ice  = 273.05_wp        !: melting point of ice          [Kelvin]
 #endif
-#if defined key_cice
-   REAL(wp), PUBLIC ::   rau0     = 1026._wp         !: volumic mass of reference     [kg/m3]
-#else
-   REAL(wp), PUBLIC ::   rau0     = 1035._wp         !: volumic mass of reference     [kg/m3]
-#endif
+   REAL(wp), PUBLIC ::   rau0                        !: volumic mass of reference     [kg/m3]
    REAL(wp), PUBLIC ::   r1_rau0                     !: = 1. / rau0                   [m3/kg]
-   REAL(wp), PUBLIC ::   rauw     = 1000._wp         !: volumic mass of pure water    [m3/kg]
-   REAL(wp), PUBLIC ::   rcp      =    4.e3_wp       !: ocean specific heat           [J/Kelvin]
+   REAL(wp), PUBLIC ::   rcp                         !: ocean specific heat           [J/Kelvin]
    REAL(wp), PUBLIC ::   r1_rcp                      !: = 1. / rcp                    [Kelvin/J]
    REAL(wp), PUBLIC ::   r1_rau0_rcp                 !: = 1. / ( rau0 * rcp )
@@ -163,15 +158,6 @@
       IF(lwp) WRITE(numout,*) '          melting point of ice             rt0_ice  = ', rt0_ice , ' K'
 
-      r1_rau0     = 1._wp / rau0
-      r1_rcp      = 1._wp / rcp
-      r1_rau0_rcp = 1._wp / ( rau0 * rcp )
-      IF(lwp) WRITE(numout,*)
-      IF(lwp) WRITE(numout,*) '          volumic mass of pure water          rauw  = ', rauw   , ' kg/m^3'
-      IF(lwp) WRITE(numout,*) '          volumic mass of reference           rau0  = ', rau0   , ' kg/m^3'
-      IF(lwp) WRITE(numout,*) '          1. / rau0                        r1_rau0  = ', r1_rau0, ' m^3/kg'
-      IF(lwp) WRITE(numout,*) '          ocean specific heat                 rcp   = ', rcp    , ' J/Kelvin'
-      IF(lwp) WRITE(numout,*) '          1. / ( rau0 * rcp )           r1_rau0_rcp = ', r1_rau0_rcp
-
-
+      IF(lwp) WRITE(numout,*) '          reference density and heat capacity now defined in eosbn2.f90'
+              
 #if defined key_lim3 || defined key_cice
       xlsn = lfus * rhosn        ! volumetric latent heat fusion of snow [J/m3]
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/divcur.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/divcur.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/divcur.F90	(revision 5075)
@@ -25,6 +25,7 @@
    USE oce             ! ocean dynamics and tracers
    USE dom_oce         ! ocean space and time domain
-   USE sbc_oce, ONLY : ln_rnf   ! surface boundary condition: ocean
+   USE sbc_oce, ONLY : ln_rnf, nn_isf ! surface boundary condition: ocean
    USE sbcrnf          ! river runoff 
+   USE sbcisf          ! ice shelf 
    USE cla             ! cross land advection             (cla_div routine)
    USE in_out_manager  ! I/O manager
@@ -66,5 +67,6 @@
       !!         - compute the now divergence given by :
       !!         hdivn = 1/(e1t*e2t*e3t) ( di[e2u*e3u un] + dj[e1v*e3v vn] )
-      !!      correct hdiv with runoff inflow (div_rnf) and cross land flow (div_cla) 
+      !!      correct hdiv with runoff inflow (div_rnf), ice shelf melting (div_isf)
+      !!      and cross land flow (div_cla) 
       !!              II. vorticity :
       !!         - save the curl computed at the previous time-step
@@ -225,6 +227,7 @@
       !                                                ! ===============
 
-      IF( ln_rnf      )   CALL sbc_rnf_div( hdivn )          ! runoffs (update hdivn field)
-      IF( nn_cla == 1 .AND. cp_cfg == 'orca' .AND. jp_cfg == 2 )   CALL cla_div    ( kt )             ! Cross Land Advection (Update Hor. divergence)
+      IF( ln_rnf      )   CALL sbc_rnf_div( hdivn )          ! runoffs   (update hdivn field)
+      IF( ln_divisf .AND. (nn_isf /= 0) )   CALL sbc_isf_div( hdivn )          ! ice shelf (update hdivn field)
+      IF( nn_cla == 1 )   CALL cla_div    ( kt )             ! Cross Land Advection (Update Hor. divergence)
       
       ! 4. Lateral boundary conditions on hdivn and rotn
@@ -323,5 +326,6 @@
       !                                                ! ===============
 
-      IF( ln_rnf      )   CALL sbc_rnf_div( hdivn )          ! runoffs (update hdivn field)
+      IF( ln_rnf      )   CALL sbc_rnf_div( hdivn )                            ! runoffs (update hdivn field)
+      IF( ln_divisf .AND. (nn_isf .GT. 0) )   CALL sbc_isf_div( hdivn )          ! ice shelf (update hdivn field)
       IF( nn_cla == 1 )   CALL cla_div    ( kt )             ! Cross Land Advection (update hdivn field)
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv.F90	(revision 5075)
@@ -30,4 +30,5 @@
    LOGICAL, PUBLIC ::   ln_dynadv_cen2  !: flux form - 2nd order centered scheme flag
    LOGICAL, PUBLIC ::   ln_dynadv_ubs   !: flux form - 3rd order UBS scheme flag
+   LOGICAL, PUBLIC ::   ln_dynzad_zts   !: vertical advection with sub-timestepping (requires vector form)
    
    INTEGER ::   nadv   ! choice of the formulation and scheme for the advection
@@ -64,7 +65,10 @@
                       CALL dyn_keg     ( kt )    ! vector form : horizontal gradient of kinetic energy
                       CALL dyn_zad     ( kt )    ! vector form : vertical advection
-      CASE ( 1 ) 
+      CASE ( 1 )     
+                      CALL dyn_keg     ( kt )    ! vector form : horizontal gradient of kinetic energy
+                      CALL dyn_zad_zts ( kt )    ! vector form : vertical advection with sub-timestepping
+      CASE ( 2 ) 
                       CALL dyn_adv_cen2( kt )    ! 2nd order centered scheme
-      CASE ( 2 )   
+      CASE ( 3 )   
                       CALL dyn_adv_ubs ( kt )    ! 3rd order UBS      scheme
       !
@@ -91,5 +95,5 @@
       INTEGER  ::   ios                 ! Local integer output status for namelist read
       !!
-      NAMELIST/namdyn_adv/ ln_dynadv_vec, ln_dynadv_cen2 , ln_dynadv_ubs
+      NAMELIST/namdyn_adv/ ln_dynadv_vec, ln_dynadv_cen2 , ln_dynadv_ubs, ln_dynzad_zts
       !!----------------------------------------------------------------------
 
@@ -111,4 +115,5 @@
          WRITE(numout,*) '          2nd order centred advection scheme ln_dynadv_cen2 = ', ln_dynadv_cen2
          WRITE(numout,*) '          3rd order UBS advection scheme     ln_dynadv_ubs  = ', ln_dynadv_ubs
+         WRITE(numout,*) '      Sub timestepping of vertical advection ln_dynzad_zts  = ', ln_dynzad_zts
       ENDIF
 
@@ -120,9 +125,12 @@
 
       IF( ioptio /= 1 )   CALL ctl_stop( 'Choose ONE advection scheme in namelist namdyn_adv' )
+      IF( ln_dynzad_zts .AND. .NOT. ln_dynadv_vec )   &
+          CALL ctl_stop( 'Sub timestepping of vertical advection requires vector form; set ln_dynadv_vec = .TRUE.' )
 
       !                               ! Set nadv
       IF( ln_dynadv_vec  )   nadv =  0 
-      IF( ln_dynadv_cen2 )   nadv =  1
-      IF( ln_dynadv_ubs  )   nadv =  2
+      IF( ln_dynzad_zts  )   nadv =  1
+      IF( ln_dynadv_cen2 )   nadv =  2
+      IF( ln_dynadv_ubs  )   nadv =  3
       IF( lk_esopa       )   nadv = -1
 
@@ -130,6 +138,7 @@
          WRITE(numout,*)
          IF( nadv ==  0 )   WRITE(numout,*) '         vector form : keg + zad + vor is used'
-         IF( nadv ==  1 )   WRITE(numout,*) '         flux form   : 2nd order scheme is used'
-         IF( nadv ==  2 )   WRITE(numout,*) '         flux form   : UBS       scheme is used'
+         IF( nadv ==  1 )   WRITE(numout,*) '         vector form : keg + zad_zts + vor is used'
+         IF( nadv ==  2 )   WRITE(numout,*) '         flux form   : 2nd order scheme is used'
+         IF( nadv ==  3 )   WRITE(numout,*) '         flux form   : UBS       scheme is used'
          IF( nadv == -1 )   WRITE(numout,*) '         esopa test: use all advection formulation'
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv_cen2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv_cen2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv_cen2.F90	(revision 5075)
@@ -15,11 +15,12 @@
    USE oce            ! ocean dynamics and tracers
    USE dom_oce        ! ocean space and time domain
-   USE trdmod_oce     ! ocean variables trends
-   USE trdmod         ! ocean dynamics trends
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics
+   !
    USE in_out_manager ! I/O manager
    USE lib_mpp        ! MPP library
    USE prtctl         ! Print control
-   USE wrk_nemo        ! Memory Allocation
-   USE timing          ! Timing
+   USE wrk_nemo       ! Memory Allocation
+   USE timing         ! Timing
 
    IMPLICIT NONE
@@ -103,5 +104,5 @@
          zfu_uw(:,:,:) = ua(:,:,:) - zfu_uw(:,:,:)
          zfv_vw(:,:,:) = va(:,:,:) - zfv_vw(:,:,:)
-         CALL trd_mod( zfu_uw, zfv_vw, jpdyn_trd_had, 'DYN', kt )
+         CALL trd_dyn( zfu_uw, zfv_vw, jpdyn_keg, kt )
          zfu_t(:,:,:) = ua(:,:,:)
          zfv_t(:,:,:) = va(:,:,:)
@@ -153,5 +154,5 @@
          zfu_t(:,:,:) = ua(:,:,:) - zfu_t(:,:,:)
          zfv_t(:,:,:) = va(:,:,:) - zfv_t(:,:,:)
-         CALL trd_mod( zfu_t, zfv_t, jpdyn_trd_zad, 'DYN', kt )
+         CALL trd_dyn( zfu_t, zfv_t, jpdyn_zad, kt )
       ENDIF
       !                                            ! Control print
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv_ubs.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv_ubs.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynadv_ubs.F90	(revision 5075)
@@ -16,12 +16,13 @@
    USE oce            ! ocean dynamics and tracers
    USE dom_oce        ! ocean space and time domain
-   USE trdmod         ! ocean dynamics trends
-   USE trdmod_oce     ! ocean variables trends
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics
+   !
    USE in_out_manager ! I/O manager
    USE prtctl         ! Print control
    USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
    USE lib_mpp        ! MPP library
-   USE wrk_nemo        ! Memory Allocation
-   USE timing          ! Timing
+   USE wrk_nemo       ! Memory Allocation
+   USE timing         ! Timing
 
    IMPLICIT NONE
@@ -115,28 +116,25 @@
          DO jj = 2, jpjm1                          ! laplacian
             DO ji = fs_2, fs_jpim1   ! vector opt.
-               zlu_uu(ji,jj,jk,1) = ( ub (ji+1,jj,jk)-2.*ub (ji,jj,jk)+ub (ji-1,jj,jk) ) * umask(ji,jj,jk)
-               zlv_vv(ji,jj,jk,1) = ( vb (ji,jj+1,jk)-2.*vb (ji,jj,jk)+vb (ji,jj-1,jk) ) * vmask(ji,jj,jk) 
-               zlu_uv(ji,jj,jk,1) = ( ub (ji,jj+1,jk)-2.*ub (ji,jj,jk)+ub (ji,jj-1,jk) ) * umask(ji,jj,jk)
-               zlv_vu(ji,jj,jk,1) = ( vb (ji+1,jj,jk)-2.*vb (ji,jj,jk)+vb (ji-1,jj,jk) ) * vmask(ji,jj,jk)
-               !
-               zlu_uu(ji,jj,jk,2) = ( zfu(ji+1,jj,jk)-2.*zfu(ji,jj,jk)+zfu(ji-1,jj,jk) ) * umask(ji,jj,jk)
-               zlv_vv(ji,jj,jk,2) = ( zfv(ji,jj+1,jk)-2.*zfv(ji,jj,jk)+zfv(ji,jj-1,jk) ) * vmask(ji,jj,jk)
-               zlu_uv(ji,jj,jk,2) = ( zfu(ji,jj+1,jk)-2.*zfu(ji,jj,jk)+zfu(ji,jj-1,jk) ) * umask(ji,jj,jk)
-               zlv_vu(ji,jj,jk,2) = ( zfv(ji+1,jj,jk)-2.*zfv(ji,jj,jk)+zfv(ji-1,jj,jk) ) * vmask(ji,jj,jk)
-            END DO
-         END DO
-      END DO
-!!gm BUG !!!  just below this should be +1 in all the communications
-!      CALL lbc_lnk( zlu_uu(:,:,:,1), 'U', -1.)   ;   CALL lbc_lnk( zlu_uv(:,:,:,1), 'U', -1.)
-!      CALL lbc_lnk( zlu_uu(:,:,:,2), 'U', -1.)   ;   CALL lbc_lnk( zlu_uv(:,:,:,2), 'U', -1.)
-!      CALL lbc_lnk( zlv_vv(:,:,:,1), 'V', -1.)   ;   CALL lbc_lnk( zlv_vu(:,:,:,1), 'V', -1.)
-!      CALL lbc_lnk( zlv_vv(:,:,:,2), 'V', -1.)   ;   CALL lbc_lnk( zlv_vu(:,:,:,2), 'V', -1.)
-!
-!!gm corrected:
+               !
+               zlu_uu(ji,jj,jk,1) = ( ub (ji+1,jj  ,jk) - 2.*ub (ji,jj,jk) + ub (ji-1,jj  ,jk) ) * umask(ji,jj,jk)
+               zlv_vv(ji,jj,jk,1) = ( vb (ji  ,jj+1,jk) - 2.*vb (ji,jj,jk) + vb (ji  ,jj-1,jk) ) * vmask(ji,jj,jk)
+               zlu_uv(ji,jj,jk,1) = ( ub (ji  ,jj+1,jk) - ub (ji  ,jj  ,jk) ) * fmask(ji  ,jj  ,jk)   &
+                  &               - ( ub (ji  ,jj  ,jk) - ub (ji  ,jj-1,jk) ) * fmask(ji  ,jj-1,jk)
+               zlv_vu(ji,jj,jk,1) = ( vb (ji+1,jj  ,jk) - vb (ji  ,jj  ,jk) ) * fmask(ji  ,jj  ,jk)   &
+                  &               - ( vb (ji  ,jj  ,jk) - vb (ji-1,jj  ,jk) ) * fmask(ji-1,jj  ,jk)
+               !
+               zlu_uu(ji,jj,jk,2) = ( zfu(ji+1,jj  ,jk) - 2.*zfu(ji,jj,jk) + zfu(ji-1,jj  ,jk) ) * umask(ji,jj,jk)
+               zlv_vv(ji,jj,jk,2) = ( zfv(ji  ,jj+1,jk) - 2.*zfv(ji,jj,jk) + zfv(ji  ,jj-1,jk) ) * vmask(ji,jj,jk)
+               zlu_uv(ji,jj,jk,2) = ( zfu(ji  ,jj+1,jk) - zfu(ji  ,jj  ,jk) ) * fmask(ji  ,jj  ,jk)   &
+                  &               - ( zfu(ji  ,jj  ,jk) - zfu(ji  ,jj-1,jk) ) * fmask(ji  ,jj-1,jk)
+               zlv_vu(ji,jj,jk,2) = ( zfv(ji+1,jj  ,jk) - zfv(ji  ,jj  ,jk) ) * fmask(ji  ,jj  ,jk)   &
+                  &               - ( zfv(ji  ,jj  ,jk) - zfv(ji-1,jj  ,jk) ) * fmask(ji-1,jj  ,jk)
+            END DO
+         END DO
+      END DO
       CALL lbc_lnk( zlu_uu(:,:,:,1), 'U', 1. )   ;   CALL lbc_lnk( zlu_uv(:,:,:,1), 'U', 1. )
       CALL lbc_lnk( zlu_uu(:,:,:,2), 'U', 1. )   ;   CALL lbc_lnk( zlu_uv(:,:,:,2), 'U', 1. )
       CALL lbc_lnk( zlv_vv(:,:,:,1), 'V', 1. )   ;   CALL lbc_lnk( zlv_vu(:,:,:,1), 'V', 1. )
       CALL lbc_lnk( zlv_vv(:,:,:,2), 'V', 1. )   ;   CALL lbc_lnk( zlv_vu(:,:,:,2), 'V', 1. ) 
-!!gm end
       
       !                                      ! ====================== !
@@ -196,5 +194,5 @@
          zfu_uw(:,:,:) = ua(:,:,:) - zfu_uw(:,:,:)
          zfv_vw(:,:,:) = va(:,:,:) - zfv_vw(:,:,:)
-         CALL trd_mod( zfu_uw, zfv_vw, jpdyn_trd_had, 'DYN', kt )
+         CALL trd_dyn( zfu_uw, zfv_vw, jpdyn_keg, kt )
          zfu_t(:,:,:) = ua(:,:,:)
          zfv_t(:,:,:) = va(:,:,:)
@@ -245,5 +243,5 @@
          zfu_t(:,:,:) = ua(:,:,:) - zfu_t(:,:,:)
          zfv_t(:,:,:) = va(:,:,:) - zfv_t(:,:,:)
-         CALL trd_mod( zfu_t, zfv_t, jpdyn_trd_zad, 'DYN', kt )
+         CALL trd_dyn( zfu_t, zfv_t, jpdyn_zad, kt )
       ENDIF
       !                                            ! Control print
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynbfr.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynbfr.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynbfr.F90	(revision 5075)
@@ -10,21 +10,21 @@
 
    !!----------------------------------------------------------------------
-   !!   dyn_bfr      : Update the momentum trend with the bottom friction contribution
+   !!   dyn_bfr       : Update the momentum trend with the bottom friction contribution
    !!----------------------------------------------------------------------
-   USE oce             ! ocean dynamics and tracers variables
-   USE dom_oce         ! ocean space and time domain variables 
-   USE zdf_oce         ! ocean vertical physics variables
-   USE zdfbfr          ! ocean bottom friction variables
-   USE trdmod          ! ocean active dynamics and tracers trends 
-   USE trdmod_oce      ! ocean variables trends
-   USE in_out_manager  ! I/O manager
-   USE prtctl          ! Print control
-   USE timing          ! Timing
-   USE wrk_nemo        ! Memory Allocation
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables 
+   USE zdf_oce        ! ocean vertical physics variables
+   USE zdfbfr         ! ocean bottom friction variables
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics
+   USE in_out_manager ! I/O manager
+   USE prtctl         ! Print control
+   USE timing         ! Timing
+   USE wrk_nemo       ! Memory Allocation
 
    IMPLICIT NONE
    PRIVATE
 
-   PUBLIC   dyn_bfr    !  routine called by step.F90
+   PUBLIC   dyn_bfr   !  routine called by step.F90
 
    !! * Substitutions
@@ -57,7 +57,10 @@
       IF( nn_timing == 1 )  CALL timing_start('dyn_bfr')
       !
+!!gm issue: better to put the logical in step to control the call of zdf_bfr
+!!          ==> change the logical from ln_bfrimp to ln_bfr_exp !!
       IF( .NOT.ln_bfrimp) THEN     ! only for explicit bottom friction form
                                     ! implicit bfr is implemented in dynzdf_imp
 
+!!gm bug : time step is only rdt (not 2 rdt if euler start !)
         zm1_2dt = - 1._wp / ( 2._wp * rdt )
 
@@ -69,11 +72,6 @@
 
 
-# if defined key_vectopt_loop
-        DO jj = 1, 1
-           DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
-# else
         DO jj = 2, jpjm1
            DO ji = 2, jpim1
-# endif
               ikbu = mbku(ji,jj)          ! deepest ocean u- & v-levels
               ikbv = mbkv(ji,jj)
@@ -82,4 +80,16 @@
               ua(ji,jj,ikbu) = ua(ji,jj,ikbu) + MAX(  bfrua(ji,jj) / fse3u(ji,jj,ikbu) , zm1_2dt  ) * ub(ji,jj,ikbu)
               va(ji,jj,ikbv) = va(ji,jj,ikbv) + MAX(  bfrva(ji,jj) / fse3v(ji,jj,ikbv) , zm1_2dt  ) * vb(ji,jj,ikbv)
+              
+              ! (ISF) stability criteria for top friction
+              ikbu = miku(ji,jj)          ! first wet ocean u- & v-levels
+              ikbv = mikv(ji,jj)
+              !
+              ! Apply stability criteria on absolute value  : abs(bfr/e3) < 1/(2dt) => bfr/e3 > -1/(2dt)
+              ua(ji,jj,ikbu) = ua(ji,jj,ikbu) + MAX(  tfrua(ji,jj) / fse3u(ji,jj,ikbu) , zm1_2dt  ) * ub(ji,jj,ikbu) &
+                 &             * (1.-umask(ji,jj,1))
+              va(ji,jj,ikbv) = va(ji,jj,ikbv) + MAX(  tfrva(ji,jj) / fse3v(ji,jj,ikbv) , zm1_2dt  ) * vb(ji,jj,ikbv) &
+                 &             * (1.-vmask(ji,jj,1))
+              ! (ISF)
+              
            END DO
         END DO
@@ -89,5 +99,5 @@
            ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
            ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-           CALL trd_mod( ztrdu(:,:,:), ztrdv(:,:,:), jpdyn_trd_bfr, 'DYN', kt )
+           CALL trd_dyn( ztrdu(:,:,:), ztrdv(:,:,:), jpdyn_bfr, kt )
            CALL wrk_dealloc( jpi,jpj,jpk, ztrdu, ztrdv )
         ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynhpg.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynhpg.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynhpg.F90	(revision 5075)
@@ -29,12 +29,15 @@
    !!----------------------------------------------------------------------
    USE oce             ! ocean dynamics and tracers
+   USE sbc_oce         ! surface variable (only for the flag with ice shelf)
    USE dom_oce         ! ocean space and time domain
    USE phycst          ! physical constants
-   USE trdmod          ! ocean dynamics trends
-   USE trdmod_oce      ! ocean variables trends
+   USE trd_oce         ! trends: ocean variables
+   USE trddyn          ! trend manager: dynamics
+   !
    USE in_out_manager  ! I/O manager
    USE prtctl          ! Print control
-   USE lbclnk          ! lateral boundary condition
+   USE lbclnk          ! lateral boundary condition 
    USE lib_mpp         ! MPP library
+   USE eosbn2          ! compute density
    USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
@@ -74,5 +77,5 @@
       !!
       !! ** Action : - Update (ua,va) with the now hydrastatic pressure trend
-      !!             - Save the trend (l_trddyn=T)
+      !!             - send trends to trd_dyn for futher diagnostics (l_trddyn=T)
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
@@ -99,5 +102,5 @@
          ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
          ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-         CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_hpg, 'DYN', kt )
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_hpg, kt )
          CALL wrk_dealloc( jpi,jpj,jpk, ztrdu, ztrdv )
       ENDIF
@@ -175,4 +178,6 @@
       IF( ln_hpg_prj )   ioptio = ioptio + 1
       IF( ioptio /= 1 )   CALL ctl_stop( 'NO or several hydrostatic pressure gradient options used' )
+      IF( (ln_hpg_zco .OR. ln_hpg_zps .OR. ln_hpg_djc .OR. ln_hpg_prj ) .AND. nn_isf .NE. 0 )   &
+          &  CALL ctl_stop( 'Only hpg_sco has been corrected to work with ice shelf cavity.' )
       !
    END SUBROUTINE dyn_hpg_init
@@ -315,11 +320,6 @@
 
       ! partial steps correction at the last level  (use gru & grv computed in zpshde.F90)
-# if defined key_vectopt_loop
-         jj = 1
-         DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
-# else
       DO jj = 2, jpjm1
          DO ji = 2, jpim1
-# endif
             iku = mbku(ji,jj)
             ikv = mbkv(ji,jj)
@@ -338,7 +338,5 @@
                va  (ji,jj,ikv) = va(ji,jj,ikv) + zhpj(ji,jj,ikv)         ! add the new one to the general momentum trend
             ENDIF
-# if ! defined key_vectopt_loop
-         END DO
-# endif
+         END DO
       END DO
       !
@@ -368,12 +366,16 @@
       INTEGER, INTENT(in) ::   kt    ! ocean time-step index
       !!
-      INTEGER  ::   ji, jj, jk                 ! dummy loop indices
-      REAL(wp) ::   zcoef0, zuap, zvap, znad   ! temporary scalars
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::  zhpi, zhpj
-      !!----------------------------------------------------------------------
-      !
-      CALL wrk_alloc( jpi,jpj,jpk, zhpi, zhpj )
-      !
-      IF( kt == nit000 ) THEN
+      INTEGER  ::   ji, jj, jk, iku, ikv, ikt, iktp1i, iktp1j                 ! dummy loop indices
+      REAL(wp) ::   zcoef0, zuap, zvap, znad, ze3wu, ze3wv, zuapint, zvapint, zhpjint, zhpiint, zdzwt, zdzwtjp1, zdzwtip1             ! temporary scalars
+      REAL(wp), POINTER, DIMENSION(:,:,:)   ::  zhpi, zhpj, zrhd
+      REAL(wp), POINTER, DIMENSION(:,:,:)   ::  ztstop
+      REAL(wp), POINTER, DIMENSION(:,:)     ::  ze3w, zp, zrhdtop_isf, zrhdtop_oce, ziceload, zdept, zpshpi, zpshpj
+      !!----------------------------------------------------------------------
+      !
+      CALL wrk_alloc( jpi,jpj, 2, ztstop) 
+      CALL wrk_alloc( jpi,jpj,jpk, zhpi, zhpj, zrhd)
+      CALL wrk_alloc( jpi,jpj, ze3w, zp, zrhdtop_isf, zrhdtop_oce, ziceload, zdept, zpshpi, zpshpj) 
+      !
+     IF( kt == nit000 ) THEN
          IF(lwp) WRITE(numout,*)
          IF(lwp) WRITE(numout,*) 'dyn:hpg_sco : hydrostatic pressure gradient trend'
@@ -384,17 +386,74 @@
       zcoef0 = - grav * 0.5_wp
       ! To use density and not density anomaly
-      IF ( lk_vvl ) THEN   ;     znad = 1._wp          ! Variable volume
-      ELSE                 ;     znad = 0._wp         ! Fixed volume
-      ENDIF
-
-      ! Surface value
+!      IF ( lk_vvl ) THEN   ;     znad = 1._wp          ! Variable volume
+!      ELSE                 ;     znad = 0._wp         ! Fixed volume
+!      ENDIF
+      znad=1._wp
+      ! iniitialised to 0. zhpi zhpi 
+      zhpi(:,:,:)=0._wp ; zhpj(:,:,:)=0._wp
+
+!==================================================================================     
+!=====Compute iceload and contribution of the half first wet layer ================= 
+!===================================================================================
+
+      ! assume water displaced by the ice shelf is at T=-1.9 and S=34.4 (rude)
+      ztstop(:,:,1)=-1.9_wp ; ztstop(:,:,2)=34.4_wp
+
+      ! compute density of the water displaced by the ice shelf 
+      zrhd = rhd ! save rhd
+      DO jk = 1, jpk
+           zdept(:,:)=gdept_1d(jk)
+           CALL eos(ztstop(:,:,:),zdept(:,:),rhd(:,:,jk))
+      END DO
+      WHERE ( tmask(:,:,:) == 1._wp)
+        rhd(:,:,:) = zrhd(:,:,:) ! replace wet cell by the saved rhd
+      END WHERE
+      
+      ! compute rhd at the ice/oce interface (ice shelf side)
+      CALL eos(ztstop,risfdep,zrhdtop_isf)
+
+      ! compute rhd at the ice/oce interface (ocean side)
+      DO ji=1,jpi
+        DO jj=1,jpj
+          ikt=mikt(ji,jj)
+          ztstop(ji,jj,1)=tsn(ji,jj,ikt,1)
+          ztstop(ji,jj,2)=tsn(ji,jj,ikt,2)
+        END DO
+      END DO
+      CALL eos(ztstop,risfdep,zrhdtop_oce)
+      !
+      ! Surface value + ice shelf gradient
+      ! compute pressure due to ice shelf load (used to compute hpgi/j for all the level from 1 to miku/v)
+      ziceload = 0._wp
+      DO jj = 1, jpj
+         DO ji = 1, jpi   ! vector opt.
+            ikt=mikt(ji,jj)
+            ziceload(ji,jj) = ziceload(ji,jj) + (znad + rhd(ji,jj,1) ) * fse3w(ji,jj,1) * (1._wp - tmask(ji,jj,1))
+            DO jk=2,ikt-1
+               ziceload(ji,jj) = ziceload(ji,jj) + (2._wp * znad + rhd(ji,jj,jk-1) + rhd(ji,jj,jk)) * fse3w(ji,jj,jk) &
+                  &                              * (1._wp - tmask(ji,jj,jk))
+            END DO
+            IF (ikt .GE. 2) ziceload(ji,jj) = ziceload(ji,jj) + (2._wp * znad + zrhdtop_isf(ji,jj) + rhd(ji,jj,ikt-1)) &
+                               &                              * ( risfdep(ji,jj) - gdept_1d(ikt-1) )
+         END DO
+      END DO
+      riceload(:,:) = 0.0_wp ; riceload(:,:)=ziceload(:,:)  ! need to be saved for diaar5
+      ! compute zp from z=0 to first T wet point (correction due to zps not yet applied)
       DO jj = 2, jpjm1
          DO ji = fs_2, fs_jpim1   ! vector opt.
-            ! hydrostatic pressure gradient along s-surfaces
-            zhpi(ji,jj,1) = zcoef0 / e1u(ji,jj) * ( fse3w(ji+1,jj  ,1) * ( znad + rhd(ji+1,jj  ,1) )   &
-               &                                  - fse3w(ji  ,jj  ,1) * ( znad + rhd(ji  ,jj  ,1) ) )
-            zhpj(ji,jj,1) = zcoef0 / e2v(ji,jj) * ( fse3w(ji  ,jj+1,1) * ( znad + rhd(ji  ,jj+1,1) )   &
-               &                                  - fse3w(ji  ,jj  ,1) * ( znad + rhd(ji  ,jj  ,1) ) )
-            ! s-coordinate pressure gradient correction
+            ikt=mikt(ji,jj) ; iktp1i=mikt(ji+1,jj); iktp1j=mikt(ji,jj+1)
+            ! hydrostatic pressure gradient along s-surfaces and ice shelf pressure
+            ! we assume ISF is in isostatic equilibrium
+            zhpi(ji,jj,1) = zcoef0 / e1u(ji,jj) * ( 0.5_wp * fse3w(ji+1,jj  ,iktp1i)                                    &
+               &                                  * ( 2._wp * znad + rhd(ji+1,jj  ,iktp1i) + zrhdtop_oce(ji+1,jj  ) )   &
+               &                                  - 0.5_wp * fse3w(ji  ,jj  ,ikt   )                                    &
+               &                                  * ( 2._wp * znad + rhd(ji  ,jj  ,ikt   ) + zrhdtop_oce(ji  ,jj  ) )   &
+               &                                  + ( ziceload(ji+1,jj) - ziceload(ji,jj))                              ) 
+            zhpj(ji,jj,1) = zcoef0 / e2v(ji,jj) * ( 0.5_wp * fse3w(ji  ,jj+1,iktp1j)                                    &
+               &                                  * ( 2._wp * znad + rhd(ji  ,jj+1,iktp1j) + zrhdtop_oce(ji  ,jj+1) )   &
+               &                                  - 0.5_wp * fse3w(ji  ,jj  ,ikt   )                                    & 
+               &                                  * ( 2._wp * znad + rhd(ji  ,jj  ,ikt   ) + zrhdtop_oce(ji  ,jj  ) )   &
+               &                                  + ( ziceload(ji,jj+1) - ziceload(ji,jj) )                             ) 
+            ! s-coordinate pressure gradient correction (=0 if z coordinate)
             zuap = -zcoef0 * ( rhd   (ji+1,jj,1) + rhd   (ji,jj,1) + 2._wp * znad )   &
                &           * ( fsde3w(ji+1,jj,1) - fsde3w(ji,jj,1) ) / e1u(ji,jj)
@@ -402,35 +461,155 @@
                &           * ( fsde3w(ji,jj+1,1) - fsde3w(ji,jj,1) ) / e2v(ji,jj)
             ! add to the general momentum trend
-            ua(ji,jj,1) = ua(ji,jj,1) + zhpi(ji,jj,1) + zuap
-            va(ji,jj,1) = va(ji,jj,1) + zhpj(ji,jj,1) + zvap
-         END DO
-      END DO
-
-      ! interior value (2=<jk=<jpkm1)
-      DO jk = 2, jpkm1
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+            ua(ji,jj,1) = ua(ji,jj,1) + (zhpi(ji,jj,1) + zuap) * umask(ji,jj,1)
+            va(ji,jj,1) = va(ji,jj,1) + (zhpj(ji,jj,1) + zvap) * vmask(ji,jj,1)
+         END DO
+      END DO
+!==================================================================================     
+!===== Compute partial cell contribution for the top cell ========================= 
+!==================================================================================
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            iku = miku(ji,jj) ; 
+            zpshpi(ji,jj)=0.0_wp ; zpshpj(ji,jj)=0.0_wp
+            ze3wu  = (gdepw_0(ji+1,jj,iku+1) - gdept_0(ji+1,jj,iku)) - (gdepw_0(ji,jj,iku+1) - gdept_0(ji,jj,iku))
+            ! u direction
+            IF ( iku .GT. 1 ) THEN
+               ! case iku
+               zhpi(ji,jj,iku)   =  zcoef0 / e1u(ji,jj) * ze3wu                                            &
+                      &                                 * ( rhd    (ji+1,jj,iku) + rhd   (ji,jj,iku)       &
+                      &                                   + SIGN(1._wp,ze3wu) * grui(ji,jj) + 2._wp * znad )
+               ! corrective term ( = 0 if z coordinate )
+               zuap              = -zcoef0 * ( arui(ji,jj) + 2._wp * znad ) * gzui(ji,jj) / e1u(ji,jj)
+               ! zhpi will be added in interior loop
+               ua(ji,jj,iku)     = ua(ji,jj,iku) + zuap
+               ! in case of 2 cell water column, need to save the pressure gradient to compute the bottom pressure  
+               IF (mbku(ji,jj) == iku + 1) zpshpi(ji,jj)  = zhpi(ji,jj,iku)
+
+               ! case iku + 1 (remove the zphi term added in the interior loop and compute the one corrected for zps)
+               zhpiint        =  zcoef0 / e1u(ji,jj)                                                               &    
+                  &           * (  fse3w(ji+1,jj  ,iku+1) * ( (rhd(ji+1,jj,iku+1) + znad)                          &
+                  &                                         + (rhd(ji+1,jj,iku  ) + znad) ) * tmask(ji+1,jj,iku)   &
+                  &              - fse3w(ji  ,jj  ,iku+1) * ( (rhd(ji  ,jj,iku+1) + znad)                          &
+                  &                                         + (rhd(ji  ,jj,iku  ) + znad) ) * tmask(ji  ,jj,iku)   )
+               zhpi(ji,jj,iku+1) =  zcoef0 / e1u(ji,jj) * ge3rui(ji,jj) - zhpiint 
+            END IF
+               
+            ! v direction
+            ikv = mikv(ji,jj)
+            ze3wv  = (gdepw_0(ji,jj+1,ikv+1) - gdept_0(ji,jj+1,ikv)) - (gdepw_0(ji,jj,ikv+1) - gdept_0(ji,jj,ikv))
+            IF ( ikv .GT. 1 ) THEN
+               ! case ikv
+               zhpj(ji,jj,ikv)   =  zcoef0 / e2v(ji,jj) * ze3wv                                            &
+                     &                                  * ( rhd(ji,jj+1,ikv) + rhd   (ji,jj,ikv)           &
+                     &                                    + SIGN(1._wp,ze3wv) * grvi(ji,jj) + 2._wp * znad )
+               ! corrective term ( = 0 if z coordinate )
+               zvap              = -zcoef0 * ( arvi(ji,jj) + 2._wp * znad ) * gzvi(ji,jj) / e2v(ji,jj)
+               ! zhpi will be added in interior loop
+               va(ji,jj,ikv)      = va(ji,jj,ikv) + zvap
+               ! in case of 2 cell water column, need to save the pressure gradient to compute the bottom pressure  
+               IF (mbkv(ji,jj) == ikv + 1)  zpshpj(ji,jj)  =  zhpj(ji,jj,ikv) 
+               
+               ! case ikv + 1 (remove the zphj term added in the interior loop and compute the one corrected for zps)
+               zhpjint        =  zcoef0 / e2v(ji,jj)                                                              &
+                  &           * (  fse3w(ji  ,jj+1,ikv+1) * ( (rhd(ji,jj+1,ikv+1) + znad)                         &
+                  &                                       + (rhd(ji,jj+1,ikv  ) + znad) ) * tmask(ji,jj+1,ikv)    &
+                  &              - fse3w(ji  ,jj  ,ikv+1) * ( (rhd(ji,jj  ,ikv+1) + znad)                         &
+                  &                                       + (rhd(ji,jj  ,ikv  ) + znad) ) * tmask(ji,jj  ,ikv)  )
+               zhpj(ji,jj,ikv+1) =  zcoef0 / e2v(ji,jj) * ge3rvi(ji,jj) - zhpjint
+            END IF
+         END DO
+      END DO
+
+!==================================================================================     
+!===== Compute interior value ===================================================== 
+!==================================================================================
+
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            iku=miku(ji,jj); ikv=mikv(ji,jj)
+            DO jk = 2, jpkm1
                ! hydrostatic pressure gradient along s-surfaces
-               zhpi(ji,jj,jk) = zhpi(ji,jj,jk-1) + zcoef0 / e1u(ji,jj)   &
-                  &           * (  fse3w(ji+1,jj,jk) * ( rhd(ji+1,jj,jk) + rhd(ji+1,jj,jk-1) + 2*znad )   &
-                  &              - fse3w(ji  ,jj,jk) * ( rhd(ji  ,jj,jk) + rhd(ji  ,jj,jk-1) + 2*znad )  )
-               zhpj(ji,jj,jk) = zhpj(ji,jj,jk-1) + zcoef0 / e2v(ji,jj)   &
-                  &           * (  fse3w(ji,jj+1,jk) * ( rhd(ji,jj+1,jk) + rhd(ji,jj+1,jk-1) + 2*znad )   &
-                  &              - fse3w(ji,jj  ,jk) * ( rhd(ji,jj,  jk) + rhd(ji,jj  ,jk-1) + 2*znad )  )
+               ! zhpi is masked for the first wet cell  (contribution already done in the upper bloc)
+               zhpi(ji,jj,jk) = zhpi(ji,jj,jk) + zhpi(ji,jj,jk-1)                                                              &
+                  &                            + zcoef0 / e1u(ji,jj)                                                           &
+                  &                                     * ( fse3w(ji+1,jj  ,jk) * ( (rhd(ji+1,jj,jk  ) + znad)                 &
+                  &                                                     + (rhd(ji+1,jj,jk-1) + znad) ) * tmask(ji+1,jj,jk-1)   &
+                  &                                       - fse3w(ji  ,jj  ,jk) * ( (rhd(ji  ,jj,jk  ) + znad)                 &
+                  &                                                     + (rhd(ji  ,jj,jk-1) + znad) ) * tmask(ji  ,jj,jk-1)   ) 
                ! s-coordinate pressure gradient correction
-               zuap = -zcoef0 * ( rhd   (ji+1,jj  ,jk) + rhd   (ji,jj,jk) + 2._wp * znad )   &
-                  &           * ( fsde3w(ji+1,jj  ,jk) - fsde3w(ji,jj,jk) ) / e1u(ji,jj)
-               zvap = -zcoef0 * ( rhd   (ji  ,jj+1,jk) + rhd   (ji,jj,jk) + 2._wp * znad )   &
-                  &           * ( fsde3w(ji  ,jj+1,jk) - fsde3w(ji,jj,jk) ) / e2v(ji,jj)
+               ! corrective term, we mask this term for the first wet level beneath the ice shelf (contribution done in the upper bloc) 
+               zuap = - zcoef0 * ( rhd   (ji+1,jj  ,jk) + rhd   (ji,jj,jk) + 2._wp * znad )                    &
+                  &            * ( fsde3w(ji+1,jj  ,jk) - fsde3w(ji,jj,jk) ) / e1u(ji,jj) * umask(ji,jj,jk-1)
+               ua(ji,jj,jk) = ua(ji,jj,jk) + ( zhpi(ji,jj,jk) + zuap) * umask(ji,jj,jk)
+
+               ! hydrostatic pressure gradient along s-surfaces
+               ! zhpi is masked for the first wet cell  (contribution already done in the upper bloc)
+               zhpj(ji,jj,jk) = zhpj(ji,jj,jk) + zhpj(ji,jj,jk-1)                                                              &
+                  &                            + zcoef0 / e2v(ji,jj)                                                           &
+                  &                                     * ( fse3w(ji  ,jj+1,jk) * ( (rhd(ji,jj+1,jk  ) + znad)                 &
+                  &                                                     + (rhd(ji,jj+1,jk-1) + znad) ) * tmask(ji,jj+1,jk-1)   &
+                  &                                       - fse3w(ji  ,jj  ,jk) * ( (rhd(ji,jj  ,jk  ) + znad)                 &
+                  &                                                     + (rhd(ji,jj  ,jk-1) + znad) ) * tmask(ji,jj  ,jk-1)   )
+               ! s-coordinate pressure gradient correction
+               ! corrective term, we mask this term for the first wet level beneath the ice shelf (contribution done in the upper bloc)
+               zvap = - zcoef0 * ( rhd   (ji  ,jj+1,jk) + rhd   (ji,jj,jk) + 2._wp * znad )                     &
+                  &            * ( fsde3w(ji  ,jj+1,jk) - fsde3w(ji,jj,jk) ) / e2v(ji,jj) * vmask(ji,jj,jk-1)
                ! add to the general momentum trend
-               ua(ji,jj,jk) = ua(ji,jj,jk) + zhpi(ji,jj,jk) + zuap
-               va(ji,jj,jk) = va(ji,jj,jk) + zhpj(ji,jj,jk) + zvap
+               va(ji,jj,jk) = va(ji,jj,jk) + ( zhpj(ji,jj,jk) + zvap ) * vmask(ji,jj,jk)
             END DO
          END DO
       END DO
-      !
-      CALL wrk_dealloc( jpi,jpj,jpk, zhpi, zhpj )
+
+!==================================================================================     
+!===== Compute bottom cell contribution (partial cell) ============================ 
+!==================================================================================
+
+# if defined key_vectopt_loop
+         jj = 1
+         DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
+# else
+      DO jj = 2, jpjm1
+         DO ji = 2, jpim1
+# endif
+            iku = mbku(ji,jj)
+            ikv = mbkv(ji,jj)
+
+            IF (iku .GT. 1) THEN
+               ! remove old value (interior case)
+               zuap            = -zcoef0 * ( rhd   (ji+1,jj  ,iku) + rhd   (ji,jj,iku) + 2._wp * znad )   &
+                     &                   * ( fsde3w(ji+1,jj  ,iku) - fsde3w(ji,jj,iku) ) / e1u(ji,jj)
+               ua(ji,jj,iku)   = ua(ji,jj,iku) - zhpi(ji,jj,iku) - zuap
+               ! put new value
+               ! -zpshpi to avoid double contribution of the partial step in the top layer 
+               zuap            = -zcoef0 * ( aru(ji,jj) + 2._wp * znad ) * gzu(ji,jj)  / e1u(ji,jj)
+               zhpi(ji,jj,iku) =  zhpi(ji,jj,iku-1) + zcoef0 / e1u(ji,jj) * ge3ru(ji,jj) - zpshpi(ji,jj) 
+               ua(ji,jj,iku)   =  ua(ji,jj,iku) + zhpi(ji,jj,iku) + zuap
+            END IF
+            ! v direction
+            IF (ikv .GT. 1) THEN
+               ! remove old value (interior case)
+               zvap            = -zcoef0 * ( rhd   (ji  ,jj+1,ikv) + rhd   (ji,jj,ikv) + 2._wp * znad )   &
+                     &                   * ( fsde3w(ji  ,jj+1,ikv) - fsde3w(ji,jj,ikv) )   / e2v(ji,jj)
+               va(ji,jj,ikv)   = va(ji,jj,ikv) - zhpj(ji,jj,ikv) - zvap
+               ! put new value
+               ! -zpshpj to avoid double contribution of the partial step in the top layer 
+               zvap            = -zcoef0 * ( arv(ji,jj) + 2._wp * znad ) * gzv(ji,jj)     / e2v(ji,jj)
+               zhpj(ji,jj,ikv) =  zhpj(ji,jj,ikv-1) + zcoef0 / e2v(ji,jj) * ge3rv(ji,jj) - zpshpj(ji,jj)   
+               va(ji,jj,ikv)   =  va(ji,jj,ikv) + zhpj(ji,jj,ikv) + zvap
+            END IF
+# if ! defined key_vectopt_loop
+         END DO
+# endif
+      END DO
+     
+      ! set back to original density value into the ice shelf cell (maybe useless because it is masked)
+      rhd = zrhd
+      !
+      CALL wrk_dealloc( jpi,jpj,2, ztstop)
+      CALL wrk_dealloc( jpi,jpj,jpk, zhpi, zhpj, zrhd)
+      CALL wrk_dealloc( jpi,jpj, ze3w, zp, zrhdtop_isf, zrhdtop_oce, ziceload, zdept, zpshpi, zpshpj)
       !
    END SUBROUTINE hpg_sco
+
 
    SUBROUTINE hpg_djc( kt )
@@ -671,6 +850,4 @@
       !!
       !! ** Action : - Update (ua,va) with the now hydrastatic pressure trend
-      !!             - Save the trend (l_trddyn=T)
-      !!
       !!----------------------------------------------------------------------
       INTEGER, PARAMETER  :: polynomial_type = 1    ! 1: cubic spline, 2: linear
@@ -724,13 +901,19 @@
 
       ! Transfer the depth of "T(:,:,:)" to vertical coordinate "zdept(:,:,:)"
-      DO jj = 1, jpj;   DO ji = 1, jpi
-          zdept(ji,jj,1) = 0.5_wp * fse3w(ji,jj,1) - sshn(ji,jj) * znad
-      END DO        ;   END DO
-
-      DO jk = 2, jpk;   DO jj = 1, jpj;   DO ji = 1, jpi
-          zdept(ji,jj,jk) = zdept(ji,jj,jk-1) + fse3w(ji,jj,jk)
-      END DO        ;   END DO        ;   END DO
-
-      fsp(:,:,:) = zrhh(:,:,:)
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zdept(ji,jj,1) = 0.5_wp * fse3w(ji,jj,1) - sshn(ji,jj) * znad
+         END DO
+      END DO
+
+      DO jk = 2, jpk
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zdept(ji,jj,jk) = zdept(ji,jj,jk-1) + fse3w(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+      fsp(:,:,:) = zrhh (:,:,:)
       xsp(:,:,:) = zdept(:,:,:)
 
@@ -933,4 +1116,5 @@
    END SUBROUTINE hpg_prj
 
+
    SUBROUTINE cspline(fsp, xsp, asp, bsp, csp, dsp, polynomial_type)
       !!----------------------------------------------------------------------
@@ -940,6 +1124,6 @@
       !!
       !! ** Method  :   f(x) = asp + bsp*x + csp*x^2 + dsp*x^3
+      !!
       !! Reference: CJC Kruger, Constrained Cubic Spline Interpoltation
-      !!
       !!----------------------------------------------------------------------
       IMPLICIT NONE
@@ -949,6 +1133,5 @@
       INTEGER, INTENT(in) :: polynomial_type                        ! 1: cubic spline
                                                                     ! 2: Linear
-
-      ! Local Variables
+      !
       INTEGER  ::   ji, jj, jk                 ! dummy loop indices
       INTEGER  ::   jpi, jpj, jpkm1
@@ -1040,5 +1223,4 @@
       ENDIF
 
-
    END SUBROUTINE cspline
 
@@ -1050,8 +1232,6 @@
       !! ** Purpose :   1-d linear interpolation
       !!
-      !! ** Method  :
-      !!                interpolation is straight forward
+      !! ** Method  :   interpolation is straight forward
       !!                extrapolation is also permitted (no value limit)
-      !!
       !!----------------------------------------------------------------------
       IMPLICIT NONE
@@ -1070,4 +1250,5 @@
    END FUNCTION interp1
 
+
    FUNCTION interp2(x, a, b, c, d)  RESULT(f)
       !!----------------------------------------------------------------------
@@ -1133,5 +1314,4 @@
    END FUNCTION integ_spline
 
-
    !!======================================================================
 END MODULE dynhpg
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynkeg.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynkeg.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynkeg.F90	(revision 5075)
@@ -14,6 +14,7 @@
    USE oce             ! ocean dynamics and tracers
    USE dom_oce         ! ocean space and time domain
-   USE trdmod          ! ocean dynamics trends 
-   USE trdmod_oce      ! ocean variables trends
+   USE trd_oce         ! trends: ocean variables
+   USE trddyn          ! trend manager: dynamics
+   !
    USE in_out_manager  ! I/O manager
    USE lib_mpp         ! MPP library
@@ -52,8 +53,8 @@
       !!
       !! ** Action : - Update the (ua, va) with the hor. ke gradient trend
-      !!             - save this trends (l_trddyn=T) for post-processing
+      !!             - send this trends to trd_dyn (l_trddyn=T) for post-processing
       !!----------------------------------------------------------------------
       INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
-      !!
+      !
       INTEGER  ::   ji, jj, jk   ! dummy loop indices
       REAL(wp) ::   zu, zv       ! temporary scalars
@@ -131,5 +132,5 @@
          ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
          ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-         CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_keg, 'DYN', kt )
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_keg, kt )
          CALL wrk_dealloc( jpi,jpj,jpk, ztrdu, ztrdv )
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf.F90	(revision 5075)
@@ -15,4 +15,5 @@
    USE phycst         ! physical constants
    USE ldfdyn_oce     ! ocean dynamics lateral physics
+   USE ldftra_oce     ! ocean tracers  lateral physics
    USE ldfslp         ! lateral mixing: slopes of mixing orientation
    USE dynldf_bilapg  ! lateral mixing            (dyn_ldf_bilapg routine)
@@ -20,7 +21,7 @@
    USE dynldf_iso     ! lateral mixing            (dyn_ldf_iso    routine)
    USE dynldf_lap     ! lateral mixing            (dyn_ldf_lap    routine)
-   USE ldftra_oce, ONLY: ln_traldf_hor     ! ocean tracers lateral physics
-   USE trdmod         ! ocean dynamics and tracer trends
-   USE trdmod_oce     ! ocean variables trends
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics   (trd_dyn        routine)
+   !
    USE prtctl         ! Print control
    USE in_out_manager ! I/O manager
@@ -30,5 +31,4 @@
    USE timing          ! Timing
 
-
    IMPLICIT NONE
    PRIVATE
@@ -55,5 +55,4 @@
       !! ** Purpose :   compute the lateral ocean dynamics physics.
       !!----------------------------------------------------------------------
-      !
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
       !
@@ -107,5 +106,5 @@
          ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
          ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-         CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_ldf, 'DYN', kt )
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_ldf, kt )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdu, ztrdv )
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilap.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilap.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilap.F90	(revision 5075)
@@ -19,7 +19,6 @@
    USE dom_oce         ! ocean space and time domain
    USE ldfdyn_oce      ! ocean dynamics: lateral physics
+   !
    USE in_out_manager  ! I/O manager
-   USE trdmod          ! ocean dynamics trends 
-   USE trdmod_oce      ! ocean variables trends
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
    USE wrk_nemo        ! Memory Allocation
@@ -70,11 +69,8 @@
       !!      Add this before trend to the general trend (ua,va):
       !!            (ua,va) = (ua,va) + (diffu,diffv)
-      !!      'key_trddyn' defined: the two components of the horizontal
-      !!                               diffusion trend are saved.
       !!
       !! ** Action : - Update (ua,va) with the before iso-level biharmonic
       !!               mixing trend.
       !!----------------------------------------------------------------------
-      !
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilapg.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilapg.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_bilapg.F90	(revision 5075)
@@ -19,9 +19,8 @@
    USE dom_oce         ! ocean space and time domain
    USE ldfdyn_oce      ! ocean dynamics lateral physics
+   USE zdf_oce         ! ocean vertical physics
+   USE ldfslp          ! iso-neutral slopes available
    USE ldftra_oce, ONLY: ln_traldf_iso
-   USE zdf_oce         ! ocean vertical physics
-   USE trdmod          ! ocean dynamics trends 
-   USE trdmod_oce      ! ocean variables trends
-   USE ldfslp          ! iso-neutral slopes available
+   !
    USE in_out_manager  ! I/O manager
    USE lib_mpp         ! MPP library
@@ -81,9 +80,7 @@
       !!         -3- Add this trend to the general trend (ta,sa):
       !!            (ua,va) = (ua,va) + (zwk3,zwk4)
-      !!      'key_trddyn' defined: the trend is saved for diagnostics.
       !!
       !! ** Action  : - Update (ua,va) arrays with the before geopotential
       !!                biharmonic mixing trend.
-      !!              - save the trend in (zwk3,zwk4) ('key_trddyn')
       !!----------------------------------------------------------------------
       INTEGER, INTENT( in ) ::   kt           ! ocean time-step index
@@ -201,7 +198,5 @@
       !!                          pu and pv (all the components except
       !!                          second order vertical derivative term)
-      !!      'key_trddyn' defined: the trend is saved for diagnostics.
-      !!----------------------------------------------------------------------
-      !!
+      !!----------------------------------------------------------------------
       REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pu , pv    ! 1st call: before horizontal velocity 
       !                                                               ! 2nd call: ahm x these fields
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_iso.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_iso.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_iso.F90	(revision 5075)
@@ -22,7 +22,6 @@
    USE ldftra_oce      ! ocean tracer   lateral physics
    USE zdf_oce         ! ocean vertical physics
-   USE trdmod          ! ocean dynamics trends 
-   USE trdmod_oce      ! ocean variables trends
    USE ldfslp          ! iso-neutral slopes 
+   !
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
    USE in_out_manager  ! I/O manager
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_lap.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_lap.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynldf_lap.F90	(revision 5075)
@@ -19,8 +19,6 @@
    USE ldfdyn_oce      ! ocean dynamics: lateral physics
    USE zdf_oce         ! ocean vertical physics
+   !
    USE in_out_manager  ! I/O manager
-   USE trdmod          ! ocean dynamics trends 
-   USE trdmod_oce      ! ocean variables trends
-   USE ldfslp          ! iso-neutral slopes 
    USE timing          ! Timing
 
@@ -57,9 +55,6 @@
       !!      Add this before trend to the general trend (ua,va):
       !!            (ua,va) = (ua,va) + (diffu,diffv)
-      !!      'key_trddyn' activated: the two components of the horizontal
-      !!                                 diffusion trend are saved.
       !!
-      !! ** Action : - Update (ua,va) with the before iso-level harmonic 
-      !!               mixing trend.
+      !! ** Action : - Update (ua,va) with the iso-level harmonic mixing trend
       !!----------------------------------------------------------------------
       INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynnxt.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynnxt.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynnxt.F90	(revision 5075)
@@ -18,4 +18,5 @@
    !!            3.3  !  2011-03  (P. Oddo) Bug fix for time-splitting+(BDY-OBC) and not VVL
    !!            3.5  !  2013-07  (J. Chanut) Compliant with time splitting changes
+   !!            3.7  !  2014-04  (G. Madec) add the diagnostic of the time filter trends
    !!-------------------------------------------------------------------------
   
@@ -34,14 +35,18 @@
    USE bdydyn          ! ocean open boundary conditions
    USE bdyvol          ! ocean open boundary condition (bdy_vol routines)
+   USE trd_oce         ! trends: ocean variables
+   USE trddyn          ! trend manager: dynamics
+   USE trdken          ! trend manager: kinetic energy
+   !
    USE in_out_manager  ! I/O manager
+   USE iom             ! I/O manager library
    USE lbclnk          ! lateral boundary condition (or mpp link)
    USE lib_mpp         ! MPP library
    USE wrk_nemo        ! Memory Allocation
    USE prtctl          ! Print control
-
+   USE timing          ! Timing
 #if defined key_agrif
    USE agrif_opa_interp
 #endif
-   USE timing          ! Timing
 
    IMPLICIT NONE
@@ -79,5 +84,5 @@
       !!             at the local domain boundaries through lbc_lnk call,
       !!             at the one-way open boundaries (lk_bdy=T),
-      !!             at the AGRIF zoom     boundaries (lk_agrif=T)
+      !!             at the AGRIF zoom   boundaries (lk_agrif=T)
       !!
       !!              * Apply the time filter applied and swap of the dynamics
@@ -99,14 +104,14 @@
       REAL(wp) ::   z2dt         ! temporary scalar
 #endif
-      REAL(wp) ::   zue3a, zue3n, zue3b, zuf, zec   ! local scalars
-      REAL(wp) ::   zve3a, zve3n, zve3b, zvf        !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:)   ::  zua, zva
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ze3u_f, ze3v_f 
+      REAL(wp) ::   zue3a, zue3n, zue3b, zuf, zec      ! local scalars
+      REAL(wp) ::   zve3a, zve3n, zve3b, zvf, z1_2dt   !   -      -
+      REAL(wp), POINTER, DIMENSION(:,:)   ::  zue, zve
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ze3u_f, ze3v_f, zua, zva 
       !!----------------------------------------------------------------------
       !
-      IF( nn_timing == 1 )  CALL timing_start('dyn_nxt')
-      !
-      CALL wrk_alloc( jpi,jpj,jpk, ze3u_f, ze3v_f )
-      IF ( lk_dynspg_ts ) CALL wrk_alloc( jpi,jpj, zua, zva )
+      IF( nn_timing == 1 )   CALL timing_start('dyn_nxt')
+      !
+      CALL wrk_alloc( jpi,jpj,jpk,  ze3u_f, ze3v_f, zua, zva )
+      IF( lk_dynspg_ts )   CALL wrk_alloc( jpi,jpj, zue, zve )
       !
       IF( kt == nit000 ) THEN
@@ -152,15 +157,16 @@
 
 # if defined key_dynspg_ts
+!!gm IF ( lk_dynspg_ts ) THEN ....
       ! Ensure below that barotropic velocities match time splitting estimate
       ! Compute actual transport and replace it with ts estimate at "after" time step
-      zua(:,:) = 0._wp
-      zva(:,:) = 0._wp
-      DO jk = 1, jpkm1
-         zua(:,:) = zua(:,:) + fse3u_a(:,:,jk) * ua(:,:,jk) * umask(:,:,jk)
-         zva(:,:) = zva(:,:) + fse3v_a(:,:,jk) * va(:,:,jk) * vmask(:,:,jk)
+      zue(:,:) = fse3u_a(:,:,1) * ua(:,:,1) * umask(:,:,1)
+      zve(:,:) = fse3v_a(:,:,1) * va(:,:,1) * vmask(:,:,1)
+      DO jk = 2, jpkm1
+         zue(:,:) = zue(:,:) + fse3u_a(:,:,jk) * ua(:,:,jk) * umask(:,:,jk)
+         zve(:,:) = zve(:,:) + fse3v_a(:,:,jk) * va(:,:,jk) * vmask(:,:,jk)
       END DO
       DO jk = 1, jpkm1
-         ua(:,:,jk) = ( ua(:,:,jk) - zua(:,:) * hur_a(:,:) + ua_b(:,:) ) * umask(:,:,jk)
-         va(:,:,jk) = ( va(:,:,jk) - zva(:,:) * hvr_a(:,:) + va_b(:,:) ) * vmask(:,:,jk)
+         ua(:,:,jk) = ( ua(:,:,jk) - zue(:,:) * hur_a(:,:) + ua_b(:,:) ) * umask(:,:,jk)
+         va(:,:,jk) = ( va(:,:,jk) - zve(:,:) * hvr_a(:,:) + va_b(:,:) ) * vmask(:,:,jk)
       END DO
 
@@ -175,4 +181,5 @@
          END DO  
       ENDIF
+!!gm ENDIF
 # endif
 
@@ -195,4 +202,23 @@
 # endif
 #endif
+
+      IF( l_trddyn ) THEN             ! prepare the atf trend computation + some diagnostics
+         z1_2dt = 1._wp / (2. * rdt)        ! Euler or leap-frog time step 
+         IF( neuler == 0 .AND. kt == nit000 )   z1_2dt = 1._wp / rdt
+         !
+         !                                  ! Kinetic energy and Conversion
+         IF( ln_KE_trd  )   CALL trd_dyn( ua, va, jpdyn_ken, kt )
+         !
+         IF( ln_dyn_trd ) THEN              ! 3D output: total momentum trends
+            zua(:,:,:) = ( ua(:,:,:) - ub(:,:,:) ) * z1_2dt
+            zva(:,:,:) = ( va(:,:,:) - vb(:,:,:) ) * z1_2dt
+            CALL iom_put( "utrd_tot", zua )        ! total momentum trends, except the asselin time filter
+            CALL iom_put( "vtrd_tot", zva )
+         ENDIF
+         !
+         zua(:,:,:) = un(:,:,:)             ! save the now velocity before the asselin filter
+         zva(:,:,:) = vn(:,:,:)             ! (caution: there will be a shift by 1 timestep in the
+         !                                  !  computation of the asselin filter trends)
+      ENDIF
 
       ! Time filter and swap of dynamics arrays
@@ -217,6 +243,6 @@
                DO jj = 1, jpj
                   DO ji = 1, jpi    
-                     zuf = un(ji,jj,jk) + atfp * ( ub(ji,jj,jk) - 2.e0_wp * un(ji,jj,jk) + ua(ji,jj,jk) )
-                     zvf = vn(ji,jj,jk) + atfp * ( vb(ji,jj,jk) - 2.e0_wp * vn(ji,jj,jk) + va(ji,jj,jk) )
+                     zuf = un(ji,jj,jk) + atfp * ( ub(ji,jj,jk) - 2._wp * un(ji,jj,jk) + ua(ji,jj,jk) )
+                     zvf = vn(ji,jj,jk) + atfp * ( vb(ji,jj,jk) - 2._wp * vn(ji,jj,jk) + va(ji,jj,jk) )
                      !
                      ub(ji,jj,jk) = zuf                      ! ub <-- filtered velocity
@@ -301,13 +327,13 @@
             ! Revert "before" velocities to time split estimate
             ! Doing it here also means that asselin filter contribution is removed  
-            zua(:,:) = 0._wp
-            zva(:,:) = 0._wp
-            DO jk = 1, jpkm1
-               zua(:,:) = zua(:,:) + fse3u_b(:,:,jk) * ub(:,:,jk) * umask(:,:,jk)
-               zva(:,:) = zva(:,:) + fse3v_b(:,:,jk) * vb(:,:,jk) * vmask(:,:,jk)    
+            zue(:,:) = fse3u_b(:,:,1) * ub(:,:,1) * umask(:,:,1)
+            zve(:,:) = fse3v_b(:,:,1) * vb(:,:,1) * vmask(:,:,1)    
+            DO jk = 2, jpkm1
+               zue(:,:) = zue(:,:) + fse3u_b(:,:,jk) * ub(:,:,jk) * umask(:,:,jk)
+               zve(:,:) = zve(:,:) + fse3v_b(:,:,jk) * vb(:,:,jk) * vmask(:,:,jk)    
             END DO
             DO jk = 1, jpkm1
-               ub(:,:,jk) = ub(:,:,jk) - (zua(:,:) * hur(:,:) - un_b(:,:)) * umask(:,:,jk)
-               vb(:,:,jk) = vb(:,:,jk) - (zva(:,:) * hvr(:,:) - vn_b(:,:)) * vmask(:,:,jk)
+               ub(:,:,jk) = ub(:,:,jk) - (zue(:,:) * hur(:,:) - un_b(:,:)) * umask(:,:,jk)
+               vb(:,:,jk) = vb(:,:,jk) - (zve(:,:) * hvr(:,:) - vn_b(:,:)) * vmask(:,:,jk)
             END DO
          ENDIF
@@ -327,6 +353,6 @@
             hv_b(:,:) = hv_b(:,:) + fse3v_b(:,:,jk) * vmask(:,:,jk)
          END DO
-         hur_b(:,:) = umask(:,:,1) / ( hu_b(:,:) + 1. - umask(:,:,1) )
-         hvr_b(:,:) = vmask(:,:,1) / ( hv_b(:,:) + 1. - vmask(:,:,1) )
+         hur_b(:,:) = umask_i(:,:) / ( hu_b(:,:) + 1._wp - umask_i(:,:) )
+         hvr_b(:,:) = vmask_i(:,:) / ( hv_b(:,:) + 1._wp - vmask_i(:,:) )
       ENDIF
       !
@@ -335,11 +361,6 @@
       !
       DO jk = 1, jpkm1
-#if defined key_vectopt_loop
-         DO jj = 1, 1         !Vector opt. => forced unrolling
-            DO ji = 1, jpij
-#else 
          DO jj = 1, jpj
             DO ji = 1, jpi
-#endif                  
                un_b(ji,jj) = un_b(ji,jj) + fse3u_a(ji,jj,jk) * un(ji,jj,jk) * umask(ji,jj,jk)
                vn_b(ji,jj) = vn_b(ji,jj) + fse3v_a(ji,jj,jk) * vn(ji,jj,jk) * vmask(ji,jj,jk)
@@ -358,9 +379,16 @@
       !
       !
+
+      IF( l_trddyn ) THEN                ! 3D output: asselin filter trends on momentum
+         zua(:,:,:) = ( ub(:,:,:) - zua(:,:,:) ) * z1_2dt
+         zva(:,:,:) = ( vb(:,:,:) - zva(:,:,:) ) * z1_2dt
+         CALL trd_dyn( zua, zva, jpdyn_atf, kt )
+      ENDIF
+      !
       IF(ln_ctl)   CALL prt_ctl( tab3d_1=un, clinfo1=' nxt  - Un: ', mask1=umask,   &
          &                       tab3d_2=vn, clinfo2=' Vn: '       , mask2=vmask )
       ! 
-      CALL wrk_dealloc( jpi,jpj,jpk, ze3u_f, ze3v_f )
-      IF ( lk_dynspg_ts ) CALL wrk_dealloc( jpi,jpj, zua, zva )
+      CALL wrk_dealloc( jpi,jpj,jpk,  ze3u_f, ze3v_f, zua, zva )
+      IF( lk_dynspg_ts )   CALL wrk_dealloc( jpi,jpj, zue, zve )
       !
       IF( nn_timing == 1 )  CALL timing_stop('dyn_nxt')
@@ -370,3 +398,2 @@
    !!=========================================================================
 END MODULE dynnxt
-
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg.F90	(revision 5075)
@@ -26,12 +26,13 @@
    USE sbctide
    USE updtide
-   USE trdmod         ! ocean dynamics trends
-   USE trdmod_oce     ! ocean variables trends
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics
+   !
    USE prtctl         ! Print control                     (prt_ctl routine)
    USE in_out_manager ! I/O manager
    USE lib_mpp        ! MPP library
-   USE solver          ! solver initialization
-   USE wrk_nemo        ! Memory Allocation
-   USE timing          ! Timing
+   USE solver         ! solver initialization
+   USE wrk_nemo       ! Memory Allocation
+   USE timing         ! Timing
 
 
@@ -163,5 +164,8 @@
                END DO
             END DO
-         END DO         
+         END DO    
+         
+!!gm add here a call to dyn_trd for ice pressure gradient, the surf pressure trends ????
+              
       ENDIF
 
@@ -191,9 +195,9 @@
          CASE( 2 )
             z2dt = 2. * rdt
-            IF( neuler == 0 .AND. kt == nit000 ) z2dt = rdt
+            IF( neuler == 0 .AND. kt == nit000 )   z2dt = rdt
             ztrdu(:,:,:) = ( ua(:,:,:) - ub(:,:,:) ) / z2dt - ztrdu(:,:,:)
             ztrdv(:,:,:) = ( va(:,:,:) - vb(:,:,:) ) / z2dt - ztrdv(:,:,:)
          END SELECT
-         CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_spg, 'DYN', kt )
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_spg, kt )
          !
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdu, ztrdv ) 
@@ -246,4 +250,6 @@
       IF( ( ioptio > 1 .AND. .NOT. lk_esopa ) .OR. ( ioptio == 0 .AND. .NOT. lk_c1d ) )   &
            &   CALL ctl_stop( ' Choose only one surface pressure gradient scheme with a key cpp' )
+      IF( ( lk_dynspg_ts .OR. lk_dynspg_exp ) .AND. nn_isf .NE. 0 )   &
+           &   CALL ctl_stop( ' dynspg_ts and dynspg_exp not tested with ice shelf cavity ' )
       !
       IF( lk_esopa     )   nspg = -1
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_exp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_exp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_exp.F90	(revision 5075)
@@ -19,4 +19,5 @@
    USE sbc_oce         ! surface boundary condition: ocean
    USE phycst          ! physical constants
+   !
    USE in_out_manager  ! I/O manager
    USE lib_mpp         ! distributed memory computing library
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_flt.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_flt.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_flt.F90	(revision 5075)
@@ -13,4 +13,5 @@
    !!             -   !  2006-08  (J.Chanut, A.Sellar) Calls to BDY routines. 
    !!            3.2  !  2009-03  (G. Madec, M. Leclair, R. Benshila) introduce sshwzv module
+   !!            3.7  !  2014-04  (F. Roquet, G. Madec)  add some trends diag
    !!----------------------------------------------------------------------
 #if defined key_dynspg_flt   ||   defined key_esopa  
@@ -36,4 +37,7 @@
    USE bdyvol          ! ocean open boundary condition (bdy_vol routine)
    USE cla             ! cross land advection
+   USE trd_oce         ! trends: ocean variables
+   USE trddyn          ! trend manager: dynamics
+   !
    USE in_out_manager  ! I/O manager
    USE lib_mpp         ! distributed memory computing library
@@ -43,8 +47,8 @@
    USE iom
    USE lib_fortran
+   USE timing          ! Timing
 #if defined key_agrif
    USE agrif_opa_interp
 #endif
-   USE timing          ! Timing
 
    IMPLICIT NONE
@@ -99,15 +103,16 @@
       !! ** Action : - Update (ua,va) with the surf. pressure gradient trend
       !!
-      !! References : Roullet and Madec 1999, JGR.
+      !! References : Roullet and Madec, JGR, 2000.
       !!---------------------------------------------------------------------
       INTEGER, INTENT(in   ) ::   kt       ! ocean time-step index
       INTEGER, INTENT(  out) ::   kindic   ! solver convergence flag (<0 if not converge)
-      !!                                   
+      !
       INTEGER  ::   ji, jj, jk   ! dummy loop indices
       REAL(wp) ::   z2dt, z2dtg, zgcb, zbtd, ztdgu, ztdgv   ! local scalars
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztrdu, ztrdv
+      REAL(wp), POINTER, DIMENSION(:,:)   ::  zpw
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('dyn_spg_flt')
-      !
       !
       IF( kt == nit000 ) THEN
@@ -179,4 +184,17 @@
          END DO
          !
+         IF( l_trddyn )   THEN                      ! temporary save of spg trends
+            CALL wrk_alloc( jpi, jpj, jpk, ztrdu, ztrdv )
+            DO jk = 1, jpkm1              ! unweighted time stepping 
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1   ! vector opt.
+                     ztrdu(ji,jj,jk) = spgu(ji,jj) * umask(ji,jj,jk)
+                     ztrdv(ji,jj,jk) = spgv(ji,jj) * vmask(ji,jj,jk)
+                  END DO
+               END DO
+            END DO
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_spgexp, kt )
+         ENDIF
+         !
       ENDIF
 
@@ -194,31 +212,18 @@
       DO jj = 2, jpjm1
          DO ji = fs_2, fs_jpim1   ! vector opt.
-            spgu(ji,jj) = 0._wp
-            spgv(ji,jj) = 0._wp
-         END DO
-      END DO
-
-      ! vertical sum
-!CDIR NOLOOPCHG
-      IF( lk_vopt_loop ) THEN          ! vector opt., forced unroll
-         DO jk = 1, jpkm1
-            DO ji = 1, jpij
-               spgu(ji,1) = spgu(ji,1) + fse3u_a(ji,1,jk) * ua(ji,1,jk)
-               spgv(ji,1) = spgv(ji,1) + fse3v_a(ji,1,jk) * va(ji,1,jk)
-            END DO
-         END DO
-      ELSE                        ! No  vector opt.
-         DO jk = 1, jpkm1
-            DO jj = 2, jpjm1
-               DO ji = 2, jpim1
-                  spgu(ji,jj) = spgu(ji,jj) + fse3u_a(ji,jj,jk) * ua(ji,jj,jk)
-                  spgv(ji,jj) = spgv(ji,jj) + fse3v_a(ji,jj,jk) * va(ji,jj,jk)
-               END DO
-            END DO
-         END DO
-      ENDIF
-
-      ! transport: multiplied by the horizontal scale factor
-      DO jj = 2, jpjm1
+            spgu(ji,jj) = fse3u_a(ji,jj,1) * ua(ji,jj,1)
+            spgv(ji,jj) = fse3v_a(ji,jj,1) * va(ji,jj,1)
+         END DO
+      END DO
+      DO jk = 2, jpkm1                     ! vertical sum
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               spgu(ji,jj) = spgu(ji,jj) + fse3u_a(ji,jj,jk) * ua(ji,jj,jk)
+               spgv(ji,jj) = spgv(ji,jj) + fse3v_a(ji,jj,jk) * va(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+      DO jj = 2, jpjm1                     ! transport: multiplied by the horizontal scale factor
          DO ji = fs_2, fs_jpim1   ! vector opt.
             spgu(ji,jj) = spgu(ji,jj) * e2u(ji,jj)
@@ -322,4 +327,26 @@
       ENDIF
 #endif      
+
+      IF( l_trddyn )   THEN                     
+         ztrdu(:,:,:) = ua(:,:,:)                 ! save the after velocity before the filtered SPG
+         ztrdv(:,:,:) = va(:,:,:)
+         !
+         CALL wrk_alloc( jpi, jpj, zpw )
+         !
+         zpw(:,:) = - z2dt * gcx(:,:)
+         CALL iom_put( "ssh_flt" , zpw )          ! output equivalent ssh modification due to implicit filter
+         !
+         !                                        ! save surface pressure flux: -pw at z=0
+         zpw(:,:) = - rau0 * grav * sshn(:,:) * wn(:,:,1) * tmask(:,:,1)
+         CALL iom_put( "pw0_exp" , zpw )
+         zpw(:,:) = wn(:,:,1)
+         CALL iom_put( "w0" , zpw )
+         zpw(:,:) =  rau0 * z2dtg * gcx(:,:) * wn(:,:,1) * tmask(:,:,1)
+         CALL iom_put( "pw0_flt" , zpw )
+         !
+         CALL wrk_dealloc( jpi, jpj, zpw ) 
+         !                                   
+      ENDIF
+      
       ! Add the trends multiplied by z2dt to the after velocity
       ! -------------------------------------------------------
@@ -336,10 +363,15 @@
       END DO
 
-      ! write filtered free surface arrays in restart file
-      ! --------------------------------------------------
-      IF( lrst_oce ) CALL flt_rst( kt, 'WRITE' )
-      !
-      !
-      IF( nn_timing == 1 )  CALL timing_stop('dyn_spg_flt')
+      IF( l_trddyn )   THEN                      ! save the explicit SPG trends for further diagnostics
+         ztrdu(:,:,:) = ( ua(:,:,:) - ztrdu(:,:,:) ) / z2dt
+         ztrdv(:,:,:) = ( va(:,:,:) - ztrdv(:,:,:) ) / z2dt
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_spgflt, kt )
+         !
+         CALL wrk_dealloc( jpi, jpj, jpk, ztrdu, ztrdv ) 
+      ENDIF
+
+      IF( lrst_oce )   CALL flt_rst( kt, 'WRITE' )      ! write filtered free surface arrays in restart file
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('dyn_spg_flt')
       !
    END SUBROUTINE dyn_spg_flt
@@ -352,6 +384,6 @@
       !! ** Purpose : Read or write filtered free surface arrays in restart file
       !!----------------------------------------------------------------------
-      INTEGER         , INTENT(in) ::   kt         ! ocean time-step
-      CHARACTER(len=*), INTENT(in) ::   cdrw       ! "READ"/"WRITE" flag
+      INTEGER         , INTENT(in) ::   kt     ! ocean time-step
+      CHARACTER(len=*), INTENT(in) ::   cdrw   ! "READ"/"WRITE" flag
       !!----------------------------------------------------------------------
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_ts.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_ts.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynspg_ts.F90	(revision 5075)
@@ -44,5 +44,7 @@
    USE agrif_opa_interp ! agrif
 #endif
-
+#if defined key_asminc   
+   USE asminc          ! Assimilation increment
+#endif
 
    IMPLICIT NONE
@@ -95,6 +97,6 @@
       ALLOCATE( wgtbtp1(3*nn_baro), wgtbtp2(3*nn_baro), zwz(jpi,jpj), STAT= ierr(2) )
 
-      IF( ln_dynvor_een ) ALLOCATE( ftnw(jpi,jpj) , ftne(jpi,jpj) , & 
-                             &      ftsw(jpi,jpj) , ftse(jpi,jpj) , STAT=ierr(3) )
+      IF( ln_dynvor_een .or. ln_dynvor_een_old ) ALLOCATE( ftnw(jpi,jpj) , ftne(jpi,jpj) , & 
+                                                    &      ftsw(jpi,jpj) , ftse(jpi,jpj) , STAT=ierr(3) )
 
       dyn_spg_ts_alloc = MAXVAL(ierr(:))
@@ -216,5 +218,25 @@
       !
       IF ( kt == nit000 .OR. lk_vvl ) THEN
-         IF ( ln_dynvor_een ) THEN
+         IF ( ln_dynvor_een_old ) THEN
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  zwz(ji,jj) =   ( ht(ji  ,jj+1) + ht(ji+1,jj+1) +                    &
+                        &          ht(ji  ,jj  ) + ht(ji+1,jj  )   ) / 4._wp  
+                  IF( zwz(ji,jj) /= 0._wp )   zwz(ji,jj) = 1._wp / zwz(ji,jj)
+               END DO
+            END DO
+            CALL lbc_lnk( zwz, 'F', 1._wp )
+            zwz(:,:) = ff(:,:) * zwz(:,:)
+
+            ftne(1,:) = 0._wp ; ftnw(1,:) = 0._wp ; ftse(1,:) = 0._wp ; ftsw(1,:) = 0._wp
+            DO jj = 2, jpj
+               DO ji = fs_2, jpi   ! vector opt.
+                  ftne(ji,jj) = zwz(ji-1,jj  ) + zwz(ji  ,jj  ) + zwz(ji  ,jj-1)
+                  ftnw(ji,jj) = zwz(ji-1,jj-1) + zwz(ji-1,jj  ) + zwz(ji  ,jj  )
+                  ftse(ji,jj) = zwz(ji  ,jj  ) + zwz(ji  ,jj-1) + zwz(ji-1,jj-1)
+                  ftsw(ji,jj) = zwz(ji  ,jj-1) + zwz(ji-1,jj-1) + zwz(ji-1,jj  )
+               END DO
+            END DO
+         ELSE IF ( ln_dynvor_een ) THEN
             DO jj = 1, jpjm1
                DO ji = 1, jpim1
@@ -290,15 +312,6 @@
       !
       DO jk = 1, jpkm1
-#if defined key_vectopt_loop
-         DO jj = 1, 1         !Vector opt. => forced unrolling
-            DO ji = 1, jpij
-#else 
-         DO jj = 1, jpj
-            DO ji = 1, jpi
-#endif                                                                   
-               zu_frc(ji,jj) = zu_frc(ji,jj) + fse3u_n(ji,jj,jk) * ua(ji,jj,jk) * umask(ji,jj,jk)
-               zv_frc(ji,jj) = zv_frc(ji,jj) + fse3v_n(ji,jj,jk) * va(ji,jj,jk) * vmask(ji,jj,jk)         
-            END DO
-         END DO
+         zu_frc(:,:) = zu_frc(:,:) + fse3u_n(:,:,jk) * ua(:,:,jk) * umask(:,:,jk)
+         zv_frc(:,:) = zv_frc(:,:) + fse3v_n(:,:,jk) * va(:,:,jk) * vmask(:,:,jk)         
       END DO
       !
@@ -346,5 +359,5 @@
          END DO
          !
-      ELSEIF ( ln_dynvor_een ) THEN                    ! enstrophy and energy conserving scheme
+      ELSEIF ( ln_dynvor_een .or. ln_dynvor_een_old ) THEN  ! enstrophy and energy conserving scheme
          DO jj = 2, jpjm1
             DO ji = fs_2, fs_jpim1   ! vector opt.
@@ -464,4 +477,13 @@
       !                                             ! ==================== !  
       ! Initialize barotropic variables:      
+      IF( ll_init )THEN
+         sshbb_e(:,:) = 0._wp
+         ubb_e  (:,:) = 0._wp
+         vbb_e  (:,:) = 0._wp
+         sshb_e (:,:) = 0._wp
+         ub_e   (:,:) = 0._wp
+         vb_e   (:,:) = 0._wp
+      ENDIF
+      !
       IF (ln_bt_fw) THEN                  ! FORWARD integration: start from NOW fields                    
          sshn_e(:,:) = sshn (:,:)            
@@ -685,5 +707,5 @@
             END DO
             !
-         ELSEIF ( ln_dynvor_een ) THEN                    !==  energy and enstrophy conserving scheme  ==!
+         ELSEIF ( ln_dynvor_een .or. ln_dynvor_een_old ) THEN !==  energy and enstrophy conserving scheme  ==!
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1   ! vector opt.
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynvor.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynvor.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynvor.F90	(revision 5075)
@@ -15,4 +15,5 @@
    !!            3.2  ! 2009-04  (R. Benshila)  vvl: correction of een scheme
    !!            3.3  ! 2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
+   !!            3.7  ! 2014-04  (G. Madec) trend simplification: suppress jpdyn_trd_dat vorticity 
    !!----------------------------------------------------------------------
 
@@ -29,6 +30,6 @@
    USE dommsk         ! ocean mask
    USE dynadv         ! momentum advection (use ln_dynadv_vec value)
-   USE trdmod         ! ocean dynamics trends 
-   USE trdmod_oce     ! ocean variables trends
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics
    USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
    USE prtctl         ! Print control
@@ -50,4 +51,5 @@
    LOGICAL, PUBLIC ::   ln_dynvor_mix   !: mixed scheme
    LOGICAL, PUBLIC ::   ln_dynvor_een   !: energy and enstrophy conserving scheme
+   LOGICAL, PUBLIC ::   ln_dynvor_een_old !: energy and enstrophy conserving scheme (original formulation)
 
    INTEGER ::   nvor = 0   ! type of vorticity trend used
@@ -73,5 +75,6 @@
       !! ** Action : - Update (ua,va) with the now vorticity term trend
       !!             - save the trends in (ztrdu,ztrdv) in 2 parts (relative
-      !!               and planetary vorticity trends) ('key_trddyn')
+      !!               and planetary vorticity trends) and send them to trd_dyn 
+      !!               for futher diagnostics (l_trddyn=T)
       !!----------------------------------------------------------------------
       INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
@@ -108,5 +111,5 @@
             ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
             ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_rvo, 'DYN', kt )
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_rvo, kt )
             ztrdu(:,:,:) = ua(:,:,:)
             ztrdv(:,:,:) = va(:,:,:)
@@ -114,6 +117,5 @@
             ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
             ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_pvo, 'DYN', kt )
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_dat, 'DYN', kt )
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_pvo, kt )
          ELSE
             CALL vor_ene( kt, ntot, ua, va )                ! total vorticity
@@ -127,5 +129,5 @@
             ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
             ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_rvo, 'DYN', kt )
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_rvo, kt )
             ztrdu(:,:,:) = ua(:,:,:)
             ztrdv(:,:,:) = va(:,:,:)
@@ -133,6 +135,5 @@
             ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
             ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_pvo, 'DYN', kt )
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_dat, 'DYN', kt )
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_pvo, kt )
          ELSE
             CALL vor_ens( kt, ntot, ua, va )                ! total vorticity
@@ -146,5 +147,5 @@
             ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
             ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_rvo, 'DYN', kt )
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_rvo, kt )
             ztrdu(:,:,:) = ua(:,:,:)
             ztrdv(:,:,:) = va(:,:,:)
@@ -152,6 +153,5 @@
             ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
             ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_pvo, 'DYN', kt )
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_dat, 'DYN', kt )
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_pvo, kt )
          ELSE
             CALL vor_mix( kt )                               ! total vorticity (mix=ens-ene)
@@ -165,5 +165,5 @@
             ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
             ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_rvo, 'DYN', kt )
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_rvo, kt )
             ztrdu(:,:,:) = ua(:,:,:)
             ztrdv(:,:,:) = va(:,:,:)
@@ -171,6 +171,5 @@
             ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
             ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_pvo, 'DYN', kt )
-            CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_dat, 'DYN', kt )
+            CALL trd_dyn( ztrdu, ztrdv, jpdyn_pvo, kt )
          ELSE
             CALL vor_een( kt, ntot, ua, va )                ! total vorticity
@@ -211,6 +210,4 @@
       !!
       !! ** Action : - Update (ua,va) with the now vorticity term trend
-      !!             - save the trends in (ztrdu,ztrdv) in 2 parts (relative
-      !!               and planetary vorticity trends) ('key_trddyn')
       !!
       !! References : Sadourny, r., 1975, j. atmos. sciences, 32, 680-689.
@@ -328,6 +325,4 @@
       !!
       !! ** Action : - Update (ua,va) arrays with the now vorticity term trend
-      !!             - Save the trends in (ztrdu,ztrdv) in 2 parts (relative
-      !!               and planetary vorticity trends) ('key_trddyn')
       !!
       !! References : Sadourny, r., 1975, j. atmos. sciences, 32, 680-689.
@@ -444,6 +439,4 @@
       !!
       !! ** Action : - Update (ua,va) arrays with the now vorticity term trend
-      !!             - Save the trends in (ztrdu,ztrdv) in 2 parts (relative 
-      !!               and planetary vorticity trends) ('key_trddyn')
       !!
       !! References : Sadourny, r., 1975, j. atmos. sciences, 32, 680-689.
@@ -557,6 +550,4 @@
       !!
       !! ** Action : - Update (ua,va) with the now vorticity term trend
-      !!             - save the trends in (ztrdu,ztrdv) in 2 parts (relative
-      !!               and planetary vorticity trends) ('key_trddyn')
       !!
       !! References : Arakawa and Lamb 1980, Mon. Wea. Rev., 109, 18-36
@@ -601,20 +592,34 @@
             IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'dyn:vor_een : unable to allocate arrays' )
          ENDIF
-         ze3f(:,:,:) = 0.d0
+         ze3f(:,:,:) = 0._wp
 #endif
       ENDIF
 
       IF( kt == nit000 .OR. lk_vvl ) THEN      ! reciprocal of e3 at F-point (masked averaging of e3t over ocean points)
-         DO jk = 1, jpk
-            DO jj = 1, jpjm1
-               DO ji = 1, jpim1
-                  ze3  = ( fse3t(ji,jj+1,jk)*tmask(ji,jj+1,jk) + fse3t(ji+1,jj+1,jk)*tmask(ji+1,jj+1,jk)   &
-                     &   + fse3t(ji,jj  ,jk)*tmask(ji,jj  ,jk) + fse3t(ji+1,jj  ,jk)*tmask(ji+1,jj  ,jk) )
-                  zmsk = (                   tmask(ji,jj+1,jk) +                     tmask(ji+1,jj+1,jk)   &
-                     &                     + tmask(ji,jj  ,jk) +                     tmask(ji+1,jj  ,jk) )
-                  IF( ze3 /= 0._wp )   ze3f(ji,jj,jk) = zmsk / ze3
-               END DO
-            END DO
-         END DO
+
+         IF( ln_dynvor_een_old ) THEN ! original formulation
+            DO jk = 1, jpk
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpim1
+                     ze3  = ( fse3t(ji,jj+1,jk)*tmask(ji,jj+1,jk) + fse3t(ji+1,jj+1,jk)*tmask(ji+1,jj+1,jk)   &
+                        &   + fse3t(ji,jj  ,jk)*tmask(ji,jj  ,jk) + fse3t(ji+1,jj  ,jk)*tmask(ji+1,jj  ,jk) )
+                     IF( ze3 /= 0._wp )   ze3f(ji,jj,jk) = 4.0_wp / ze3
+                  END DO
+               END DO
+            END DO
+         ELSE ! new formulation from NEMO 3.6
+            DO jk = 1, jpk
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpim1
+                     ze3  = ( fse3t(ji,jj+1,jk)*tmask(ji,jj+1,jk) + fse3t(ji+1,jj+1,jk)*tmask(ji+1,jj+1,jk)   &
+                        &   + fse3t(ji,jj  ,jk)*tmask(ji,jj  ,jk) + fse3t(ji+1,jj  ,jk)*tmask(ji+1,jj  ,jk) )
+                     zmsk = (                   tmask(ji,jj+1,jk) +                     tmask(ji+1,jj+1,jk)   &
+                        &                     + tmask(ji,jj  ,jk) +                     tmask(ji+1,jj  ,jk) )
+                     IF( ze3 /= 0._wp )   ze3f(ji,jj,jk) = zmsk / ze3
+                  END DO
+               END DO
+            END DO
+         ENDIF
+
          CALL lbc_lnk( ze3f, 'F', 1. )
       ENDIF
@@ -715,5 +720,5 @@
       INTEGER ::   ios             ! Local integer output status for namelist read
       !!
-      NAMELIST/namdyn_vor/ ln_dynvor_ens, ln_dynvor_ene, ln_dynvor_mix, ln_dynvor_een
+      NAMELIST/namdyn_vor/ ln_dynvor_ens, ln_dynvor_ene, ln_dynvor_mix, ln_dynvor_een, ln_dynvor_een_old
       !!----------------------------------------------------------------------
 
@@ -736,4 +741,5 @@
          WRITE(numout,*) '           mixed enstrophy/energy conserving scheme   ln_dynvor_mix = ', ln_dynvor_mix
          WRITE(numout,*) '           enstrophy and energy conserving scheme     ln_dynvor_een = ', ln_dynvor_een
+         WRITE(numout,*) '           enstrophy and energy conserving scheme (old) ln_dynvor_een_old= ', ln_dynvor_een_old
       ENDIF
 
@@ -759,4 +765,5 @@
       IF( ln_dynvor_mix )   ioptio = ioptio + 1
       IF( ln_dynvor_een )   ioptio = ioptio + 1
+      IF( ln_dynvor_een_old )   ioptio = ioptio + 1
       IF( lk_esopa      )   ioptio =          1
 
@@ -767,5 +774,5 @@
       IF( ln_dynvor_ens )   nvor =  1
       IF( ln_dynvor_mix )   nvor =  2
-      IF( ln_dynvor_een )   nvor =  3
+      IF( ln_dynvor_een .or. ln_dynvor_een_old )   nvor =  3
       IF( lk_esopa      )   nvor = -1
       
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzad.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzad.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzad.F90	(revision 5075)
@@ -16,16 +16,18 @@
    USE dom_oce        ! ocean space and time domain
    USE sbc_oce        ! surface boundary condition: ocean
-   USE trdmod_oce     ! ocean variables trends
-   USE trdmod         ! ocean dynamics trends 
+   USE trd_oce        ! trends: ocean variables
+   USE trddyn         ! trend manager: dynamics
+   !
    USE in_out_manager ! I/O manager
-   USE lib_mpp         ! MPP library
+   USE lib_mpp        ! MPP library
    USE prtctl         ! Print control
-   USE wrk_nemo        ! Memory Allocation
-   USE timing          ! Timing
+   USE wrk_nemo       ! Memory Allocation
+   USE timing         ! Timing
 
    IMPLICIT NONE
    PRIVATE
    
-   PUBLIC   dyn_zad   ! routine called by step.F90
+   PUBLIC   dyn_zad       ! routine called by dynadv.F90
+   PUBLIC   dyn_zad_zts   ! routine called by dynadv.F90
 
    !! * Substitutions
@@ -53,5 +55,5 @@
       !!
       !! ** Action  : - Update (ua,va) with the vert. momentum adv. trends
-      !!              - Save the trends in (ztrdu,ztrdv) ('key_trddyn')
+      !!              - Send the trends to trddyn for diagnostics (l_trddyn=T)
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt   ! ocean time-step inedx
@@ -83,5 +85,5 @@
          DO jj = 2, jpj                   ! vertical fluxes 
             DO ji = fs_2, jpi             ! vector opt.
-               zww(ji,jj) = 0.25 * e1t(ji,jj) * e2t(ji,jj) * wn(ji,jj,jk)
+               zww(ji,jj) = 0.25_wp * e1t(ji,jj) * e2t(ji,jj) * wn(ji,jj,jk)
             END DO
          END DO
@@ -95,8 +97,8 @@
       DO jj = 2, jpjm1              ! Surface and bottom values set to zero
          DO ji = fs_2, fs_jpim1           ! vector opt.
-            zwuw(ji,jj, 1 ) = 0.e0
-            zwvw(ji,jj, 1 ) = 0.e0
-            zwuw(ji,jj,jpk) = 0.e0
-            zwvw(ji,jj,jpk) = 0.e0
+            zwuw(ji,jj, 1:miku(ji,jj) ) = 0._wp
+            zwvw(ji,jj, 1:mikv(ji,jj) ) = 0._wp
+            zwuw(ji,jj,jpk) = 0._wp
+            zwvw(ji,jj,jpk) = 0._wp
          END DO  
       END DO
@@ -118,5 +120,5 @@
          ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
          ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-         CALL trd_mod(ztrdu, ztrdv, jpdyn_trd_zad, 'DYN', kt)
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_zad, kt )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdu, ztrdv ) 
       ENDIF
@@ -132,4 +134,146 @@
    END SUBROUTINE dyn_zad
 
+   SUBROUTINE dyn_zad_zts ( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE dynzad_zts  ***
+      !! 
+      !! ** Purpose :   Compute the now vertical momentum advection trend and 
+      !!      add it to the general trend of momentum equation. This version
+      !!      uses sub-timesteps for improved numerical stability with small
+      !!      vertical grid sizes. This is especially relevant when using 
+      !!      embedded ice with thin surface boxes.
+      !!
+      !! ** Method  :   The now vertical advection of momentum is given by:
+      !!         w dz(u) = ua + 1/(e1u*e2u*e3u) mk+1[ mi(e1t*e2t*wn) dk(un) ]
+      !!         w dz(v) = va + 1/(e1v*e2v*e3v) mk+1[ mj(e1t*e2t*wn) dk(vn) ]
+      !!      Add this trend to the general trend (ua,va):
+      !!         (ua,va) = (ua,va) + w dz(u,v)
+      !!
+      !! ** Action  : - Update (ua,va) with the vert. momentum adv. trends
+      !!              - Save the trends in (ztrdu,ztrdv) ('key_trddyn')
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step inedx
+      !
+      INTEGER  ::   ji, jj, jk, jl  ! dummy loop indices
+      INTEGER  ::   jnzts = 5       ! number of sub-timesteps for vertical advection
+      INTEGER  ::   jtb, jtn, jta   ! sub timestep pointers for leap-frog/euler forward steps
+      REAL(wp) ::   zua, zva        ! temporary scalars
+      REAL(wp) ::   zr_rdt          ! temporary scalar
+      REAL(wp) ::   z2dtzts         ! length of Euler forward sub-timestep for vertical advection
+      REAL(wp) ::   zts             ! length of sub-timestep for vertical advection
+      REAL(wp), POINTER, DIMENSION(:,:,:)   ::  zwuw , zwvw, zww
+      REAL(wp), POINTER, DIMENSION(:,:,:)   ::  ztrdu, ztrdv
+      REAL(wp), POINTER, DIMENSION(:,:,:,:) ::  zus , zvs
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )  CALL timing_start('dyn_zad_zts')
+      !
+      CALL wrk_alloc( jpi,jpj,jpk, zwuw , zwvw, zww ) 
+      CALL wrk_alloc( jpi,jpj,jpk,3, zus, zvs ) 
+      !
+      IF( kt == nit000 ) THEN
+         IF(lwp)WRITE(numout,*)
+         IF(lwp)WRITE(numout,*) 'dyn_zad_zts : arakawa advection scheme with sub-timesteps'
+      ENDIF
+
+      IF( l_trddyn )   THEN         ! Save ua and va trends
+         CALL wrk_alloc( jpi, jpj, jpk, ztrdu, ztrdv ) 
+         ztrdu(:,:,:) = ua(:,:,:) 
+         ztrdv(:,:,:) = va(:,:,:) 
+      ENDIF
+      
+      IF( neuler == 0 .AND. kt == nit000 ) THEN
+          z2dtzts =         rdt / REAL( jnzts, wp )   ! = rdt (restart with Euler time stepping)
+      ELSE
+          z2dtzts = 2._wp * rdt / REAL( jnzts, wp )   ! = 2 rdt (leapfrog)
+      ENDIF
+      
+      DO jk = 2, jpkm1                    ! Calculate and store vertical fluxes
+         DO jj = 2, jpj                   
+            DO ji = fs_2, jpi             ! vector opt.
+               zww(ji,jj,jk) = 0.25_wp * e1t(ji,jj) * e2t(ji,jj) * wn(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+
+      DO jj = 2, jpjm1                    ! Surface and bottom advective fluxes set to zero
+         DO ji = fs_2, fs_jpim1           ! vector opt.
+            zwuw(ji,jj, 1:miku(ji,jj) ) = 0._wp
+            zwvw(ji,jj, 1:mikv(ji,jj) ) = 0._wp
+            zwuw(ji,jj,jpk) = 0._wp
+            zwvw(ji,jj,jpk) = 0._wp
+         END DO  
+      END DO
+
+! Start with before values and use sub timestepping to reach after values
+
+      zus(:,:,:,1) = ub(:,:,:)
+      zvs(:,:,:,1) = vb(:,:,:)
+
+      DO jl = 1, jnzts                   ! Start of sub timestepping loop
+
+         IF( jl == 1 ) THEN              ! Euler forward to kick things off
+           jtb = 1   ;   jtn = 1   ;   jta = 2
+           zts = z2dtzts
+         ELSEIF( jl == 2 ) THEN          ! First leapfrog step
+           jtb = 1   ;   jtn = 2   ;   jta = 3
+           zts = 2._wp * z2dtzts
+         ELSE                            ! Shuffle pointers for subsequent leapfrog steps
+           jtb = MOD(jtb,3) + 1
+           jtn = MOD(jtn,3) + 1
+           jta = MOD(jta,3) + 1
+         ENDIF
+
+         DO jk = 2, jpkm1           ! Vertical momentum advection at level w and u- and v- vertical
+            DO jj = 2, jpjm1                 ! vertical momentum advection at w-point
+               DO ji = fs_2, fs_jpim1        ! vector opt.
+                  zwuw(ji,jj,jk) = ( zww(ji+1,jj  ,jk) + zww(ji,jj,jk) ) * ( zus(ji,jj,jk-1,jtn)-zus(ji,jj,jk,jtn) )
+                  zwvw(ji,jj,jk) = ( zww(ji  ,jj+1,jk) + zww(ji,jj,jk) ) * ( zvs(ji,jj,jk-1,jtn)-zvs(ji,jj,jk,jtn) )
+               END DO  
+            END DO   
+         END DO
+         DO jk = 1, jpkm1           ! Vertical momentum advection at u- and v-points
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1       ! vector opt.
+                  !                         ! vertical momentum advective trends
+                  zua = - ( zwuw(ji,jj,jk) + zwuw(ji,jj,jk+1) ) / ( e1u(ji,jj) * e2u(ji,jj) * fse3u(ji,jj,jk) )
+                  zva = - ( zwvw(ji,jj,jk) + zwvw(ji,jj,jk+1) ) / ( e1v(ji,jj) * e2v(ji,jj) * fse3v(ji,jj,jk) )
+                  zus(ji,jj,jk,jta) = zus(ji,jj,jk,jtb) + zua * zts
+                  zvs(ji,jj,jk,jta) = zvs(ji,jj,jk,jtb) + zva * zts
+               END DO  
+            END DO  
+         END DO
+
+      END DO      ! End of sub timestepping loop
+
+      zr_rdt = 1._wp / ( REAL( jnzts, wp ) * z2dtzts )
+      DO jk = 1, jpkm1              ! Recover trends over the outer timestep
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1       ! vector opt.
+               !                         ! vertical momentum advective trends
+               !                         ! add the trends to the general momentum trends
+               ua(ji,jj,jk) = ua(ji,jj,jk) + ( zus(ji,jj,jk,jta) - ub(ji,jj,jk)) * zr_rdt
+               va(ji,jj,jk) = va(ji,jj,jk) + ( zvs(ji,jj,jk,jta) - vb(ji,jj,jk)) * zr_rdt
+            END DO  
+         END DO  
+      END DO
+
+      IF( l_trddyn ) THEN           ! save the vertical advection trends for diagnostic
+         ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
+         ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_zad, kt )
+         CALL wrk_dealloc( jpi, jpj, jpk, ztrdu, ztrdv ) 
+      ENDIF
+      !                             ! Control print
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=ua, clinfo1=' zad  - Ua: ', mask1=umask,   &
+         &                       tab3d_2=va, clinfo2=       ' Va: ', mask2=vmask, clinfo3='dyn' )
+      !
+      CALL wrk_dealloc( jpi,jpj,jpk, zwuw , zwvw, zww ) 
+      CALL wrk_dealloc( jpi,jpj,jpk,3, zus, zvs ) 
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('dyn_zad_zts')
+      !
+   END SUBROUTINE dyn_zad_zts
+
    !!======================================================================
 END MODULE dynzad
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf.F90	(revision 5075)
@@ -20,6 +20,6 @@
 
    USE ldfdyn_oce      ! ocean dynamics: lateral physics
-   USE trdmod          ! ocean active dynamics and tracers trends 
-   USE trdmod_oce      ! ocean variables trends
+   USE trd_oce         ! trends: ocean variables
+   USE trddyn          ! trend manager: dynamics
    USE in_out_manager  ! I/O manager
    USE lib_mpp         ! MPP library
@@ -91,6 +91,5 @@
          ztrdu(:,:,:) = ua(:,:,:) - ztrdu(:,:,:)
          ztrdv(:,:,:) = va(:,:,:) - ztrdv(:,:,:)
-         CALL trd_mod( ztrdu, ztrdv, jpdyn_trd_zdf, 'DYN', kt )
-         !
+         CALL trd_dyn( ztrdu, ztrdv, jpdyn_zdf, kt )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdu, ztrdv ) 
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf_imp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf_imp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/dynzdf_imp.F90	(revision 5075)
@@ -70,6 +70,4 @@
       REAL(wp) ::   z1_p2dt, zcoef, zzwi, zzws, zrhs   ! local scalars
       REAL(wp) ::   ze3ua, ze3va
-      !!----------------------------------------------------------------------
-
       REAL(wp), POINTER, DIMENSION(:,:,:) ::  zwi, zwd, zws
       !!----------------------------------------------------------------------
@@ -101,15 +99,14 @@
 
       IF( ln_bfrimp ) THEN
-# if defined key_vectopt_loop
-         DO jj = 1, 1
-            DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
-# else
          DO jj = 2, jpjm1
             DO ji = 2, jpim1
-# endif
                ikbu = mbku(ji,jj)       ! ocean bottom level at u- and v-points 
                ikbv = mbkv(ji,jj)       ! (deepest ocean u- and v-points)
                avmu(ji,jj,ikbu+1) = -bfrua(ji,jj) * fse3uw(ji,jj,ikbu+1)
                avmv(ji,jj,ikbv+1) = -bfrva(ji,jj) * fse3vw(ji,jj,ikbv+1)
+               ikbu = miku(ji,jj)       ! ocean top level at u- and v-points 
+               ikbv = mikv(ji,jj)       ! (first wet ocean u- and v-points)
+               IF (ikbu .GE. 2) avmu(ji,jj,ikbu) = -tfrua(ji,jj) * fse3uw(ji,jj,ikbu)
+               IF (ikbv .GE. 2) avmv(ji,jj,ikbv) = -tfrva(ji,jj) * fse3vw(ji,jj,ikbv)
             END DO
          END DO
@@ -138,6 +135,6 @@
             ua(:,:,jk) = (ua(:,:,jk) - ua_b(:,:)) * umask(:,:,jk)
             va(:,:,jk) = (va(:,:,jk) - va_b(:,:)) * vmask(:,:,jk)
-         ENDDO
-         ! Add bottom stress due to barotropic component only:
+         END DO
+         ! Add bottom/top stress due to barotropic component only:
          DO jj = 2, jpjm1        
             DO ji = fs_2, fs_jpim1   ! vector opt.
@@ -148,4 +145,10 @@
                ua(ji,jj,ikbu) = ua(ji,jj,ikbu) + p2dt * bfrua(ji,jj) * ua_b(ji,jj) / ze3ua
                va(ji,jj,ikbv) = va(ji,jj,ikbv) + p2dt * bfrva(ji,jj) * va_b(ji,jj) / ze3va
+               ikbu = miku(ji,jj)         ! top ocean level at u- and v-points 
+               ikbv = mikv(ji,jj)         ! (first wet ocean u- and v-points)
+               ze3ua =  ( 1._wp - r_vvl ) * fse3u_n(ji,jj,ikbu) + r_vvl   * fse3u_a(ji,jj,ikbu)
+               ze3va =  ( 1._wp - r_vvl ) * fse3v_n(ji,jj,ikbv) + r_vvl   * fse3v_a(ji,jj,ikbv)
+               ua(ji,jj,ikbu) = ua(ji,jj,ikbu) + p2dt * tfrua(ji,jj) * ua_b(ji,jj) / ze3ua
+               va(ji,jj,ikbv) = va(ji,jj,ikbv) + p2dt * tfrva(ji,jj) * va_b(ji,jj) / ze3va
             END DO
          END DO
@@ -166,5 +169,5 @@
                zzwi          = zcoef * avmu (ji,jj,jk  ) / fse3uw(ji,jj,jk  )
                zwi(ji,jj,jk) = zzwi  * umask(ji,jj,jk)
-               zzws          = zcoef * avmu (ji,jj,jk+1) / fse3uw(ji,jj,jk+1)
+               zzws          = zcoef * avmu (ji,jj,jk+1) / fse3uw(ji,jj,jk+1) 
                zws(ji,jj,jk) = zzws  * umask(ji,jj,jk+1)
                zwd(ji,jj,jk) = 1._wp - zwi(ji,jj,jk) - zzws
@@ -194,7 +197,8 @@
       !-----------------------------------------------------------------------
       !
-      DO jk = 2, jpkm1        !==  First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1   (increasing k)  ==
-         DO jj = 2, jpjm1   
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+      !==  First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1   (increasing k)  ==
+      DO jj = 2, jpjm1   
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            DO jk = miku(ji,jj)+1, jpkm1
                zwd(ji,jj,jk) = zwd(ji,jj,jk) - zwi(ji,jj,jk) * zws(ji,jj,jk-1) / zwd(ji,jj,jk-1)
             END DO
@@ -204,17 +208,14 @@
       DO jj = 2, jpjm1        !==  second recurrence:    SOLk = RHSk - Lk / Dk-1  Lk-1  ==
          DO ji = fs_2, fs_jpim1   ! vector opt.
-            ze3ua =  ( 1._wp - r_vvl ) * fse3u_n(ji,jj,1) + r_vvl   * fse3u_a(ji,jj,1) 
+            ze3ua =  ( 1._wp - r_vvl ) * fse3u_n(ji,jj,miku(ji,jj)) + r_vvl   * fse3u_a(ji,jj,miku(ji,jj)) 
 #if defined key_dynspg_ts
-            ua(ji,jj,1) = ua(ji,jj,1) + p2dt * 0.5_wp * ( utau_b(ji,jj) + utau(ji,jj) )   &
+            ua(ji,jj,miku(ji,jj)) = ua(ji,jj,miku(ji,jj)) + p2dt * 0.5_wp * ( utau_b(ji,jj) + utau(ji,jj) )   &
                &                                      / ( ze3ua * rau0 ) 
 #else
-            ua(ji,jj,1) = ub(ji,jj,1) + p2dt *(ua(ji,jj,1) +  0.5_wp * ( utau_b(ji,jj) + utau(ji,jj) )   &
-               &                                                     / ( fse3u(ji,jj,1) * rau0     ) ) 
-#endif
-         END DO
-      END DO
-      DO jk = 2, jpkm1
-         DO jj = 2, jpjm1   
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+            ua(ji,jj,miku(ji,jj)) = ub(ji,jj,miku(ji,jj)) &
+               &                   + p2dt *(ua(ji,jj,miku(ji,jj)) +  0.5_wp * ( utau_b(ji,jj) + utau(ji,jj) )   &
+               &                                  / ( fse3u(ji,jj,miku(ji,jj)) * rau0     ) ) 
+#endif
+            DO jk = miku(ji,jj)+1, jpkm1
 #if defined key_dynspg_ts
                zrhs = ua(ji,jj,jk)   ! zrhs=right hand side
@@ -230,9 +231,5 @@
          DO ji = fs_2, fs_jpim1   ! vector opt.
             ua(ji,jj,jpkm1) = ua(ji,jj,jpkm1) / zwd(ji,jj,jpkm1)
-         END DO
-      END DO
-      DO jk = jpk-2, 1, -1
-         DO jj = 2, jpjm1   
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+            DO jk = jpk-2, miku(ji,jj), -1
                ua(ji,jj,jk) = ( ua(ji,jj,jk) - zws(ji,jj,jk) * ua(ji,jj,jk+1) ) / zwd(ji,jj,jk)
             END DO
@@ -292,7 +289,8 @@
       !-----------------------------------------------------------------------
       !
-      DO jk = 2, jpkm1        !==  First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1   (increasing k)  ==
-         DO jj = 2, jpjm1   
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+      !==  First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1   (increasing k)  ==
+      DO jj = 2, jpjm1   
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            DO jk = mikv(ji,jj)+1, jpkm1        
                zwd(ji,jj,jk) = zwd(ji,jj,jk) - zwi(ji,jj,jk) * zws(ji,jj,jk-1) / zwd(ji,jj,jk-1)
             END DO
@@ -302,17 +300,14 @@
       DO jj = 2, jpjm1        !==  second recurrence:    SOLk = RHSk - Lk / Dk-1  Lk-1  ==
          DO ji = fs_2, fs_jpim1   ! vector opt.
-            ze3va =  ( 1._wp - r_vvl ) * fse3v_n(ji,jj,1) + r_vvl   * fse3v_a(ji,jj,1) 
+            ze3va =  ( 1._wp - r_vvl ) * fse3v_n(ji,jj,mikv(ji,jj)) + r_vvl   * fse3v_a(ji,jj,mikv(ji,jj)) 
 #if defined key_dynspg_ts            
-            va(ji,jj,1) = va(ji,jj,1) + p2dt * 0.5_wp * ( vtau_b(ji,jj) + vtau(ji,jj) )   &
+            va(ji,jj,mikv(ji,jj)) = va(ji,jj,mikv(ji,jj)) + p2dt * 0.5_wp * ( vtau_b(ji,jj) + vtau(ji,jj) )   &
                &                                      / ( ze3va * rau0 ) 
 #else
-            va(ji,jj,1) = vb(ji,jj,1) + p2dt *(va(ji,jj,1) +  0.5_wp * ( vtau_b(ji,jj) + vtau(ji,jj) )   &
-               &                                                       / ( fse3v(ji,jj,1) * rau0     )  )
-#endif
-         END DO
-      END DO
-      DO jk = 2, jpkm1
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+            va(ji,jj,mikv(ji,jj)) = vb(ji,jj,mikv(ji,jj)) &
+               &                   + p2dt *(va(ji,jj,mikv(ji,jj)) +  0.5_wp * ( vtau_b(ji,jj) + vtau(ji,jj) )   &
+               &                                                       / ( fse3v(ji,jj,mikv(ji,jj)) * rau0     )  )
+#endif
+            DO jk = mikv(ji,jj)+1, jpkm1
 #if defined key_dynspg_ts
                zrhs = va(ji,jj,jk)   ! zrhs=right hand side
@@ -328,9 +323,5 @@
          DO ji = fs_2, fs_jpim1   ! vector opt.
             va(ji,jj,jpkm1) = va(ji,jj,jpkm1) / zwd(ji,jj,jpkm1)
-         END DO
-      END DO
-      DO jk = jpk-2, 1, -1
-         DO jj = 2, jpjm1   
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+            DO jk = jpk-2, mikv(ji,jj), -1
                va(ji,jj,jk) = ( va(ji,jj,jk) - zws(ji,jj,jk) * va(ji,jj,jk+1) ) / zwd(ji,jj,jk)
             END DO
@@ -352,17 +343,16 @@
       !! restore bottom layer avmu(v) 
       IF( ln_bfrimp ) THEN
-# if defined key_vectopt_loop
-      DO jj = 1, 1
-         DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
-# else
-      DO jj = 2, jpjm1
-         DO ji = 2, jpim1
-# endif
-            ikbu = mbku(ji,jj)         ! ocean bottom level at u- and v-points 
-            ikbv = mbkv(ji,jj)         ! (deepest ocean u- and v-points)
-            avmu(ji,jj,ikbu+1) = 0.e0
-            avmv(ji,jj,ikbv+1) = 0.e0
-         END DO
-      END DO
+        DO jj = 2, jpjm1
+           DO ji = 2, jpim1
+              ikbu = mbku(ji,jj)         ! ocean bottom level at u- and v-points 
+              ikbv = mbkv(ji,jj)         ! (deepest ocean u- and v-points)
+              avmu(ji,jj,ikbu+1) = 0.e0
+              avmv(ji,jj,ikbv+1) = 0.e0
+              ikbu = miku(ji,jj)         ! ocean top level at u- and v-points 
+              ikbv = mikv(ji,jj)         ! (first wet ocean u- and v-points)
+              IF (ikbu > 1) avmu(ji,jj,ikbu) = 0.e0
+              IF (ikbv > 1) avmv(ji,jj,ikbv) = 0.e0
+           END DO
+        END DO
       ENDIF
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/sshwzv.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/sshwzv.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/DYN/sshwzv.F90	(revision 5075)
@@ -31,5 +31,4 @@
    USE bdy_par         
    USE bdydyn2d        ! bdy_ssh routine
-   USE diaar5, ONLY:   lk_diaar5
    USE iom
 #if defined key_agrif
@@ -111,5 +110,5 @@
       ! 
       z1_rau0 = 0.5_wp * r1_rau0
-      ssha(:,:) = (  sshb(:,:) - z2dt * ( z1_rau0 * ( emp_b(:,:) + emp(:,:) ) + zhdiv(:,:) )  ) * tmask(:,:,1)
+      ssha(:,:) = (  sshb(:,:) - z2dt * ( z1_rau0 * ( emp_b(:,:) + emp(:,:) ) + zhdiv(:,:) )  ) * ssmask(:,:)
 
 #if ! defined key_dynspg_ts
@@ -138,6 +137,6 @@
       !                                           !           outputs            !
       !                                           !------------------------------!
-      CALL iom_put( "ssh" , sshn                  )   ! sea surface height
-      CALL iom_put( "ssh2", sshn(:,:) * sshn(:,:) )   ! square of sea surface height
+      CALL iom_put( "ssh" , sshn )   ! sea surface height
+      if( iom_use('ssh2') )   CALL iom_put( "ssh2", sshn(:,:) * sshn(:,:) )   ! square of sea surface height
       !
       IF(ln_ctl)   CALL prt_ctl( tab2d_1=ssha, clinfo1=' ssha  - : ', mask1=tmask, ovlap=1 )
@@ -233,5 +232,5 @@
       !                                           !------------------------------!
       CALL iom_put( "woce", wn )   ! vertical velocity
-      IF( lk_diaar5 ) THEN                            ! vertical mass transport & its square value
+      IF( iom_use('w_masstr') .OR. iom_use('w_masstr2') ) THEN   ! vertical mass transport & its square value
          CALL wrk_alloc( jpi, jpj, z2d ) 
          CALL wrk_alloc( jpi, jpj, jpk, z3d ) 
@@ -241,6 +240,6 @@
             z3d(:,:,jk) = wn(:,:,jk) * z2d(:,:)
          END DO
-         CALL iom_put( "w_masstr" , z3d                     )  
-         CALL iom_put( "w_masstr2", z3d(:,:,:) * z3d(:,:,:) )
+         CALL iom_put( "w_masstr" , z3d )  
+         IF( iom_use('w_masstr2') )   CALL iom_put( "w_masstr2", z3d(:,:,:) * z3d(:,:,:) )
          CALL wrk_dealloc( jpi, jpj, z2d  ) 
          CALL wrk_dealloc( jpi, jpj, jpk, z3d ) 
@@ -291,5 +290,5 @@
       ELSE                                         !** Leap-Frog time-stepping: Asselin filter + swap
          sshb(:,:) = sshn(:,:) + atfp * ( sshb(:,:) - 2 * sshn(:,:) + ssha(:,:) )     ! before <-- now filtered
-         IF( lk_vvl ) sshb(:,:) = sshb(:,:) - atfp * rdt / rau0 * ( emp_b(:,:) - emp(:,:) ) * tmask(:,:,1)
+         IF( lk_vvl ) sshb(:,:) = sshb(:,:) - atfp * rdt / rau0 * ( emp_b(:,:) - emp(:,:) ) * ssmask(:,:)
          sshn(:,:) = ssha(:,:)                           ! now <-- after
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icb_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icb_oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icb_oce.F90	(revision 5075)
@@ -44,10 +44,4 @@
 
 INTEGER, PUBLIC, PARAMETER ::   nclasses = 10   !: Number of icebergs classes   
-!!INTEGER, PUBLIC &
-!!#if !defined key_agrif 
-!!           , PARAMETER &
-!!#endif
-!!     :: &
-!!     nclasses = 10   !: Number of icebergs classes
    INTEGER, PUBLIC, PARAMETER ::   nkounts  =  3   !: Number of integers combined for unique naming
 
@@ -93,8 +87,8 @@
    ! particularly for MPP when iceberg can lie inside T grid but outside U, V, or f grid
    REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   uo_e, vo_e
-   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ff_e
+   REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ff_e, tt_e, fr_e, hicth
    REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ua_e, va_e
    REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ssh_e
-#if defined key_lim2 || defined key_lim3
+#if defined key_lim2 || defined key_lim3 || defined key_cice
    REAL(wp), PUBLIC, DIMENSION(:,:), ALLOCATABLE ::   ui_e, vi_e
 #endif
@@ -144,4 +138,7 @@
    INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)       ::   nicbflddest                      !: nfold destination proc
    INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)       ::   nicbfldproc                      !: nfold destination proc
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)       ::   nicbfldnsend                     !: nfold number of bergs to send to nfold neighbour
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)       ::   nicbfldexpect                    !: nfold expected number of bergs
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:)       ::   nicbfldreq                       !: nfold message handle (immediate send)
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   :: griddata                           !: work array for icbrst
@@ -162,4 +159,6 @@
       !
       icb_alloc = 0
+      ALLOCATE( berg_grid, STAT=ill )
+      icb_alloc = icb_alloc + ill
       ALLOCATE( berg_grid%calving    (jpi,jpj) , berg_grid%calving_hflx (jpi,jpj)          ,   &
          &      berg_grid%stored_heat(jpi,jpj) , berg_grid%floating_melt(jpi,jpj)          ,   &
@@ -171,9 +170,11 @@
       ALLOCATE( uo_e(0:jpi+1,0:jpj+1) , ua_e(0:jpi+1,0:jpj+1) ,   &
          &      vo_e(0:jpi+1,0:jpj+1) , va_e(0:jpi+1,0:jpj+1) ,   &
-#if defined key_lim2 || defined key_lim3
+#if defined key_lim2 || defined key_lim3 || defined key_cice
          &      ui_e(0:jpi+1,0:jpj+1) ,                            &
          &      vi_e(0:jpi+1,0:jpj+1) ,                            &
 #endif
-         &      ff_e(0:jpi+1,0:jpj+1) , ssh_e(0:jpi+1,0:jpj+1) ,   &
+         &      ff_e(0:jpi+1,0:jpj+1) , fr_e(0:jpi+1,0:jpj+1)  ,   &
+         &      tt_e(0:jpi+1,0:jpj+1) , ssh_e(0:jpi+1,0:jpj+1) ,   &
+         &      hicth(0:jpi+1,0:jpj+1),                            &
          &      first_width(nclasses) , first_length(nclasses) ,   &
          &      src_calving (jpi,jpj) ,                            &
@@ -181,5 +182,6 @@
       icb_alloc = icb_alloc + ill
 
-      ALLOCATE( nicbfldpts(jpi) , nicbflddest(jpi) , nicbfldproc(jpni) , STAT=ill)
+      ALLOCATE( nicbfldpts(jpi) , nicbflddest(jpi) , nicbfldproc(jpni) , &
+         &      nicbfldnsend(jpni), nicbfldexpect(jpni) , nicbfldreq(jpni), STAT=ill)
       icb_alloc = icb_alloc + ill
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbdyn.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbdyn.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbdyn.F90	(revision 5075)
@@ -33,5 +33,5 @@
 CONTAINS
 
-   SUBROUTINE icb_dyn()
+   SUBROUTINE icb_dyn( kt )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE icb_dyn  ***
@@ -50,4 +50,5 @@
       TYPE(iceberg), POINTER          ::   berg
       TYPE(point)  , POINTER          ::   pt
+      INTEGER                         ::   kt
       !!----------------------------------------------------------------------
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbini.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbini.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbini.F90	(revision 5075)
@@ -172,13 +172,16 @@
          DO ji = nicbdi, nicbei
             ii = nicbflddest(ji)
-            DO jn = 1, jpni
-               ! work along array until we find an empty slot
-               IF( nicbfldproc(jn) == -1 ) THEN
-                  nicbfldproc(jn) = ii
-                  EXIT                             !!gm EXIT should be avoided: use DO WHILE expression instead
-               ENDIF
-               ! before we find an empty slot, we may find processor number is already here so we exit
-               IF( nicbfldproc(jn) == ii ) EXIT
-            END DO
+            IF( ii .GT. 0 ) THEN     ! Needed because land suppression can mean
+                                     ! that unused points are not set in edge haloes
+               DO jn = 1, jpni
+                  ! work along array until we find an empty slot
+                  IF( nicbfldproc(jn) == -1 ) THEN
+                     nicbfldproc(jn) = ii
+                     EXIT                             !!gm EXIT should be avoided: use DO WHILE expression instead
+                  ENDIF
+                  ! before we find an empty slot, we may find processor number is already here so we exit
+                  IF( nicbfldproc(jn) == ii ) EXIT
+               END DO
+            ENDIF
          END DO
       ENDIF
@@ -210,4 +213,6 @@
             WRITE(numicb,*) 'north fold destination procs  '
             WRITE(numicb,*) nicbflddest
+            WRITE(numicb,*) 'north fold destination proclist  '
+            WRITE(numicb,*) nicbfldproc
          ENDIF
          CALL flush(numicb)
@@ -397,7 +402,7 @@
       ENDIF
 
-      IF( lk_lim3 .AND. ln_icebergs ) THEN
-         CALL ctl_stop( 'icb_nam: the use of ICB with LIM3 not allowed. ice thickness missing in ICB' )
-      ENDIF
+!     IF( lk_lim3 .AND. ln_icebergs ) THEN
+!        CALL ctl_stop( 'icb_nam: the use of ICB with LIM3 not allowed. ice thickness missing in ICB' )
+!     ENDIF
 
       IF(lwp) THEN                  ! control print
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icblbc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icblbc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icblbc.F90	(revision 5075)
@@ -280,5 +280,5 @@
          zwebergs(1) = ibergs_to_send_e
          CALL mppsend( 12, zwebergs(1), 1, ipe_E, iml_req1)
-         CALL mpprecv( 11, zewbergs(2), 1 )
+         CALL mpprecv( 11, zewbergs(2), 1, ipe_E )
          IF( l_isend ) CALL mpi_wait( iml_req1, iml_stat, iml_err )
          ibergs_rcvd_from_e = INT( zewbergs(2) )
@@ -288,6 +288,6 @@
          CALL mppsend( 11, zewbergs(1), 1, ipe_W, iml_req2)
          CALL mppsend( 12, zwebergs(1), 1, ipe_E, iml_req3)
-         CALL mpprecv( 11, zewbergs(2), 1 )
-         CALL mpprecv( 12, zwebergs(2), 1 )
+         CALL mpprecv( 11, zewbergs(2), 1, ipe_E )
+         CALL mpprecv( 12, zwebergs(2), 1, ipe_W )
          IF( l_isend ) CALL mpi_wait( iml_req2, iml_stat, iml_err )
          IF( l_isend ) CALL mpi_wait( iml_req3, iml_stat, iml_err )
@@ -297,5 +297,5 @@
          zewbergs(1) = ibergs_to_send_w
          CALL mppsend( 11, zewbergs(1), 1, ipe_W, iml_req4)
-         CALL mpprecv( 12, zwebergs(2), 1 )
+         CALL mpprecv( 12, zwebergs(2), 1, ipe_W )
          IF( l_isend ) CALL mpi_wait( iml_req4, iml_stat, iml_err )
          ibergs_rcvd_from_w = INT( zwebergs(2) )
@@ -411,5 +411,5 @@
          zsnbergs(1) = ibergs_to_send_n
          CALL mppsend( 16, zsnbergs(1), 1, ipe_N, iml_req1)
-         CALL mpprecv( 15, znsbergs(2), 1 )
+         CALL mpprecv( 15, znsbergs(2), 1, ipe_N )
          IF( l_isend ) CALL mpi_wait( iml_req1, iml_stat, iml_err )
          ibergs_rcvd_from_n = INT( znsbergs(2) )
@@ -419,6 +419,6 @@
          CALL mppsend( 15, znsbergs(1), 1, ipe_S, iml_req2)
          CALL mppsend( 16, zsnbergs(1), 1, ipe_N, iml_req3)
-         CALL mpprecv( 15, znsbergs(2), 1 )
-         CALL mpprecv( 16, zsnbergs(2), 1 )
+         CALL mpprecv( 15, znsbergs(2), 1, ipe_N )
+         CALL mpprecv( 16, zsnbergs(2), 1, ipe_S )
          IF( l_isend ) CALL mpi_wait( iml_req2, iml_stat, iml_err )
          IF( l_isend ) CALL mpi_wait( iml_req3, iml_stat, iml_err )
@@ -428,5 +428,5 @@
          znsbergs(1) = ibergs_to_send_s
          CALL mppsend( 15, znsbergs(1), 1, ipe_S, iml_req4)
-         CALL mpprecv( 16, zsnbergs(2), 1 )
+         CALL mpprecv( 16, zsnbergs(2), 1, ipe_S )
          IF( l_isend ) CALL mpi_wait( iml_req4, iml_stat, iml_err )
          ibergs_rcvd_from_s = INT( zsnbergs(2) )
@@ -581,5 +581,6 @@
       INTEGER                             :: ifldproc, iproc, ipts
       INTEGER                             :: iine, ijne
-      REAL(wp), DIMENSION(2)              :: zsbergs, znbergs
+      INTEGER                             :: jjn
+      REAL(wp), DIMENSION(0:3)            :: zsbergs, znbergs
       INTEGER                             :: iml_req1, iml_req2, iml_err
       INTEGER, DIMENSION(MPI_STATUS_SIZE) :: iml_stat
@@ -591,4 +592,93 @@
       ! its of fixed size, the first -1 marks end of list of processors
       !
+      nicbfldnsend(:) = 0
+      nicbfldexpect(:) = 0
+      nicbfldreq(:) = 0
+      !
+      ! Since each processor may be communicating with more than one northern
+      ! neighbour, cycle through the sends so that the receive order can be
+      ! controlled.
+      !
+      ! First compute how many icebergs each active neighbour should expect
+      DO jn = 1, jpni
+         IF( nicbfldproc(jn) /= -1 ) THEN
+            ifldproc = nicbfldproc(jn)
+            nicbfldnsend(jn) = 0
+
+            ! Find number of bergs that need to be exchanged
+            ! Pick out exchanges with processor ifldproc
+            ! if ifldproc is this processor then don't send
+            !
+            IF( ASSOCIATED(first_berg) ) THEN
+               this => first_berg
+               DO WHILE (ASSOCIATED(this))
+                  pt => this%current_point
+                  iine = INT( pt%xi + 0.5 )
+                  ijne = INT( pt%yj + 0.5 )
+                  iproc = nicbflddest(mi1(iine))
+                  IF( ijne .GT. mjg(nicbej) ) THEN
+                     IF( iproc == ifldproc ) THEN
+                        !
+                        IF( iproc /= narea ) THEN
+                           tmpberg => this
+                           nicbfldnsend(jn) = nicbfldnsend(jn) + 1
+                        ENDIF
+                        !
+                     ENDIF
+                  ENDIF
+                  this => this%next
+               END DO
+            ENDIF
+            !
+         ENDIF
+         !
+      END DO
+      !
+      ! Now tell each active neighbour how many icebergs to expect
+      DO jn = 1, jpni
+         IF( nicbfldproc(jn) /= -1 ) THEN
+            ifldproc = nicbfldproc(jn)
+            IF( ifldproc == narea ) CYCLE
+   
+            zsbergs(0) = narea
+            zsbergs(1) = nicbfldnsend(jn)
+            !IF ( nicbfldnsend(jn) .GT. 0) write(numicb,*) 'ICB sending ',nicbfldnsend(jn),' to ', ifldproc
+            CALL mppsend( 21, zsbergs(0:1), 2, ifldproc-1, nicbfldreq(jn))
+         ENDIF
+         !
+      END DO
+      !
+      ! and receive the heads-up from active neighbours preparing to send
+      DO jn = 1, jpni
+         IF( nicbfldproc(jn) /= -1 ) THEN
+            ifldproc = nicbfldproc(jn)
+            IF( ifldproc == narea ) CYCLE
+
+            CALL mpprecv( 21, znbergs(1:2), 2 )
+            DO jjn = 1,jpni
+             IF( nicbfldproc(jjn) .eq. INT(znbergs(1)) ) EXIT
+            END DO
+            IF( jjn .GT. jpni ) write(numicb,*) 'ICB ERROR'
+            nicbfldexpect(jjn) = INT( znbergs(2) )
+            !IF ( nicbfldexpect(jjn) .GT. 0) write(numicb,*) 'ICB expecting ',nicbfldexpect(jjn),' from ', nicbfldproc(jjn)
+            !CALL FLUSH(numicb)
+         ENDIF
+         !
+      END DO
+      !
+      ! post the mpi waits if using immediate send protocol
+      DO jn = 1, jpni
+         IF( nicbfldproc(jn) /= -1 ) THEN
+            ifldproc = nicbfldproc(jn)
+            IF( ifldproc == narea ) CYCLE
+
+            IF( l_isend ) CALL mpi_wait( nicbfldreq(jn), iml_stat, iml_err )
+         ENDIF
+         !
+      END DO
+   
+         !
+         ! Cycle through the icebergs again, this time packing and sending any
+         ! going through the north fold. They will be expected.
       DO jn = 1, jpni
          IF( nicbfldproc(jn) /= -1 ) THEN
@@ -646,19 +736,25 @@
             IF( ifldproc == narea ) CYCLE
    
-            zsbergs(1) = ibergs_to_send
-            CALL mppsend( 21, zsbergs(1), 1, ifldproc-1, iml_req1)
-            CALL mpprecv( 21, znbergs(2), 1 )
-            IF( l_isend ) CALL mpi_wait( iml_req1, iml_stat, iml_err )
-            ibergs_to_rcv = INT( znbergs(2) )
-   
             ! send bergs
    
             IF( ibergs_to_send > 0 )  &
-                CALL mppsend( 12, obuffer_f%data, ibergs_to_send*jp_buffer_width, ifldproc-1, iml_req2 )
+                CALL mppsend( 12, obuffer_f%data, ibergs_to_send*jp_buffer_width, ifldproc-1, nicbfldreq(jn) )
+            !
+         ENDIF
+         !
+      END DO
+      !
+      ! Now receive the expected number of bergs from the active neighbours
+      DO jn = 1, jpni
+         IF( nicbfldproc(jn) /= -1 ) THEN
+            ifldproc = nicbfldproc(jn)
+            IF( ifldproc == narea ) CYCLE
+            ibergs_to_rcv = nicbfldexpect(jn)
+
             IF( ibergs_to_rcv  > 0 ) THEN
                CALL icb_increase_ibuffer(ibuffer_f, ibergs_to_rcv)
-               CALL mpprecv( 12, ibuffer_f%data, ibergs_to_rcv*jp_buffer_width )
-            ENDIF
-            IF( ibergs_to_send > 0 .AND. l_isend ) CALL mpi_wait( iml_req2, iml_stat, iml_err )
+               CALL mpprecv( 12, ibuffer_f%data, ibergs_to_rcv*jp_buffer_width, ifldproc-1 )
+            ENDIF
+            !
             DO jk = 1, ibergs_to_rcv
                IF( nn_verbose_level >= 4 ) THEN
@@ -668,5 +764,15 @@
                CALL icb_unpack_from_buffer(first_berg, ibuffer_f, jk )
             END DO
-            !
+         ENDIF
+         !
+      END DO
+      !
+      ! Finally post the mpi waits if using immediate send protocol
+      DO jn = 1, jpni
+         IF( nicbfldproc(jn) /= -1 ) THEN
+            ifldproc = nicbfldproc(jn)
+            IF( ifldproc == narea ) CYCLE
+
+            IF( l_isend ) CALL mpi_wait( nicbfldreq(jn), iml_stat, iml_err )
          ENDIF
          !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbrst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbrst.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbrst.F90	(revision 5075)
@@ -64,5 +64,5 @@
                                                                                             ! start and count arrays
       LOGICAL                      ::   ll_found_restart
-      CHARACTER(len=80)            ::   cl_filename
+      CHARACTER(len=256)           ::   cl_filename
       CHARACTER(len=NF90_MAX_NAME) ::   cl_dname
       TYPE(iceberg)                ::   localberg ! NOT a pointer but an actual local variable
@@ -228,5 +228,5 @@
       INTEGER ::   jn   ! dummy loop index
       INTEGER ::   ix_dim, iy_dim, ik_dim, in_dim
-      CHARACTER(len=80)      :: cl_filename
+      CHARACTER(len=256)     :: cl_filename
       TYPE(iceberg), POINTER :: this
       TYPE(point)  , POINTER :: pt
@@ -256,4 +256,19 @@
       IF (nret .ne. NF90_NOERR) CALL ctl_stop('icebergs, write_restart: nf_def_dim k failed')
 
+      ! global attributes
+      IF( lk_mpp ) THEN
+         ! Set domain parameters (assume jpdom_local_full)
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_number_total'   , jpnij              )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_number'         , narea-1            )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_dimensions_ids' , (/1     , 2     /) )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_size_global'    , (/jpiglo, jpjglo/) )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_size_local'     , (/jpi   , jpj   /) )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_position_first' , (/nimpp , njmpp /) )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_position_last'  , (/nimpp + jpi - 1 , njmpp + jpj - 1  /) )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_halo_size_start', (/nldi - 1        , nldj - 1         /) )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_halo_size_end'  , (/jpi - nlei      , jpj - nlej       /) )
+         nret = NF90_PUT_ATT( ncid, NF90_GLOBAL, 'DOMAIN_type'           , 'BOX'              )
+      ENDIF
+      
       IF (associated(first_berg)) then
          nret = NF90_DEF_DIM(ncid, 'n', NF90_UNLIMITED, in_dim)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbstp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbstp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbstp.F90	(revision 5075)
@@ -105,5 +105,5 @@
 !                               !==  For each berg, evolve  ==!
       !
-      IF( ASSOCIATED(first_berg) )   CALL icb_dyn()           ! ice berg dynamics
+      IF( ASSOCIATED(first_berg) )   CALL icb_dyn( kt )       ! ice berg dynamics
 
       IF( lk_mpp ) THEN          ;   CALL icb_lbc_mpp()       ! Send bergs to other PEs
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbutl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbutl.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ICB/icbutl.F90	(revision 5075)
@@ -70,15 +70,23 @@
       ! and ssh which is used to calculate gradients
 
-      uo_e(:,:) = 0._wp ;   uo_e(1:jpi, 1:jpj) = ssu_m(:,:)
-      vo_e(:,:) = 0._wp ;   vo_e(1:jpi, 1:jpj) = ssv_m(:,:)
-      ff_e(:,:) = 0._wp ;   ff_e(1:jpi, 1:jpj) = ff   (:,:)
-      ua_e(:,:) = 0._wp ;   ua_e(1:jpi, 1:jpj) = utau (:,:)
-      va_e(:,:) = 0._wp ;   va_e(1:jpi, 1:jpj) = vtau (:,:)
-
-      CALL lbc_lnk_e( uo_e, 'U', -1._wp, 1, 1 )
-      CALL lbc_lnk_e( vo_e, 'V', -1._wp, 1, 1 )
-      CALL lbc_lnk_e( ff_e, 'F', +1._wp, 1, 1 )
-      CALL lbc_lnk_e( ua_e, 'U', -1._wp, 1, 1 )
-      CALL lbc_lnk_e( va_e, 'V', -1._wp, 1, 1 )
+      uo_e(:,:) = 0._wp ;   uo_e(1:jpi, 1:jpj) = ssu_m(:,:) * umask(:,:,1)
+      vo_e(:,:) = 0._wp ;   vo_e(1:jpi, 1:jpj) = ssv_m(:,:) * vmask(:,:,1)
+      ff_e(:,:) = 0._wp ;   ff_e(1:jpi, 1:jpj) = ff   (:,:) 
+      tt_e(:,:) = 0._wp ;   tt_e(1:jpi, 1:jpj) = sst_m(:,:)
+      fr_e(:,:) = 0._wp ;   fr_e(1:jpi, 1:jpj) = fr_i (:,:)
+      ua_e(:,:) = 0._wp ;   ua_e(1:jpi, 1:jpj) = utau (:,:) * umask(:,:,1) ! maybe mask useless because mask applied in sbcblk
+      va_e(:,:) = 0._wp ;   va_e(1:jpi, 1:jpj) = vtau (:,:) * vmask(:,:,1) ! maybe mask useless because mask applied in sbcblk
+
+      CALL lbc_lnk_icb( uo_e, 'U', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( vo_e, 'V', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( ff_e, 'F', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( ua_e, 'U', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( va_e, 'V', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( fr_e, 'T', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( tt_e, 'T', +1._wp, 1, 1 )
+#if defined key_lim2
+      hicth(:,:) = 0._wp ;  hicth(1:jpi,1:jpj) = hicif(:,:)  
+      CALL lbc_lnk_icb(hicth, 'T', +1._wp, 1, 1 )  
+#endif
 
 #if defined key_lim2 || defined key_lim3
@@ -86,6 +94,6 @@
       vi_e(:,:) = 0._wp ;   vi_e(1:jpi, 1:jpj) = v_ice(:,:)
 
-      CALL lbc_lnk_e( ui_e, 'U', -1._wp, 1, 1 )
-      CALL lbc_lnk_e( vi_e, 'V', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( ui_e, 'U', -1._wp, 1, 1 )
+      CALL lbc_lnk_icb( vi_e, 'V', -1._wp, 1, 1 )
 #endif
 
@@ -93,5 +101,5 @@
       !! so fudge some numbers all the way around the boundary
 
-      ssh_e(:,:) = 0._wp ;   ssh_e(1:jpi, 1:jpj) = ssh_m(:,:)
+      ssh_e(:,:) = 0._wp ;   ssh_e(1:jpi, 1:jpj) = ssh_m(:,:) * tmask(:,:,1)
       ssh_e(0    ,    :) = ssh_e(1  ,  :)
       ssh_e(jpi+1,    :) = ssh_e(jpi,  :)
@@ -102,5 +110,5 @@
       ssh_e(0,jpj+1)     = ssh_e(1,jpj)
       ssh_e(jpi+1,jpj+1) = ssh_e(jpi,jpj)
-      CALL lbc_lnk_e( ssh_e, 'T', +1._wp, 1, 1 )
+      CALL lbc_lnk_icb( ssh_e, 'T', +1._wp, 1, 1 )
       !
    END SUBROUTINE icb_utl_copy
@@ -133,18 +141,18 @@
       !!----------------------------------------------------------------------
 
-      pe1 = icb_utl_bilin_e( e1t, e1u, e1v, e1f, pi, pj )         ! scale factors
+      pe1 = icb_utl_bilin_e( e1t, e1u, e1v, e1f, pi, pj )     ! scale factors
       pe2 = icb_utl_bilin_e( e2t, e2u, e2v, e2f, pi, pj )
       !
       puo  = icb_utl_bilin_h( uo_e, pi, pj, 'U' )             ! ocean velocities
       pvo  = icb_utl_bilin_h( vo_e, pi, pj, 'V' )
-      psst = icb_utl_bilin( sst_m, pi, pj, 'T' )              ! SST
-      pcn  = icb_utl_bilin( fr_i , pi, pj, 'T' )              ! ice concentration
+      psst = icb_utl_bilin_h( tt_e, pi, pj, 'T' )             ! SST
+      pcn  = icb_utl_bilin_h( fr_e , pi, pj, 'T' )            ! ice concentration
       pff  = icb_utl_bilin_h( ff_e , pi, pj, 'F' )            ! Coriolis parameter
       !
       pua  = icb_utl_bilin_h( ua_e , pi, pj, 'U' )            ! 10m wind
       pva  = icb_utl_bilin_h( va_e , pi, pj, 'V' )            ! here (ua,va) are stress => rough conversion from stress to speed
-      zcd  = 1.22_wp * 1.5e-3_wp                                  ! air density * drag coefficient
+      zcd  = 1.22_wp * 1.5e-3_wp                              ! air density * drag coefficient
       zmod = 1._wp / MAX(  1.e-20, SQRT(  zcd * SQRT( pua*pua + pva*pva)  )  )
-      pua  = pua * zmod                                           ! note: stress module=0 necessarly implies ua=va=0
+      pua  = pua * zmod                                       ! note: stress module=0 necessarly implies ua=va=0
       pva  = pva * zmod
 
@@ -155,5 +163,5 @@
       phi = 0._wp                                             ! LIM-3 case (to do)
 # else
-      phi = icb_utl_bilin(hicif, pi, pj, 'T' )                ! ice thickness
+      phi = icb_utl_bilin_h(hicth, pi, pj, 'T' )              ! ice thickness
 # endif
 #else
@@ -217,7 +225,25 @@
       END SELECT
       !
-      ! find position in this processor
-      ii = mi1( ii )
-      ij = mj1( ij )
+      ! find position in this processor. Prevent near edge problems (see #1389)
+
+      if (ii.lt.mig(1)) then
+        ii = 1
+      else if (ii.gt.mig(jpi)) then
+        ii = jpi
+      else
+        ii  = mi1( ii  )
+      end if
+
+      if (ij.lt.mjg(1)) then
+        ij = 1
+      else if (ij.gt.mjg(jpj)) then
+        ij = jpj
+      else
+        ij  = mj1( ij  )
+      end if
+
+      if (ij.eq.jpj) ij=ij-1
+      if (ii.eq.jpi) ii=ii-1      
+
       !
       icb_utl_bilin_h = ( pfld(ii,ij  ) * (1.-zi) + pfld(ii+1,ij  ) * zi ) * (1.-zj)   &
@@ -271,8 +297,25 @@
       END SELECT
       !
-      ! find position in this processor
-      ii = mi1( ii )
-      ij = mj1( ij )
-      !
+      ! find position in this processor. Prevent near edge problems (see #1389)
+
+      if (ii.lt.mig(1)) then
+        ii = 1
+      else if (ii.gt.mig(jpi)) then
+        ii = jpi
+      else
+        ii  = mi1( ii  )
+      end if
+
+      if (ij.lt.mjg(1)) then
+        ij = 1
+      else if (ij.gt.mjg(jpj)) then
+        ij = jpj
+      else
+        ij  = mj1( ij  )
+      end if
+
+      if (ij.eq.jpj) ij=ij-1
+      if (ii.eq.jpi) ii=ii-1
+
       icb_utl_bilin = ( pfld(ii,ij  ) * (1.-zi) + pfld(ii+1,ij  ) * zi ) * (1.-zj)   &
          &          + ( pfld(ii,ij+1) * (1.-zi) + pfld(ii+1,ij+1) * zi ) *     zj
@@ -309,7 +352,25 @@
       zj = pj - REAL(ij,wp)
       !
-      ! find position in this processor          !!gm use here mig, mjg arrays
-      ii = mi1( ii )
-      ij = mj1( ij )
+      ! find position in this processor. Prevent near edge problems (see #1389)
+
+      if (ii.lt.mig(1)) then
+        ii = 1
+      else if (ii.gt.mig(jpi)) then
+        ii = jpi
+      else
+        ii  = mi1( ii  )
+      end if
+
+      if (ij.lt.mjg(1)) then
+        ij = 1
+      else if (ij.gt.mjg(jpj)) then
+        ij = jpj
+      else
+        ij  = mj1( ij  )
+      end if
+
+      if (ij.eq.jpj) ij=ij-1
+      if (ii.eq.jpi) ii=ii-1
+
       z4(1) = pfld(ii  ,ij  )
       z4(2) = pfld(ii+1,ij  )
@@ -359,7 +420,24 @@
       zj = pj - REAL(ij,wp)
 
-      ! find position in this processor
-      ii = mi1( ii )
-      ij = mj1( ij )
+      ! find position in this processor. Prevent near edge problems (see #1389)
+
+      if (ii.lt.mig(1)) then
+        ii = 1
+      else if (ii.gt.mig(jpi)) then
+        ii = jpi
+      else
+        ii  = mi1( ii  )
+      end if
+
+      if (ij.lt.mjg(1)) then
+        ij = 1
+      else if (ij.gt.mjg(jpj)) then
+        ij = jpj
+      else
+        ij  = mj1( ij  )
+      end if
+
+      if (ij.eq.jpj) ij=ij-1
+      if (ii.eq.jpi) ii=ii-1
 
       IF(    0.0_wp <= zi .AND. zi < 0.5_wp   ) THEN
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/in_out_manager.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/in_out_manager.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/in_out_manager.F90	(revision 5075)
@@ -112,11 +112,12 @@
    INTEGER ::   numstp          =   -1      !: logical unit for time step
    INTEGER ::   numtime         =   -1      !: logical unit for timing
-   INTEGER ::   numout          =    6      !: logical unit for output print
+   INTEGER ::   numout          =    6      !: logical unit for output print; Set to stdout to ensure any early
+                                            !  output can be collected; do not change
    INTEGER ::   numnam_ref      =   -1      !: logical unit for reference namelist
    INTEGER ::   numnam_cfg      =   -1      !: logical unit for configuration specific namelist
-   INTEGER ::   numond          =    7      !: logical unit for Output Namelist Dynamics
+   INTEGER ::   numond          =   -1      !: logical unit for Output Namelist Dynamics
    INTEGER ::   numnam_ice_ref  =   -1      !: logical unit for ice reference namelist
    INTEGER ::   numnam_ice_cfg  =   -1      !: logical unit for ice reference namelist
-   INTEGER ::   numoni          =    8      !: logical unit for Output Namelist Ice
+   INTEGER ::   numoni          =   -1      !: logical unit for Output Namelist Ice
    INTEGER ::   numevo_ice      =   -1      !: logical unit for ice variables (temp. evolution)
    INTEGER ::   numsol          =   -1      !: logical unit for solver statistics
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/iom.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/iom.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/iom.F90	(revision 5075)
@@ -32,4 +32,9 @@
    USE trc_oce, ONLY :   nn_dttrc        !  !: frequency of step on passive tracers
    USE icb_oce, ONLY :   nclasses, class_num       !  !: iceberg classes
+#if defined key_lim3
+   USE par_ice
+#elif defined key_lim2
+   USE par_ice_2
+#endif
    USE domngb          ! ocean space and time domain
    USE phycst          ! physical constants
@@ -49,5 +54,5 @@
 #endif
    PUBLIC iom_init, iom_swap, iom_open, iom_close, iom_setkt, iom_varid, iom_get, iom_gettime, iom_rstput, iom_put
-   PUBLIC iom_getatt, iom_context_finalize
+   PUBLIC iom_getatt, iom_use, iom_context_finalize
 
    PRIVATE iom_rp0d, iom_rp1d, iom_rp2d, iom_rp3d
@@ -143,4 +148,7 @@
       CALL iom_set_axis_attr( "nfloat", (/ (REAL(ji,wp), ji=1,nfloat) /) )
 # endif
+#if defined key_lim3 || defined key_lim2
+      CALL iom_set_axis_attr( "ncatice", (/ (REAL(ji,wp), ji=1,jpl) /) )
+#endif
       CALL iom_set_axis_attr( "icbcla", class_num )
       
@@ -1015,6 +1023,9 @@
       CHARACTER(LEN=*), INTENT(in) ::   cdname
       REAL(wp)        , INTENT(in) ::   pfield0d
+      REAL(wp)        , DIMENSION(jpi,jpj) ::   zz     ! masson
 #if defined key_iomput
-      CALL xios_send_field(cdname, (/pfield0d/))
+      zz(:,:)=pfield0d
+      CALL xios_send_field(cdname, zz)
+      !CALL xios_send_field(cdname, (/pfield0d/)) 
 #else
       IF( .FALSE. )   WRITE(numout,*) cdname, pfield0d   ! useless test to avoid compilation warnings
@@ -1155,8 +1166,10 @@
    SUBROUTINE iom_context_finalize( cdname )
       CHARACTER(LEN=*), INTENT(in) :: cdname
-      !     
-      CALL iom_swap( cdname )   ! swap to cdname context
-      CALL xios_context_finalize() ! finalize the context
-      IF( cdname /= "nemo" ) CALL iom_swap( "nemo" )   ! return back to nemo context
+      !
+      IF( xios_is_valid_context(cdname) ) THEN
+         CALL iom_swap( cdname )   ! swap to cdname context
+         CALL xios_context_finalize() ! finalize the context
+         IF( cdname /= "nemo" ) CALL iom_swap( "nemo" )   ! return back to nemo context
+      ENDIF
       !
    END SUBROUTINE iom_context_finalize
@@ -1189,5 +1202,5 @@
          CASE('T')   ;   zmask(:,:,:)       = tmask(:,:,:)
          CASE('U')   ;   zmask(2:jpim1,:,:) = tmask(2:jpim1,:,:) + tmask(3:jpi,:,:)   ;   CALL lbc_lnk( zmask, 'U', 1. )
-         CASE('V')   ;   zmask(:,2:jpjm1,:) = tmask(:,2:jpjm1,:) + tmask(:,3:jpi,:)   ;   CALL lbc_lnk( zmask, 'V', 1. )
+         CASE('V')   ;   zmask(:,2:jpjm1,:) = tmask(:,2:jpjm1,:) + tmask(:,3:jpj,:)   ;   CALL lbc_lnk( zmask, 'V', 1. )
          CASE('W')   ;   zmask(:,:,2:jpk  ) = tmask(:,:,1:jpkm1) + tmask(:,:,2:jpk)   ;   zmask(:,:,1) = tmask(:,:,1)
          END SELECT
@@ -1207,9 +1220,10 @@
       !!
       !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(1,1) ::   zz = 1.
+      REAL(wp), DIMENSION(1) ::   zz = 1.
       !!----------------------------------------------------------------------
       CALL iom_set_domain_attr('scalarpoint', ni_glo=jpnij, nj_glo=1, ibegin=narea, jbegin=1, ni=1, nj=1)
-      CALL iom_set_domain_attr('scalarpoint', data_dim=1)
-      CALL iom_set_domain_attr('scalarpoint', lonvalue=(/ zz /), latvalue=(/ zz /))
+      CALL iom_set_domain_attr('scalarpoint', data_dim=2, data_ibegin = 1, data_ni = 1, data_jbegin = 1, data_nj = 1)
+      zz=REAL(narea,wp)
+      CALL iom_set_domain_attr('scalarpoint', lonvalue=zz, latvalue=zz)
 
    END SUBROUTINE set_scalar
@@ -1226,5 +1240,6 @@
       CHARACTER(len=256)             ::   clsuff                   ! suffix name
       CHARACTER(len=1)               ::   cl1                      ! 1 character
-      CHARACTER(len=2)               ::   cl2                      ! 1 character
+      CHARACTER(len=2)               ::   cl2                      ! 2 characters
+      CHARACTER(len=3)               ::   cl3                      ! 3 characters
       INTEGER                        ::   ji, jg                   ! loop counters
       INTEGER                        ::   ix, iy                   ! i-,j- index
@@ -1252,4 +1267,8 @@
          WRITE(cl2,'(i2.2)') ji 
          CALL iom_update_file_name('file'//cl2)
+      END DO
+      DO ji = 1, 999
+         WRITE(cl3,'(i3.3)') ji 
+         CALL iom_update_file_name('file'//cl3)
       END DO
 
@@ -1499,4 +1518,13 @@
 
 #endif
+
+   LOGICAL FUNCTION iom_use( cdname )
+      CHARACTER(LEN=*), INTENT(in) ::   cdname
+#if defined key_iomput
+      iom_use = xios_field_is_active( cdname )
+#else
+      iom_use = .FALSE.
+#endif
+   END FUNCTION iom_use
    
    !!======================================================================
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/iom_nf90.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/iom_nf90.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/iom_nf90.F90	(revision 5075)
@@ -217,5 +217,5 @@
          CALL iom_nf90_check(NF90_Inquire_Variable(if90id, ivarid, dimids = idimid(1:i_nvd)), clinfo)   ! dimensions ids
          iom_file(kiomid)%luld(kiv) = .FALSE.   ! default value
-         iom_file(kiomid)%dimsz(:,kiv) = 0   ! reset dimsz in case previously used
+         iom_file(kiomid)%dimsz(:,kiv) = 0      ! reset dimsz in case previously used
          DO ji = 1, i_nvd                       ! dimensions size
             CALL iom_nf90_check(NF90_Inquire_Dimension(if90id, idimid(ji), len = iom_file(kiomid)%dimsz(ji,kiv)), clinfo)   
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/prtctl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/prtctl.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/prtctl.F90	(revision 5075)
@@ -164,10 +164,12 @@
          ENDIF
 
-         IF ( clinfo3 == 'tra' )  THEN
-             zvctl1 = t_ctll(jn)
-             zvctl2 = s_ctll(jn)
-         ELSEIF ( clinfo3 == 'dyn' )   THEN
-             zvctl1 = u_ctll(jn)
-             zvctl2 = v_ctll(jn)
+         IF( PRESENT(clinfo3)) THEN
+            IF ( clinfo3 == 'tra' )  THEN
+               zvctl1 = t_ctll(jn)
+               zvctl2 = s_ctll(jn)
+            ELSEIF ( clinfo3 == 'dyn' )   THEN
+               zvctl1 = u_ctll(jn)
+               zvctl2 = v_ctll(jn)
+            ENDIF
          ENDIF
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/restart.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/restart.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/IOM/restart.F90	(revision 5075)
@@ -22,5 +22,5 @@
    USE iom             ! I/O module
    USE eosbn2          ! equation of state            (eos bn2 routine)
-   USE trdmld_oce      ! ocean active mixed layer tracers trends variables
+   USE trdmxl_oce      ! ocean active mixed layer tracers trends variables
    USE divcur          ! hor. divergence and curl      (div & cur routines)
    USE sbc_ice, ONLY : lk_lim3
@@ -120,4 +120,6 @@
                      CALL iom_rstput( kt, nitrst, numrow, 'hdivb'  , hdivb     )
                      CALL iom_rstput( kt, nitrst, numrow, 'sshb'   , sshb      )
+                     !
+      IF( lk_lim3 )  CALL iom_rstput( kt, nitrst, numrow, 'fse3t_b', fse3t_b(:,:,:) )
                      !
                      CALL iom_rstput( kt, nitrst, numrow, 'un'     , un        )     ! now fields
@@ -133,13 +135,15 @@
 #endif
                   IF( lk_lim3 ) THEN
-                     CALL iom_rstput( kt, nitrst, numrow, 'iatte'  , iatte     ) !clem modif
-                     CALL iom_rstput( kt, nitrst, numrow, 'oatte'  , oatte     ) !clem modif
+                     CALL iom_rstput( kt, nitrst, numrow, 'fraqsr_1lev'  , fraqsr_1lev     ) !clem modif
                   ENDIF
       IF( kt == nitrst ) THEN
          CALL iom_close( numrow )     ! close the restart file (only at last time step)
-         IF( .NOT. lk_trdmld )   lrst_oce = .FALSE.
+!!gm         IF( .NOT. lk_trdmld )   lrst_oce = .FALSE.
+!!gm  not sure what to do here   ===>>>  ask to Sebastian
+         lrst_oce = .FALSE.
       ENDIF
       !
    END SUBROUTINE rst_write
+
 
    SUBROUTINE rst_read_open
@@ -155,6 +159,6 @@
       LOGICAL  ::   llok
       !!----------------------------------------------------------------------
-
-      IF( numror .LE. 0 ) THEN
+      !
+      IF( numror <= 0 ) THEN
          IF(lwp) THEN                                             ! Contol prints
             WRITE(numout,*)
@@ -210,4 +214,5 @@
          CALL iom_get( numror, jpdom_autoglo, 'hdivb'  , hdivb   )
          CALL iom_get( numror, jpdom_autoglo, 'sshb'   , sshb    )
+         IF( lk_lim3 )   CALL iom_get( numror, jpdom_autoglo, 'fse3t_b', fse3t_b(:,:,:) )
       ELSE
          neuler = 0
@@ -245,9 +250,21 @@
          hdivb(:,:,:)   = hdivn(:,:,:)
          sshb (:,:)     = sshn (:,:)
-      ENDIF
-      !
-      IF( lk_lim3 ) THEN 
-         CALL iom_get( numror, jpdom_autoglo, 'iatte' , iatte ) ! clem modif
-         CALL iom_get( numror, jpdom_autoglo, 'oatte' , oatte ) ! clem modif
+
+         IF( lk_vvl ) THEN
+            DO jk = 1, jpk
+               fse3t_b(:,:,jk) = fse3t_n(:,:,jk)
+            END DO
+         ENDIF
+
+         IF( lk_lim3 .AND. .NOT. lk_vvl ) THEN
+            DO jk = 1, jpk
+               fse3t_b(:,:,jk) = fse3t_n(:,:,jk)
+            END DO
+         ENDIF
+
+      ENDIF
+      !
+      IF( lk_lim3 ) THEN
+         CALL iom_get( numror, jpdom_autoglo, 'fraqsr_1lev' , fraqsr_1lev )
       ENDIF
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lbclnk.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lbclnk.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lbclnk.F90	(revision 5075)
@@ -34,7 +34,12 @@
    END INTERFACE
 
+   INTERFACE lbc_lnk_icb
+      MODULE PROCEDURE mpp_lnk_2d_icb
+   END INTERFACE
+
    PUBLIC lbc_lnk       ! ocean lateral boundary conditions
    PUBLIC lbc_lnk_e
    PUBLIC lbc_bdy_lnk   ! ocean lateral BDY boundary conditions
+   PUBLIC lbc_lnk_icb
 
    !!----------------------------------------------------------------------
@@ -73,7 +78,12 @@
    END INTERFACE
 
+   INTERFACE lbc_lnk_icb
+      MODULE PROCEDURE lbc_lnk_2d_e
+   END INTERFACE
+
    PUBLIC   lbc_lnk       ! ocean/ice  lateral boundary conditions
    PUBLIC   lbc_lnk_e 
    PUBLIC   lbc_bdy_lnk   ! ocean lateral BDY boundary conditions
+   PUBLIC   lbc_lnk_icb
    
    !!----------------------------------------------------------------------
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lbcnfd.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lbcnfd.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lbcnfd.F90	(revision 5075)
@@ -33,5 +33,5 @@
 
    INTEGER, PUBLIC,  PARAMETER :: jpmaxngh = 3
-   INTEGER, PUBLIC                                  ::   nsndto
+   INTEGER, PUBLIC                                  ::   nsndto, nfsloop, nfeloop
    INTEGER, PUBLIC,  DIMENSION (jpmaxngh)           ::   isendto ! processes to which communicate
 
@@ -412,5 +412,5 @@
             SELECT CASE ( cd_type )
             CASE ( 'T' , 'W' )                         ! T-, W-point
-               IF (narea .ne. (jpnij - jpni + 1)) THEN
+               IF (nimpp .ne. 1) THEN
                  startloop = 1
                ELSE
@@ -420,7 +420,10 @@
                DO jk = 1, jpk
                   DO ji = startloop, nlci
-                     ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+                     ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
                      pt3dl(ji,ijpj,jk) = psgn * pt3dr(ijt,ijpj-2,jk)
                   END DO
+                  IF(nimpp .eq. 1) THEN
+                     pt3dl(1,ijpj,jk) = psgn * pt3dl(3,ijpj-2,jk)
+                  ENDIF
                END DO
 
@@ -435,5 +438,5 @@
                  DO jk = 1, jpk
                     DO ji = startloop, nlci
-                       ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+                       ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
                        jia = ji + nimpp - 1
                        ijta = jpiglo - jia + 2
@@ -448,7 +451,6 @@
 
 
-
             CASE ( 'U' )                               ! U-point
-               IF (narea .ne. (jpnij)) THEN
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -457,10 +459,16 @@
                DO jk = 1, jpk
                   DO ji = 1, endloop
-                     iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+                     iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                      pt3dl(ji,ijpj,jk) = psgn * pt3dr(iju,ijpj-2,jk)
                   END DO
-               END DO
-
-               IF (narea .ne. (jpnij)) THEN
+                  IF(nimpp .eq. 1) THEN
+                     pt3dl(   1  ,ijpj,jk) = psgn * pt3dl(    2   ,ijpj-2,jk)
+                  ENDIF
+                  IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                     pt3dl(nlci,ijpj,jk) = psgn * pt3dl(nlci-1,ijpj-2,jk)
+                  ENDIF
+               END DO
+
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -477,5 +485,5 @@
                  DO jk = 1, jpk
                     DO ji = startloop, endloop
-                      iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+                      iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                       jia = ji + nimpp - 1
                       ijua = jpiglo - jia + 1
@@ -490,5 +498,5 @@
 
             CASE ( 'V' )                               ! V-point
-               IF (narea .ne. (jpnij - jpni + 1)) THEN
+               IF (nimpp .ne. 1) THEN
                   startloop = 1
                ELSE
@@ -497,11 +505,14 @@
                DO jk = 1, jpk
                   DO ji = startloop, nlci
-                     ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+                     ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
                      pt3dl(ji,ijpj-1,jk) = psgn * pt3dr(ijt,ijpj-2,jk)
                      pt3dl(ji,ijpj  ,jk) = psgn * pt3dr(ijt,ijpj-3,jk)
                   END DO
+                  IF(nimpp .eq. 1) THEN
+                     pt3dl(1,ijpj,jk) = psgn * pt3dl(3,ijpj-3,jk)
+                  ENDIF
                END DO
             CASE ( 'F' )                               ! F-point
-               IF (narea .ne. (jpnij)) THEN
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -510,8 +521,14 @@
                DO jk = 1, jpk
                   DO ji = 1, endloop
-                     iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+                     iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                      pt3dl(ji,ijpj-1,jk) = psgn * pt3dr(iju,ijpj-2,jk)
                      pt3dl(ji,ijpj  ,jk) = psgn * pt3dr(iju,ijpj-3,jk)
                   END DO
+                  IF(nimpp .eq. 1) THEN
+                     pt3dl(   1  ,ijpj,jk) = psgn * pt3dl(    2   ,ijpj-3,jk)
+                  ENDIF
+                  IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                     pt3dl(nlci,ijpj,jk) = psgn * pt3dl(nlci-1,ijpj-3,jk)
+                  ENDIF
                END DO
             END SELECT
@@ -524,5 +541,5 @@
                DO jk = 1, jpk
                   DO ji = 1, nlci
-                     ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+                     ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                      pt3dl(ji,ijpj,jk) = psgn * pt3dr(ijt,ijpj-1,jk)
                   END DO
@@ -530,5 +547,5 @@
 
             CASE ( 'U' )                               ! U-point
-               IF (narea .ne. (jpnij)) THEN
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -537,7 +554,10 @@
                DO jk = 1, jpk
                   DO ji = 1, endloop
-                     iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 2
+                     iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
                      pt3dl(ji,ijpj,jk) = psgn * pt3dr(iju,ijpj-1,jk)
                   END DO
+                  IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                     pt3dl(nlci,ijpj,jk) = psgn * pt3dr(1,ijpj-1,jk)
+                  ENDIF
                END DO
 
@@ -545,5 +565,5 @@
                DO jk = 1, jpk
                   DO ji = 1, nlci
-                     ijt = jpiglo - ji- nimpp - nimppt(isendto(1)) + 3
+                     ijt = jpiglo - ji- nimpp - nfiimpp(isendto(1),jpnj) + 3
                      pt3dl(ji,ijpj,jk) = psgn * pt3dr(ijt,ijpj-2,jk)
                   END DO
@@ -560,5 +580,5 @@
                  DO jk = 1, jpk
                     DO ji = startloop, nlci
-                       ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+                       ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                        pt3dl(ji,ijpjm1,jk) = psgn * pt3dr(ijt,ijpjm1,jk)
                     END DO
@@ -567,5 +587,5 @@
 
             CASE ( 'F' )                               ! F-point
-               IF (narea .ne. (jpnij)) THEN
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -574,10 +594,13 @@
                DO jk = 1, jpk
                   DO ji = 1, endloop
-                     iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 2
+                     iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
                      pt3dl(ji,ijpj ,jk) = psgn * pt3dr(iju,ijpj-2,jk)
                   END DO
-               END DO
-
-               IF (narea .ne. (jpnij)) THEN
+                  IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                     pt3dl(nlci,ijpj,jk) = psgn * pt3dr(1,ijpj-2,jk)
+                  ENDIF
+               END DO
+
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -594,5 +617,5 @@
                   DO jk = 1, jpk
                      DO ji = startloop, endloop
-                        iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 2
+                        iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
                         pt3dl(ji,ijpjm1,jk) = psgn * pt3dr(iju,ijpjm1,jk)
                      END DO
@@ -656,5 +679,5 @@
          !
          CASE ( 'T' , 'W' )                               ! T- , W-points
-            IF (narea .ne. (jpnij - jpni + 1)) THEN
+            IF (nimpp .ne. 1) THEN
               startloop = 1
             ELSE
@@ -662,7 +685,10 @@
             ENDIF
             DO ji = startloop, nlci
-              ijt=jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+              ijt=jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
               pt2dl(ji,ijpj) = psgn * pt2dr(ijt,ijpjm1-1)
             END DO
+            IF (nimpp .eq. 1) THEN
+              pt2dl(1,ijpj)   = psgn * pt2dl(3,ijpj-2)
+            ENDIF
 
             IF(nimpp .ge. (jpiglo/2+1)) THEN
@@ -674,5 +700,5 @@
             ENDIF
             DO ji = startloop, nlci
-               ijt=jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+               ijt=jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
                jia = ji + nimpp - 1
                ijta = jpiglo - jia + 2
@@ -685,5 +711,5 @@
 
          CASE ( 'U' )                                     ! U-point
-            IF (narea .ne. (jpnij)) THEN
+            IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                endloop = nlci
             ELSE
@@ -691,9 +717,17 @@
             ENDIF
             DO ji = 1, endloop
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                pt2dl(ji,ijpj) = psgn * pt2dr(iju,ijpjm1-1)
             END DO
 
-            IF (narea .ne. (jpnij)) THEN
+            IF (nimpp .eq. 1) THEN
+              pt2dl(   1  ,ijpj  ) = psgn * pt2dl(    2   ,ijpj-2)
+              pt2dl(1     ,ijpj-1) = psgn * pt2dr(jpiglo - nfiimpp(isendto(1), jpnj) + 1, ijpj-1)
+            ENDIF
+            IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+              pt2dl(nlci,ijpj  ) = psgn * pt2dl(nlci-1,ijpj-2)
+            ENDIF
+
+            IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                endloop = nlci
             ELSE
@@ -708,5 +742,5 @@
             ENDIF
             DO ji = startloop, endloop
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                jia = ji + nimpp - 1
                ijua = jpiglo - jia + 1
@@ -719,5 +753,5 @@
 
          CASE ( 'V' )                                     ! V-point
-            IF (narea .ne. (jpnij - jpni + 1)) THEN
+            IF (nimpp .ne. 1) THEN
               startloop = 1
             ELSE
@@ -725,11 +759,14 @@
             ENDIF
             DO ji = startloop, nlci
-              ijt=jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+              ijt=jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
               pt2dl(ji,ijpjm1) = psgn * pt2dr(ijt,ijpjm1-1)
               pt2dl(ji,ijpj) = psgn * pt2dr(ijt,ijpjm1-2)
             END DO
+            IF (nimpp .eq. 1) THEN
+              pt2dl( 1 ,ijpj)   = psgn * pt2dl( 3 ,ijpj-3) 
+            ENDIF
 
          CASE ( 'F' )                                     ! F-point
-            IF (narea .ne. (jpnij)) THEN
+            IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                endloop = nlci
             ELSE
@@ -737,11 +774,19 @@
             ENDIF
             DO ji = 1, endloop
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                pt2dl(ji,ijpjm1) = psgn * pt2dr(iju,ijpjm1-1)
                pt2dl(ji,ijpj) = psgn * pt2dr(iju,ijpjm1-2)
             END DO
+            IF (nimpp .eq. 1) THEN
+              pt2dl(   1  ,ijpj)   = psgn * pt2dl(    2   ,ijpj-3)
+              pt2dl(   1  ,ijpj-1) = psgn * pt2dl(    2   ,ijpj-2)
+            ENDIF
+            IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+              pt2dl(nlci,ijpj)   = psgn * pt2dl(nlci-1,ijpj-3)
+              pt2dl(nlci,ijpj-1) = psgn * pt2dl(nlci-1,ijpj-2) 
+            ENDIF
 
          CASE ( 'I' )                                     ! ice U-V point (I-point)
-            IF (narea .ne. (jpnij - jpni + 1)) THEN
+            IF (nimpp .ne. 1) THEN
                startloop = 1
             ELSE
@@ -750,10 +795,10 @@
             ENDIF
             DO ji = startloop, nlci
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 5
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 5
                pt2dl(ji,ijpj) = psgn * pt2dr(iju,ijpjm1)
             END DO
 
          CASE ( 'J' )                                     ! first ice U-V point
-            IF (narea .ne. (jpnij - jpni + 1)) THEN
+            IF (nimpp .ne. 1) THEN
                startloop = 1
             ELSE
@@ -762,10 +807,10 @@
             ENDIF
             DO ji = startloop, nlci
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 5
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 5
                pt2dl(ji,ijpj) = psgn * pt2dr(iju,ijpjm1)
             END DO
 
          CASE ( 'K' )                                     ! second ice U-V point
-            IF (narea .ne. (jpnij - jpni + 1)) THEN
+            IF (nimpp .ne. 1) THEN
                startloop = 1
             ELSE
@@ -774,5 +819,5 @@
             ENDIF
             DO ji = startloop, nlci
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 5
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 5
                pt2dl(ji,ijpj) = psgn * pt2dr(iju,ijpjm1)
             END DO
@@ -785,10 +830,10 @@
          CASE ( 'T' , 'W' )                               ! T-, W-point
             DO ji = 1, nlci
-               ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+               ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                pt2dl(ji,ijpj) = psgn * pt2dr(ijt,ijpjm1)
             END DO
 
          CASE ( 'U' )                                     ! U-point
-            IF (narea .ne. (jpnij)) THEN
+            IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                endloop = nlci
             ELSE
@@ -796,11 +841,14 @@
             ENDIF
             DO ji = 1, endloop
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 2
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
                pt2dl(ji,ijpj) = psgn * pt2dr(iju,ijpjm1)
             END DO
+            IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+               pt2dl(nlci,ijpj) = psgn * pt2dr(1,ijpj-1)
+            ENDIF
 
          CASE ( 'V' )                                     ! V-point
             DO ji = 1, nlci
-               ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+               ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                pt2dl(ji,ijpj) = psgn * pt2dr(ijt,ijpjm1-1)
             END DO
@@ -813,10 +861,10 @@
             ENDIF
             DO ji = startloop, nlci
-               ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 3
+               ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 3
                pt2dl(ji,ijpjm1) = psgn * pt2dr(ijt,ijpjm1)
             END DO
 
          CASE ( 'F' )                               ! F-point
-            IF (narea .ne. (jpnij)) THEN
+            IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                endloop = nlci
             ELSE
@@ -824,9 +872,12 @@
             ENDIF
             DO ji = 1, endloop
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 2
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
                pt2dl(ji,ijpj) = psgn * pt2dr(iju,ijpjm1-1)
             END DO
-
-            IF (narea .ne. (jpnij)) THEN
+            IF((nimpp + nlci - 1) .eq. jpiglo) THEN
+                pt2dl(nlci,ijpj) = psgn * pt2dr(1,ijpj-2)
+            ENDIF
+
+            IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                endloop = nlci
             ELSE
@@ -842,15 +893,15 @@
 
             DO ji = startloop, endloop
-               iju = jpiglo - ji - nimpp - nimppt(isendto(1)) + 2
+               iju = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 2
                pt2dl(ji,ijpjm1) = psgn * pt2dr(iju,ijpjm1)
             END DO
 
          CASE ( 'I' )                                  ! ice U-V point (I-point)
-               IF (narea .ne. (jpnij - jpni + 1)) THEN
+               IF (nimpp .ne. 1) THEN
                   startloop = 1
                ELSE
                   startloop = 2
                ENDIF
-               IF (narea .ne. jpnij) THEN
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -858,15 +909,15 @@
                ENDIF
                DO ji = startloop , endloop
-                  ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+                  ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
                   pt2dl(ji,ijpj)= 0.5 * (pt2dr(ji,ijpjm1) + psgn * pt2dr(ijt,ijpjm1))
                END DO
 
          CASE ( 'J' )                                  ! first ice U-V point
-               IF (narea .ne. (jpnij - jpni + 1)) THEN
+               IF (nimpp .ne. 1) THEN
                   startloop = 1
                ELSE
                   startloop = 2
                ENDIF
-               IF (narea .ne. jpnij) THEN
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -874,15 +925,15 @@
                ENDIF
                DO ji = startloop , endloop
-                  ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+                  ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
                   pt2dl(ji,ijpj) = pt2dr(ji,ijpjm1)
                END DO
 
          CASE ( 'K' )                                  ! second ice U-V point
-               IF (narea .ne. (jpnij - jpni + 1)) THEN
+               IF (nimpp .ne. 1) THEN
                   startloop = 1
                ELSE
                   startloop = 2
                ENDIF
-               IF (narea .ne. jpnij) THEN
+               IF ((nimpp + nlci - 1) .ne. jpiglo) THEN
                   endloop = nlci
                ELSE
@@ -890,5 +941,5 @@
                ENDIF
                DO ji = startloop, endloop
-                  ijt = jpiglo - ji - nimpp - nimppt(isendto(1)) + 4
+                  ijt = jpiglo - ji - nimpp - nfiimpp(isendto(1),jpnj) + 4
                   pt2dl(ji,ijpj) = pt2dr(ijt,ijpjm1)
                END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lib_mpp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lib_mpp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/lib_mpp.F90	(revision 5075)
@@ -42,4 +42,5 @@
    !!   mpp_lnk_3d_gather :  Message passing manadgement for two 3D arrays
    !!   mpp_lnk_e     : interface (defined in lbclnk) for message passing of 2d array with extra halo (mpp_lnk_2d_e)
+   !!   mpp_lnk_icb   : interface for message passing of 2d arrays with extra halo for icebergs (mpp_lnk_2d_icb)
    !!   mpprecv         :
    !!   mppsend       :   SUBROUTINE mpp_ini_znl
@@ -56,4 +57,5 @@
    !!   mpp_lbc_north : north fold processors gathering
    !!   mpp_lbc_north_e : variant of mpp_lbc_north for extra outer halo
+   !!   mpp_lbc_north_icb : variant of mpp_lbc_north for extra outer halo with icebergs
    !!----------------------------------------------------------------------
    USE dom_oce        ! ocean space and time domain
@@ -74,4 +76,5 @@
    PUBLIC   mppsend, mpprecv                          ! needed by TAM and ICB routines
    PUBLIC   mpp_lnk_bdy_2d, mpp_lnk_bdy_3d
+   PUBLIC   mpp_lbc_north_icb, mpp_lnk_2d_icb
 
    !! * Interfaces
@@ -2026,4 +2029,5 @@
       ijpjm1 = 3
       !
+      znorthloc(:,:,:) = 0
       DO jk = 1, jpk
          DO jj = nlcj - ijpj +1, nlcj          ! put in xnorthloc the last 4 jlines of pt3d
@@ -2036,12 +2040,13 @@
       itaille = jpi * jpk * ijpj
 
-
       IF ( l_north_nogather ) THEN
          !
         ztabr(:,:,:) = 0
+        ztabl(:,:,:) = 0
+
         DO jk = 1, jpk
            DO jj = nlcj-ijpj+1, nlcj          ! First put local values into the global array
               ij = jj - nlcj + ijpj
-              DO ji = 1, nlci
+              DO ji = nfsloop, nfeloop
                  ztabl(ji,ij,jk) = pt3d(ji,jj,jk)
               END DO
@@ -2050,24 +2055,28 @@
 
          DO jr = 1,nsndto
-            IF (isendto(jr) .ne. narea) CALL mppsend( 5, znorthloc, itaille, isendto(jr)-1, ml_req_nf(jr) )
+            IF ((nfipproc(isendto(jr),jpnj) .ne. (narea-1)) .and. (nfipproc(isendto(jr),jpnj) .ne. -1)) THEN
+              CALL mppsend( 5, znorthloc, itaille, nfipproc(isendto(jr),jpnj), ml_req_nf(jr) )
+            ENDIF
          END DO
          DO jr = 1,nsndto
-            iproc = isendto(jr)
-            ildi = nldit (iproc)
-            ilei = nleit (iproc)
-            iilb = nimppt(isendto(jr)) - nimppt(isendto(1))
-            IF(isendto(jr) .ne. narea) THEN
-              CALL mpprecv(5, zfoldwk, itaille, isendto(jr)-1)
+            iproc = nfipproc(isendto(jr),jpnj)
+            IF(iproc .ne. -1) THEN
+               ilei = nleit (iproc+1)
+               ildi = nldit (iproc+1)
+               iilb = nfiimpp(isendto(jr),jpnj) - nfiimpp(isendto(1),jpnj)
+            ENDIF
+            IF((iproc .ne. (narea-1)) .and. (iproc .ne. -1)) THEN
+              CALL mpprecv(5, zfoldwk, itaille, iproc)
               DO jk = 1, jpk
                  DO jj = 1, ijpj
-                    DO ji = 1, ilei
+                    DO ji = ildi, ilei
                        ztabr(iilb+ji,jj,jk) = zfoldwk(ji,jj,jk)
                     END DO
                  END DO
               END DO
-           ELSE
+           ELSE IF (iproc .eq. (narea-1)) THEN
               DO jk = 1, jpk
                  DO jj = 1, ijpj
-                    DO ji = 1, ilei
+                    DO ji = ildi, ilei
                        ztabr(iilb+ji,jj,jk) = pt3d(ji,nlcj-ijpj+jj,jk)
                     END DO
@@ -2078,9 +2087,10 @@
          IF (l_isend) THEN
             DO jr = 1,nsndto
-               IF (isendto(jr) .ne. narea) CALL mpi_wait(ml_req_nf(jr), ml_stat, ml_err)
+               IF ((nfipproc(isendto(jr),jpnj) .ne. (narea-1)) .and. (nfipproc(isendto(jr),jpnj) .ne. -1)) THEN
+                  CALL mpi_wait(ml_req_nf(jr), ml_stat, ml_err)
+               ENDIF    
             END DO
          ENDIF
          CALL mpp_lbc_nfd( ztabl, ztabr, cd_type, psgn )   ! North fold boundary condition
-         !
          DO jk = 1, jpk
             DO jj = nlcj-ijpj+1, nlcj             ! Scatter back to pt3d
@@ -2190,7 +2200,9 @@
          !
          ztabr(:,:) = 0
+         ztabl(:,:) = 0
+
          DO jj = nlcj-ijpj+1, nlcj          ! First put local values into the global array
             ij = jj - nlcj + ijpj
-            DO ji = 1, nlci
+              DO ji = nfsloop, nfeloop
                ztabl(ji,ij) = pt2d(ji,jj)
             END DO
@@ -2198,21 +2210,25 @@
 
          DO jr = 1,nsndto
-            IF (isendto(jr) .ne. narea) CALL mppsend(5, znorthloc, itaille, isendto(jr)-1, ml_req_nf(jr))
+            IF ((nfipproc(isendto(jr),jpnj) .ne. (narea-1)) .and. (nfipproc(isendto(jr),jpnj) .ne. -1)) THEN
+               CALL mppsend(5, znorthloc, itaille, nfipproc(isendto(jr),jpnj), ml_req_nf(jr))
+            ENDIF
          END DO
          DO jr = 1,nsndto
-            iproc = isendto(jr)
-            ildi = nldit (iproc)
-            ilei = nleit (iproc)
-            iilb = nimppt(isendto(jr)) - nimppt(isendto(1))
-            IF(isendto(jr) .ne. narea) THEN
-              CALL mpprecv(5, zfoldwk, itaille, isendto(jr)-1)
+            iproc = nfipproc(isendto(jr),jpnj)
+            IF(iproc .ne. -1) THEN
+               ilei = nleit (iproc+1)
+               ildi = nldit (iproc+1)
+               iilb = nfiimpp(isendto(jr),jpnj) - nfiimpp(isendto(1),jpnj)
+            ENDIF
+            IF((iproc .ne. (narea-1)) .and. (iproc .ne. -1)) THEN
+              CALL mpprecv(5, zfoldwk, itaille, iproc)
               DO jj = 1, ijpj
-                 DO ji = 1, ilei
+                 DO ji = ildi, ilei
                     ztabr(iilb+ji,jj) = zfoldwk(ji,jj)
                  END DO
               END DO
-            ELSE
+            ELSE IF (iproc .eq. (narea-1)) THEN
               DO jj = 1, ijpj
-                 DO ji = 1, ilei
+                 DO ji = ildi, ilei
                     ztabr(iilb+ji,jj) = pt2d(ji,nlcj-ijpj+jj)
                  END DO
@@ -2222,5 +2238,7 @@
          IF (l_isend) THEN
             DO jr = 1,nsndto
-               IF (isendto(jr) .ne. narea) CALL mpi_wait(ml_req_nf(jr), ml_stat, ml_err)
+               IF ((nfipproc(isendto(jr),jpnj) .ne. (narea-1)) .and. (nfipproc(isendto(jr),jpnj) .ne. -1)) THEN
+                  CALL mpi_wait(ml_req_nf(jr), ml_stat, ml_err)
+               ENDIF
             END DO
          ENDIF
@@ -2878,4 +2896,267 @@
    END SUBROUTINE DDPDD_MPI
 
+   SUBROUTINE mpp_lbc_north_icb( pt2d, cd_type, psgn, pr2dj)
+      !!---------------------------------------------------------------------
+      !!                   ***  routine mpp_lbc_north_icb  ***
+      !!
+      !! ** Purpose :   Ensure proper north fold horizontal bondary condition
+      !!              in mpp configuration in case of jpn1 > 1 and for 2d
+      !!              array with outer extra halo
+      !!
+      !! ** Method  :   North fold condition and mpp with more than one proc
+      !!              in i-direction require a specific treatment. We gather
+      !!              the 4+2*jpr2dj northern lines of the global domain on 1
+      !!              processor and apply lbc north-fold on this sub array.
+      !!              Then we scatter the north fold array back to the processors.
+      !!              This version accounts for an extra halo with icebergs.
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   pt2d     ! 2D array with extra halo
+      CHARACTER(len=1)        , INTENT(in   ) ::   cd_type  ! nature of pt3d grid-points
+      !                                                     !   = T ,  U , V , F or W -points
+      REAL(wp)                , INTENT(in   ) ::   psgn     ! = -1. the sign change across the
+      !!                                                    ! north fold, =  1. otherwise
+      INTEGER, OPTIONAL       , INTENT(in   ) ::   pr2dj
+      INTEGER ::   ji, jj, jr
+      INTEGER ::   ierr, itaille, ildi, ilei, iilb
+      INTEGER ::   ijpj, ij, iproc, ipr2dj
+      !
+      REAL(wp), DIMENSION(:,:)  , ALLOCATABLE  ::  ztab_e, znorthloc_e
+      REAL(wp), DIMENSION(:,:,:), ALLOCATABLE  ::  znorthgloio_e
+
+      !!----------------------------------------------------------------------
+      !
+      ijpj=4
+      IF( PRESENT(pr2dj) ) THEN           ! use of additional halos
+         ipr2dj = pr2dj
+      ELSE
+         ipr2dj = 0
+      ENDIF
+      ALLOCATE( ztab_e(jpiglo,4+2*ipr2dj), znorthloc_e(jpi,4+2*ipr2dj), znorthgloio_e(jpi,4+2*ipr2dj,jpni) )
+
+      !
+      ztab_e(:,:) = 0.e0
+
+      ij=0
+      ! put in znorthloc_e the last 4 jlines of pt2d
+      DO jj = nlcj - ijpj + 1 - ipr2dj, nlcj +ipr2dj
+         ij = ij + 1
+         DO ji = 1, jpi
+            znorthloc_e(ji,ij)=pt2d(ji,jj)
+         END DO
+      END DO
+      !
+      itaille = jpi * ( ijpj + 2 * ipr2dj )
+      CALL MPI_ALLGATHER( znorthloc_e(1,1)  , itaille, MPI_DOUBLE_PRECISION,    &
+         &                znorthgloio_e(1,1,1), itaille, MPI_DOUBLE_PRECISION, ncomm_north, ierr )
+      !
+      DO jr = 1, ndim_rank_north            ! recover the global north array
+         iproc = nrank_north(jr) + 1
+         ildi = nldit (iproc)
+         ilei = nleit (iproc)
+         iilb = nimppt(iproc)
+         DO jj = 1, ijpj+2*ipr2dj
+            DO ji = ildi, ilei
+               ztab_e(ji+iilb-1,jj) = znorthgloio_e(ji,jj,jr)
+            END DO
+         END DO
+      END DO
+
+
+      ! 2. North-Fold boundary conditions
+      ! ----------------------------------
+      CALL lbc_nfd( ztab_e(:,:), cd_type, psgn, pr2dj = ipr2dj )
+
+      ij = ipr2dj
+      !! Scatter back to pt2d
+      DO jj = nlcj - ijpj + 1 , nlcj +ipr2dj
+      ij  = ij +1
+         DO ji= 1, nlci
+            pt2d(ji,jj) = ztab_e(ji+nimpp-1,ij)
+         END DO
+      END DO
+      !
+      DEALLOCATE( ztab_e, znorthloc_e, znorthgloio_e )
+      !
+   END SUBROUTINE mpp_lbc_north_icb
+
+   SUBROUTINE mpp_lnk_2d_icb( pt2d, cd_type, psgn, jpri, jprj )
+      !!----------------------------------------------------------------------
+      !!                  ***  routine mpp_lnk_2d_icb  ***
+      !!
+      !! ** Purpose :   Message passing manadgement for 2d array (with extra halo and icebergs)
+      !!
+      !! ** Method  :   Use mppsend and mpprecv function for passing mask
+      !!      between processors following neighboring subdomains.
+      !!            domain parameters
+      !!                    nlci   : first dimension of the local subdomain
+      !!                    nlcj   : second dimension of the local subdomain
+      !!                    jpri   : number of rows for extra outer halo
+      !!                    jprj   : number of columns for extra outer halo
+      !!                    nbondi : mark for "east-west local boundary"
+      !!                    nbondj : mark for "north-south local boundary"
+      !!                    noea   : number for local neighboring processors
+      !!                    nowe   : number for local neighboring processors
+      !!                    noso   : number for local neighboring processors
+      !!                    nono   : number for local neighboring processors
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER                                             , INTENT(in   ) ::   jpri
+      INTEGER                                             , INTENT(in   ) ::   jprj
+      REAL(wp), DIMENSION(1-jpri:jpi+jpri,1-jprj:jpj+jprj), INTENT(inout) ::   pt2d     ! 2D array with extra halo
+      CHARACTER(len=1)                                    , INTENT(in   ) ::   cd_type  ! nature of ptab array grid-points
+      !                                                                                 ! = T , U , V , F , W and I points
+      REAL(wp)                                            , INTENT(in   ) ::   psgn     ! =-1 the sign change across the
+      !!                                                                                ! north boundary, =  1. otherwise
+      INTEGER  ::   jl   ! dummy loop indices
+      INTEGER  ::   imigr, iihom, ijhom        ! temporary integers
+      INTEGER  ::   ipreci, iprecj             ! temporary integers
+      INTEGER  ::   ml_req1, ml_req2, ml_err   ! for key_mpi_isend
+      INTEGER, DIMENSION(MPI_STATUS_SIZE) ::   ml_stat   ! for key_mpi_isend
+      !!
+      REAL(wp), DIMENSION(1-jpri:jpi+jpri,jprecj+jprj,2) :: r2dns
+      REAL(wp), DIMENSION(1-jpri:jpi+jpri,jprecj+jprj,2) :: r2dsn
+      REAL(wp), DIMENSION(1-jprj:jpj+jprj,jpreci+jpri,2) :: r2dwe
+      REAL(wp), DIMENSION(1-jprj:jpj+jprj,jpreci+jpri,2) :: r2dew
+      !!----------------------------------------------------------------------
+
+      ipreci = jpreci + jpri      ! take into account outer extra 2D overlap area
+      iprecj = jprecj + jprj
+
+
+      ! 1. standard boundary treatment
+      ! ------------------------------
+      ! Order matters Here !!!!
+      !
+      !                                      ! East-West boundaries
+      !                                           !* Cyclic east-west
+      IF( nbondi == 2 .AND. (nperio == 1 .OR. nperio == 4 .OR. nperio == 6) ) THEN
+         pt2d(1-jpri:     1    ,:) = pt2d(jpim1-jpri:  jpim1 ,:)       ! east
+         pt2d(   jpi  :jpi+jpri,:) = pt2d(     2      :2+jpri,:)       ! west
+         !
+      ELSE                                        !* closed
+         IF( .NOT. cd_type == 'F' )   pt2d(  1-jpri   :jpreci    ,:) = 0.e0    ! south except at F-point
+                                      pt2d(nlci-jpreci+1:jpi+jpri,:) = 0.e0    ! north
+      ENDIF
+      !
+
+      ! north fold treatment
+      ! -----------------------
+      IF( npolj /= 0 ) THEN
+         !
+         SELECT CASE ( jpni )
+         CASE ( 1 )     ;   CALL lbc_nfd        ( pt2d(1:jpi,1:jpj+jprj), cd_type, psgn, pr2dj=jprj )
+         CASE DEFAULT   ;   CALL mpp_lbc_north_icb( pt2d(1:jpi,1:jpj+jprj)  , cd_type, psgn , pr2dj=jprj  )
+         END SELECT
+         !
+      ENDIF
+
+      ! 2. East and west directions exchange
+      ! ------------------------------------
+      ! we play with the neigbours AND the row number because of the periodicity
+      !
+      SELECT CASE ( nbondi )      ! Read Dirichlet lateral conditions
+      CASE ( -1, 0, 1 )                ! all exept 2 (i.e. close case)
+         iihom = nlci-nreci-jpri
+         DO jl = 1, ipreci
+            r2dew(:,jl,1) = pt2d(jpreci+jl,:)
+            r2dwe(:,jl,1) = pt2d(iihom +jl,:)
+         END DO
+      END SELECT
+      !
+      !                           ! Migrations
+      imigr = ipreci * ( jpj + 2*jprj)
+      !
+      SELECT CASE ( nbondi )
+      CASE ( -1 )
+         CALL mppsend( 2, r2dwe(1-jprj,1,1), imigr, noea, ml_req1 )
+         CALL mpprecv( 1, r2dew(1-jprj,1,2), imigr, noea )
+         IF(l_isend) CALL mpi_wait(ml_req1,ml_stat,ml_err)
+      CASE ( 0 )
+         CALL mppsend( 1, r2dew(1-jprj,1,1), imigr, nowe, ml_req1 )
+         CALL mppsend( 2, r2dwe(1-jprj,1,1), imigr, noea, ml_req2 )
+         CALL mpprecv( 1, r2dew(1-jprj,1,2), imigr, noea )
+         CALL mpprecv( 2, r2dwe(1-jprj,1,2), imigr, nowe )
+         IF(l_isend) CALL mpi_wait(ml_req1,ml_stat,ml_err)
+         IF(l_isend) CALL mpi_wait(ml_req2,ml_stat,ml_err)
+      CASE ( 1 )
+         CALL mppsend( 1, r2dew(1-jprj,1,1), imigr, nowe, ml_req1 )
+         CALL mpprecv( 2, r2dwe(1-jprj,1,2), imigr, nowe )
+         IF(l_isend) CALL mpi_wait(ml_req1,ml_stat,ml_err)
+      END SELECT
+      !
+      !                           ! Write Dirichlet lateral conditions
+      iihom = nlci - jpreci
+      !
+      SELECT CASE ( nbondi )
+      CASE ( -1 )
+         DO jl = 1, ipreci
+            pt2d(iihom+jl,:) = r2dew(:,jl,2)
+         END DO
+      CASE ( 0 )
+         DO jl = 1, ipreci
+            pt2d(jl-jpri,:) = r2dwe(:,jl,2)
+            pt2d( iihom+jl,:) = r2dew(:,jl,2)
+         END DO
+      CASE ( 1 )
+         DO jl = 1, ipreci
+            pt2d(jl-jpri,:) = r2dwe(:,jl,2)
+         END DO
+      END SELECT
+
+
+      ! 3. North and south directions
+      ! -----------------------------
+      ! always closed : we play only with the neigbours
+      !
+      IF( nbondj /= 2 ) THEN      ! Read Dirichlet lateral conditions
+         ijhom = nlcj-nrecj-jprj
+         DO jl = 1, iprecj
+            r2dsn(:,jl,1) = pt2d(:,ijhom +jl)
+            r2dns(:,jl,1) = pt2d(:,jprecj+jl)
+         END DO
+      ENDIF
+      !
+      !                           ! Migrations
+      imigr = iprecj * ( jpi + 2*jpri )
+      !
+      SELECT CASE ( nbondj )
+      CASE ( -1 )
+         CALL mppsend( 4, r2dsn(1-jpri,1,1), imigr, nono, ml_req1 )
+         CALL mpprecv( 3, r2dns(1-jpri,1,2), imigr, nono )
+         IF(l_isend) CALL mpi_wait(ml_req1,ml_stat,ml_err)
+      CASE ( 0 )
+         CALL mppsend( 3, r2dns(1-jpri,1,1), imigr, noso, ml_req1 )
+         CALL mppsend( 4, r2dsn(1-jpri,1,1), imigr, nono, ml_req2 )
+         CALL mpprecv( 3, r2dns(1-jpri,1,2), imigr, nono )
+         CALL mpprecv( 4, r2dsn(1-jpri,1,2), imigr, noso )
+         IF(l_isend) CALL mpi_wait(ml_req1,ml_stat,ml_err)
+         IF(l_isend) CALL mpi_wait(ml_req2,ml_stat,ml_err)
+      CASE ( 1 )
+         CALL mppsend( 3, r2dns(1-jpri,1,1), imigr, noso, ml_req1 )
+         CALL mpprecv( 4, r2dsn(1-jpri,1,2), imigr, noso )
+         IF(l_isend) CALL mpi_wait(ml_req1,ml_stat,ml_err)
+      END SELECT
+      !
+      !                           ! Write Dirichlet lateral conditions
+      ijhom = nlcj - jprecj
+      !
+      SELECT CASE ( nbondj )
+      CASE ( -1 )
+         DO jl = 1, iprecj
+            pt2d(:,ijhom+jl) = r2dns(:,jl,2)
+         END DO
+      CASE ( 0 )
+         DO jl = 1, iprecj
+            pt2d(:,jl-jprj) = r2dsn(:,jl,2)
+            pt2d(:,ijhom+jl ) = r2dns(:,jl,2)
+         END DO
+      CASE ( 1 )
+         DO jl = 1, iprecj
+            pt2d(:,jl-jprj) = r2dsn(:,jl,2)
+         END DO
+      END SELECT
+
+   END SUBROUTINE mpp_lnk_2d_icb
 #else
    !!----------------------------------------------------------------------
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/mppini.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/mppini.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/mppini.F90	(revision 5075)
@@ -177,4 +177,5 @@
       
 #endif
+      nfilcit(:,:) = ilcit(:,:)
       IF( irestj == 0 )   irestj = jpnj
 
@@ -255,4 +256,5 @@
          END DO
       ENDIF
+      nfiimpp(:,:)=iimppt(:,:)
 
       IF( jpnj > 1 ) THEN
@@ -270,4 +272,5 @@
          ii = 1 + MOD( jn-1, jpni )
          ij = 1 + (jn-1) / jpni
+         nfipproc(ii,ij) = jn - 1
          nimppt(jn) = iimppt(ii,ij)
          njmppt(jn) = ijmppt(ii,ij)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/mppini_2.h90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/mppini_2.h90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LBC/mppini_2.h90	(revision 5075)
@@ -67,9 +67,9 @@
          imask                                ! temporary global workspace
       REAL(wp), DIMENSION(jpiglo,jpjglo) ::   &
-         zdta                   ! temporary data workspace
+         zdta, zdtaisf                     ! temporary data workspace
       REAL(wp) ::   zidom , zjdom          ! temporary scalars
 
       ! read namelist for ln_zco
-      NAMELIST/namzgr/ ln_zco, ln_zps, ln_sco
+      NAMELIST/namzgr/ ln_zco, ln_zps, ln_sco, ln_isfcav
 
       !!----------------------------------------------------------------------
@@ -109,9 +109,17 @@
       ENDIF
       CALL iom_close (inum)
+      
+      ! used to compute the land processor in case of not masked bathy file.
+      zdtaisf(:,:) = 0.0_wp
+      IF ( ln_isfcav ) THEN
+         CALL iom_open ( 'bathy_meter.nc', inum )   ! Meter bathy in case of partial steps
+         CALL iom_get ( inum, jpdom_unknown, 'isf_draft' , zdtaisf, kstart=(/jpizoom,jpjzoom/), kcount=(/jpiglo,jpjglo/) )
+      END IF
+      CALL iom_close (inum)
 
       ! land/sea mask over the global/zoom domain
 
       imask(:,:)=1
-      WHERE ( zdta(:,:) <= 0. ) imask = 0
+      WHERE ( zdta(:,:) - zdtaisf(:,:) <= 0. ) imask = 0
 
       !  1. Dimension arrays for subdomains
@@ -143,4 +151,6 @@
       ilcj(:, irestj+1:jpnj) = jpj-1
 #endif
+
+      nfilcit(:,:) = ilci(:,:)
 
       IF(lwp) WRITE(numout,*)
@@ -175,4 +185,5 @@
          END DO
       ENDIF
+      nfiimpp(:,:) = iimppt(:,:)
 
       IF( jpnj > 1 )THEN
@@ -195,10 +206,8 @@
          ili = ilci(ii,ij)
          ilj = ilcj(ii,ij)
-
          ibondj(ii,ij) = -1
          IF( jarea >  jpni          )   ibondj(ii,ij) = 0
          IF( jarea >  (jpnj-1)*jpni )   ibondj(ii,ij) = 1
          IF( jpnj  == 1             )   ibondj(ii,ij) = 2
-
          ibondi(ii,ij) = 0
          IF( MOD(jarea,jpni) == 1 )   ibondi(ii,ij) = -1
@@ -308,4 +317,7 @@
       END DO
 
+      nfipproc(:,:) = ipproc(:,:)
+
+
       ! Control
       IF(icont+1 /= jpnij) THEN
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfdyn_c2d.h90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfdyn_c2d.h90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfdyn_c2d.h90	(revision 5075)
@@ -146,13 +146,12 @@
       INTEGER  ::   inum, iim, ijm            ! local integers
       INTEGER  ::   ifreq, il1, il2, ij, ii
-      INTEGER  ::   ijpt0,ijpt1
+      INTEGER  ::   ijpt0,ijpt1, ierror
       REAL(wp) ::   zahmeq, zcoft, zcoff, zmsk
       CHARACTER (len=15) ::   clexp
-      INTEGER, POINTER, DIMENSION(:,:)  :: icof
-      INTEGER, POINTER, DIMENSION(:,:)  :: idata
+      INTEGER,     POINTER, DIMENSION(:,:)  :: icof
+      INTEGER, ALLOCATABLE, DIMENSION(:,:)  :: idata
       !!----------------------------------------------------------------------
       !                                
       CALL wrk_alloc( jpi   , jpj   , icof  )
-      CALL wrk_alloc( jpidta, jpjdta, idata )
       !
       IF(lwp) WRITE(numout,*)
@@ -234,4 +233,7 @@
          ! ===================== equatorial strip (20N-20S) defined at t-points
          
+         ALLOCATE( idata(jpidta,jpjdta), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'ldf_dyn_c2d_orca: unable to allocate idata array' )
+         !
          CALL ctl_opn( inum, 'ahmcoef', 'OLD', 'FORMATTED', 'SEQUENTIAL', -1, numout, lwp )
          READ(inum,9101) clexp, iim, ijm
@@ -269,5 +271,6 @@
 9201     FORMAT(3x,13(i3,12x))
 9202     FORMAT(i3,41i3)
-
+         
+         DEALLOCATE(idata)
 
          ! Set ahm1 and ahm2  ( T- and F- points) (used for laplacian operator)
@@ -346,5 +349,4 @@
       !
       CALL wrk_dealloc( jpi   , jpj   , icof  )
-      CALL wrk_dealloc( jpidta, jpjdta, idata )
       !
    END SUBROUTINE ldf_dyn_c2d_orca
@@ -374,13 +376,12 @@
       INTEGER ::   iim, ijm
       INTEGER ::   ifreq, il1, il2, ij, ii
-      INTEGER ::   ijpt0,ijpt1
+      INTEGER ::   ijpt0,ijpt1, ierror
       REAL(wp) ::   zahmeq, zcoft, zcoff, zmsk, zam20s
       CHARACTER (len=15) ::   clexp
-      INTEGER, POINTER, DIMENSION(:,:)  :: icof
-      INTEGER, POINTER, DIMENSION(:,:)  :: idata
+      INTEGER,     POINTER, DIMENSION(:,:)  :: icof
+      INTEGER, ALLOCATABLE, DIMENSION(:,:)  :: idata
       !!----------------------------------------------------------------------
       !                                
       CALL wrk_alloc( jpi   , jpj   , icof  )
-      CALL wrk_alloc( jpidta, jpjdta, idata )
       !                                
 
@@ -464,4 +465,7 @@
          ! ===================== equatorial strip (20N-20S) defined at t-points
          
+         ALLOCATE( idata(jpidta,jpjdta), STAT=ierror )
+         IF( ierror > 0 )   CALL ctl_stop( 'STOP', 'ldf_dyn_c2d_orca_R1: unable to allocate idata array' )
+         !
          CALL ctl_opn( inum, 'ahmcoef', 'UNKNOWN', 'FORMATTED', 'SEQUENTIAL',   &
             &           1, numout, lwp )
@@ -501,5 +505,6 @@
 9201     FORMAT(3x,13(i3,12x))
 9202     FORMAT(i3,41i3)
-
+         
+         DEALLOCATE(idata)
 
          ! Set ahm1 and ahm2  ( T- and F- points) (used for laplacian operator)
@@ -583,5 +588,4 @@
       !
       CALL wrk_dealloc( jpi   , jpj   , icof  )
-      CALL wrk_dealloc( jpidta, jpjdta, idata )
       !
    END SUBROUTINE ldf_dyn_c2d_orca_R1
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfeiv.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfeiv.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfeiv.F90	(revision 5075)
@@ -84,22 +84,5 @@
       IF( ln_traldf_grif ) THEN
          DO jk = 1, jpk
-#  if defined key_vectopt_loop  
-!CDIR NOVERRCHK 
-            DO ji = 1, jpij   ! vector opt.
-               ! Take the max of N^2 and zero then take the vertical sum
-               ! of the square root of the resulting N^2 ( required to compute
-               ! internal Rossby radius Ro = .5 * sum_jpk(N) / f
-               zn2 = MAX( rn2b(ji,1,jk), 0._wp )
-               zn(ji,1) = zn(ji,1) + SQRT( zn2 ) * fse3w(ji,1,jk)
-               ! Compute elements required for the inverse time scale of baroclinic
-               ! eddies using the isopycnal slopes calculated in ldfslp.F :
-               ! T^-1 = sqrt(m_jpk(N^2*(r1^2+r2^2)*e3w))
-               ze3w = fse3w(ji,1,jk) * tmask(ji,1,jk)
-               zah(ji,1) = zah(ji,1) + zn2 * wslp2(ji,1,jk) * ze3w
-               zhw(ji,1) = zhw(ji,1) + ze3w
-            END DO
-#  else
             DO jj = 2, jpjm1
-!CDIR NOVERRCHK 
                DO ji = 2, jpim1
                   ! Take the max of N^2 and zero then take the vertical sum 
@@ -116,27 +99,8 @@
                END DO
             END DO
-#  endif
          END DO
       ELSE
          DO jk = 1, jpk
-#  if defined key_vectopt_loop  
-!CDIR NOVERRCHK 
-            DO ji = 1, jpij   ! vector opt.
-               ! Take the max of N^2 and zero then take the vertical sum
-               ! of the square root of the resulting N^2 ( required to compute
-               ! internal Rossby radius Ro = .5 * sum_jpk(N) / f
-               zn2 = MAX( rn2b(ji,1,jk), 0._wp )
-               zn(ji,1) = zn(ji,1) + SQRT( zn2 ) * fse3w(ji,1,jk)
-               ! Compute elements required for the inverse time scale of baroclinic
-               ! eddies using the isopycnal slopes calculated in ldfslp.F :
-               ! T^-1 = sqrt(m_jpk(N^2*(r1^2+r2^2)*e3w))
-               ze3w = fse3w(ji,1,jk) * tmask(ji,1,jk)
-               zah(ji,1) = zah(ji,1) + zn2 * ( wslpi(ji,1,jk) * wslpi(ji,1,jk)   &
-                  &                          + wslpj(ji,1,jk) * wslpj(ji,1,jk) ) * ze3w
-               zhw(ji,1) = zhw(ji,1) + ze3w
-            END DO
-#  else
             DO jj = 2, jpjm1
-!CDIR NOVERRCHK 
                DO ji = 2, jpim1
                   ! Take the max of N^2 and zero then take the vertical sum 
@@ -154,10 +118,8 @@
                END DO
             END DO
-#  endif
          END DO
       END IF
 
       DO jj = 2, jpjm1
-!CDIR NOVERRCHK 
          DO ji = fs_2, fs_jpim1   ! vector opt.
             zfw = MAX( ABS( 2. * omega * SIN( rad * gphit(ji,jj) ) ) , 1.e-10 )
@@ -165,5 +127,5 @@
             zross(ji,jj) = MAX( MIN( .4 * zn(ji,jj) / zfw, 40.e3 ), 2.e3 )
             ! Compute aeiw by multiplying Ro^2 and T^-1
-            aeiw(ji,jj) = zross(ji,jj) * zross(ji,jj) * SQRT( zah(ji,jj) / zhw(ji,jj) ) * tmask(ji,jj,1)
+            aeiw(ji,jj) = zross(ji,jj) * zross(ji,jj) * SQRT( zah(ji,jj) / zhw(ji,jj) ) * ssmask(ji,jj)
          END DO
       END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfslp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfslp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/LDF/ldfslp.F90	(revision 5075)
@@ -28,6 +28,7 @@
    USE zdfmxl         ! mixed layer depth
    USE eosbn2         ! equation of states
+   !
+   USE in_out_manager ! I/O manager
    USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
-   USE in_out_manager ! I/O manager
    USE prtctl         ! Print control
    USE wrk_nemo       ! work arrays
@@ -108,7 +109,9 @@
       REAL(wp) ::   zcj, zfj, zav, zbv, zaj, zbj   !   -      -
       REAL(wp) ::   zck, zfk,      zbw             !   -      -
+      REAL(wp) ::   zdepv, zdepu         !   -      -
       REAL(wp), POINTER, DIMENSION(:,:,:) ::  zwz, zww
       REAL(wp), POINTER, DIMENSION(:,:,:) ::  zdzr
       REAL(wp), POINTER, DIMENSION(:,:,:) ::  zgru, zgrv
+      REAL(wp), POINTER, DIMENSION(:,:  ) :: zhmlpu, zhmlpv
       !!----------------------------------------------------------------------
       !
@@ -116,4 +119,5 @@
       !
       CALL wrk_alloc( jpi,jpj,jpk, zwz, zww, zdzr, zgru, zgrv )
+      CALL wrk_alloc( jpi,jpj, zhmlpu, zhmlpv )
 
       IF ( ln_traldf_iso .OR. ln_dynldf_iso ) THEN 
@@ -136,13 +140,11 @@
          END DO
          IF( ln_zps ) THEN                           ! partial steps correction at the bottom ocean level
-# if defined key_vectopt_loop
-            DO jj = 1, 1
-               DO ji = 1, jpij-jpi   ! vector opt. (forced unrolling)
-# else
             DO jj = 1, jpjm1
                DO ji = 1, jpim1
-# endif
-                  zgru(ji,jj,mbku(ji,jj)) = gru(ji,jj)
-                  zgrv(ji,jj,mbkv(ji,jj)) = grv(ji,jj)
+! IF should be useless check zpshde (PM)
+               IF ( mbku(ji,jj) > 1 ) zgru(ji,jj,mbku(ji,jj)) = gru(ji,jj)
+               IF ( mbkv(ji,jj) > 1 ) zgrv(ji,jj,mbkv(ji,jj)) = grv(ji,jj)
+               IF ( miku(ji,jj) > 1 ) zgru(ji,jj,miku(ji,jj)) = grui(ji,jj) 
+               IF ( mikv(ji,jj) > 1 ) zgrv(ji,jj,mikv(ji,jj)) = grvi(ji,jj)
                END DO
             END DO
@@ -150,5 +152,5 @@
          !
          zdzr(:,:,1) = 0._wp        !==   Local vertical density gradient at T-point   == !   (evaluated from N^2)
-         DO jk = 2, jpkm1
+         DO jk = 1, jpkm1
             !                                ! zdzr = d/dz(prd)= - ( prd ) / grav * mk(pn2) -- at t point
             !                                !   trick: tmask(ik  )  = 0   =>   all pn2   = 0   =>   zdzr = 0
@@ -159,4 +161,10 @@
                &                 * ( pn2(:,:,jk) + pn2(:,:,jk+1) ) * ( 1._wp - 0.5_wp * tmask(:,:,jk+1) )
          END DO
+         ! surface initialisation 
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+              zdzr(ji,jj,1:mikt(ji,jj)) = 0._wp
+            END DO
+         END DO
          !
          !                          !==   Slopes just below the mixed layer   ==!
@@ -167,4 +175,14 @@
          ! ===========================      | vslp = d/dj( prd ) / d/dz( prd )
          !
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               IF (miku(ji,jj) .GT. miku(ji+1,jj)) zhmlpu(ji,jj) = hmlpt(ji  ,jj)
+               IF (miku(ji,jj) .LT. miku(ji+1,jj)) zhmlpu(ji,jj) = hmlpt(ji+1,jj)
+               IF (miku(ji,jj) .EQ. miku(ji+1,jj)) zhmlpu(ji,jj) = MAX(hmlpt(ji  ,jj), hmlpt(ji+1,jj))
+               IF (mikv(ji,jj) .GT. miku(ji,jj+1)) zhmlpv(ji,jj) = hmlpt(ji  ,jj)
+               IF (mikv(ji,jj) .LT. miku(ji,jj+1)) zhmlpv(ji,jj) = hmlpt(ji,jj+1)
+               IF (mikv(ji,jj) .EQ. miku(ji,jj+1)) zhmlpv(ji,jj) = MAX(hmlpt(ji,jj), hmlpt(ji,jj+1))
+            ENDDO
+         ENDDO
          DO jk = 2, jpkm1                            !* Slopes at u and v points
             DO jj = 2, jpjm1
@@ -180,14 +198,23 @@
                   zbv = MIN(  zbv, -100._wp* ABS( zav ) , -7.e+3_wp/fse3v(ji,jj,jk)* ABS( zav )  )
                   !                                      ! uslp and vslp output in zwz and zww, resp.
-                  zfi = MAX( omlmask(ji,jj,jk), omlmask(ji+1,jj,jk) )
-                  zfj = MAX( omlmask(ji,jj,jk), omlmask(ji,jj+1,jk) )
-                  zwz(ji,jj,jk) = ( ( 1. - zfi) * zau / ( zbu - zeps )                                              &
-                     &                   + zfi  * uslpml(ji,jj)                                                     &
-                     &                          * 0.5_wp * ( fsdept(ji+1,jj,jk)+fsdept(ji,jj,jk)-fse3u(ji,jj,1) )   &
-                     &                          / MAX( hmlpt(ji,jj), hmlpt(ji+1,jj), 5._wp ) ) * umask(ji,jj,jk)
-                  zww(ji,jj,jk) = ( ( 1. - zfj) * zav / ( zbv - zeps )                                              &
-                     &                   + zfj  * vslpml(ji,jj)                                                     &
-                     &                          * 0.5_wp * ( fsdept(ji,jj+1,jk)+fsdept(ji,jj,jk)-fse3v(ji,jj,1) )   &
-                     &                          / MAX( hmlpt(ji,jj), hmlpt(ji,jj+1), 5. ) ) * vmask(ji,jj,jk)
+                  zfi = MAX( omlmask(ji,jj,jk), omlmask(ji+1,jj,jk) ) 
+                  zfj = MAX( omlmask(ji,jj,jk), omlmask(ji,jj+1,jk) ) 
+                  ! thickness of water column between surface and level k at u/v point
+                  zdepu = 0.5_wp * (( fsdept(ji,jj,jk) + fsdept(ji+1,jj  ,jk) )                   &
+                             - 2 * MAX( risfdep(ji,jj), risfdep(ji+1,jj  ) )  &
+                             - fse3u(ji,jj,miku(ji,jj))                                         )
+                  zdepv = 0.5_wp * (( fsdept(ji,jj,jk) + fsdept(ji  ,jj+1,jk) )                   &
+                             - 2 * MAX( risfdep(ji,jj), risfdep(ji,jj+1) ) &
+                             - fse3v(ji,jj,mikv(ji,jj))                                         )
+                  zwz(ji,jj,jk) = ( 1. - zfi) * zau / ( zbu - zeps )                                              &
+                     &                 + zfi  * uslpml(ji,jj)                                                     &
+                     &                        * zdepu / MAX( zhmlpu(ji,jj), 5._wp )
+                  zwz(ji,jj,jk) = zwz(ji,jj,jk) * umask(ji,jj,jk) * umask(ji,jj,jk-1)
+                  zww(ji,jj,jk) = ( 1. - zfj) * zav / ( zbv - zeps )                                              &
+                     &                 + zfj  * vslpml(ji,jj)                                                     &
+                     &                        * zdepv / MAX( zhmlpv(ji,jj), 5._wp ) 
+                  zww(ji,jj,jk) = zww(ji,jj,jk) * vmask(ji,jj,jk) * vmask(ji,jj,jk-1)
+                  
+                 
 !!gm  modif to suppress omlmask.... (as in Griffies case)
 !                  !                                         ! jk must be >= ML level for zf=1. otherwise  zf=0.
@@ -238,7 +265,9 @@
                DO ji = fs_2, fs_jpim1   ! vector opt.
                   uslp(ji,jj,jk) = uslp(ji,jj,jk) * ( umask(ji,jj+1,jk) + umask(ji,jj-1,jk  ) ) * 0.5_wp   &
-                     &                            * ( umask(ji,jj  ,jk) + umask(ji,jj  ,jk+1) ) * 0.5_wp
+                     &                            * ( umask(ji,jj  ,jk) + umask(ji,jj  ,jk+1) ) * 0.5_wp   &
+                     &                            *   umask(ji,jj,jk-1) !* umask(ji,jj,jk) * umask(ji,jj,jk+1)
                   vslp(ji,jj,jk) = vslp(ji,jj,jk) * ( vmask(ji+1,jj,jk) + vmask(ji-1,jj,jk  ) ) * 0.5_wp   &
-                     &                            * ( vmask(ji  ,jj,jk) + vmask(ji  ,jj,jk+1) ) * 0.5_wp
+                     &                            * ( vmask(ji  ,jj,jk) + vmask(ji  ,jj,jk+1) ) * 0.5_wp   &
+                     &                            *   vmask(ji,jj,jk-1) !* vmask(ji,jj,jk) * vmask(ji,jj,jk+1)
                END DO
             END DO
@@ -253,5 +282,5 @@
                DO ji = fs_2, fs_jpim1   ! vector opt.
                   !                                  !* Local vertical density gradient evaluated from N^2
-                  zbw = zm1_2g * pn2 (ji,jj,jk) * ( prd (ji,jj,jk) + prd (ji,jj,jk-1) + 2. )
+                  zbw = zm1_2g * pn2 (ji,jj,jk) * ( prd (ji,jj,jk) + prd (ji,jj,jk-1) + 2. ) * tmask(ji,jj,jk) * tmask(ji,jj,jk-1)
                   !                                  !* Slopes at w point
                   !                                        ! i- & j-gradient of density at w-points
@@ -261,7 +290,7 @@
                      &      + vmask(ji,jj-1,jk-1) + vmask(ji,jj,jk  ) , zeps  ) *  e2t(ji,jj)
                   zai =    (  zgru (ji-1,jj,jk  ) + zgru (ji,jj,jk-1)           &
-                     &      + zgru (ji-1,jj,jk-1) + zgru (ji,jj,jk  )   ) / zci * tmask (ji,jj,jk)
+                     &      + zgru (ji-1,jj,jk-1) + zgru (ji,jj,jk  )   ) / zci
                   zaj =    (  zgrv (ji,jj-1,jk  ) + zgrv (ji,jj,jk-1)           &
-                     &      + zgrv (ji,jj-1,jk-1) + zgrv (ji,jj,jk  )   ) / zcj * tmask (ji,jj,jk)
+                     &      + zgrv (ji,jj-1,jk-1) + zgrv (ji,jj,jk  )   ) / zcj
                   !                                        ! bound the slopes: abs(zw.)<= 1/100 and zb..<0.
                   !                                        ! + kxz max= ah slope max =< e1 e3 /(pi**2 2 dt)
@@ -269,8 +298,10 @@
                   zbj = MIN( zbw , -100._wp* ABS( zaj ) , -7.e+3_wp/fse3w(ji,jj,jk)* ABS( zaj )  )
                   !                                        ! wslpi and wslpj with ML flattening (output in zwz and zww, resp.)
-                  zfk = MAX( omlmask(ji,jj,jk), omlmask(ji,jj,jk-1) )   ! zfk=1 in the ML otherwise zfk=0
-                  zck = fsdepw(ji,jj,jk) / MAX( hmlp(ji,jj), 10._wp )
-                  zwz(ji,jj,jk) = (  zai / ( zbi - zeps ) * ( 1._wp - zfk ) + zck * wslpiml(ji,jj) * zfk  ) * tmask(ji,jj,jk)
-                  zww(ji,jj,jk) = (  zaj / ( zbj - zeps ) * ( 1._wp - zfk ) + zck * wslpjml(ji,jj) * zfk  ) * tmask(ji,jj,jk)
+                  zfk = MAX( omlmask(ji,jj,jk), omlmask(ji,jj,jk-1) )    ! zfk=1 in the ML otherwise zfk=0
+                  zck = ( fsdepw(ji,jj,jk) - fsdepw(ji,jj,mikt(ji,jj) ) ) / MAX( hmlp(ji,jj), 10._wp )
+                  zwz(ji,jj,jk) = (  zai / ( zbi - zeps ) * ( 1._wp - zfk ) &
+                     &            + zck * wslpiml(ji,jj) * zfk  ) * tmask(ji,jj,jk) * tmask(ji,jj,jk-1)
+                  zww(ji,jj,jk) = (  zaj / ( zbj - zeps ) * ( 1._wp - zfk ) &
+                     &            + zck * wslpjml(ji,jj) * zfk  ) * tmask(ji,jj,jk) * tmask(ji,jj,jk-1)
 
 !!gm  modif to suppress omlmask....  (as in Griffies operator)
@@ -325,6 +356,6 @@
                   zck =   ( umask(ji,jj,jk) + umask(ji-1,jj,jk) )   &
                      &  * ( vmask(ji,jj,jk) + vmask(ji,jj-1,jk) ) * 0.25
-                  wslpi(ji,jj,jk) = wslpi(ji,jj,jk) * zck
-                  wslpj(ji,jj,jk) = wslpj(ji,jj,jk) * zck
+                  wslpi(ji,jj,jk) = wslpi(ji,jj,jk) * zck * tmask(ji,jj,jk-1) * tmask(ji,jj,jk)
+                  wslpj(ji,jj,jk) = wslpj(ji,jj,jk) * zck * tmask(ji,jj,jk-1) * tmask(ji,jj,jk)
                END DO
             END DO
@@ -377,11 +408,22 @@
          ! set the slope of diffusion to the slope of s-surfaces 
          !      ( c a u t i o n : minus sign as fsdep has positive value ) 
-         DO jk = 1, jpk 
+         DO jj = 2, jpjm1 
+            DO ji = fs_2, fs_jpim1   ! vector opt. 
+               uslp(ji,jj,1) = -1./e1u(ji,jj) * ( fsdept_b(ji+1,jj,1) - fsdept_b(ji ,jj ,1) )  * umask(ji,jj,1) 
+               vslp(ji,jj,1) = -1./e2v(ji,jj) * ( fsdept_b(ji,jj+1,1) - fsdept_b(ji ,jj ,1) )  * vmask(ji,jj,1) 
+               wslpi(ji,jj,1) = -1./e1t(ji,jj) * ( fsdepw_b(ji+1,jj,1) - fsdepw_b(ji-1,jj,1) ) * tmask(ji,jj,1) * 0.5 
+               wslpj(ji,jj,1) = -1./e2t(ji,jj) * ( fsdepw_b(ji,jj+1,1) - fsdepw_b(ji,jj-1,1) ) * tmask(ji,jj,1) * 0.5 
+            END DO 
+         END DO 
+
+         DO jk = 2, jpk 
             DO jj = 2, jpjm1 
                DO ji = fs_2, fs_jpim1   ! vector opt. 
                   uslp(ji,jj,jk) = -1./e1u(ji,jj) * ( fsdept_b(ji+1,jj,jk) - fsdept_b(ji ,jj ,jk) ) * umask(ji,jj,jk) 
                   vslp(ji,jj,jk) = -1./e2v(ji,jj) * ( fsdept_b(ji,jj+1,jk) - fsdept_b(ji ,jj ,jk) ) * vmask(ji,jj,jk) 
-                  wslpi(ji,jj,jk) = -1./e1t(ji,jj) * ( fsdepw_b(ji+1,jj,jk) - fsdepw_b(ji-1,jj,jk) ) * tmask(ji,jj,jk) * 0.5 
-                  wslpj(ji,jj,jk) = -1./e2t(ji,jj) * ( fsdepw_b(ji,jj+1,jk) - fsdepw_b(ji,jj-1,jk) ) * tmask(ji,jj,jk) * 0.5 
+                  wslpi(ji,jj,jk) = -1./e1t(ji,jj) * ( fsdepw_b(ji+1,jj,jk) - fsdepw_b(ji-1,jj,jk) ) &
+                    &                              * tmask(ji,jj,jk) * tmask(ji,jj,jk-1) * 0.5 
+                  wslpj(ji,jj,jk) = -1./e2t(ji,jj) * ( fsdepw_b(ji,jj+1,jk) - fsdepw_b(ji,jj-1,jk) ) &
+                    &                              * tmask(ji,jj,jk) * tmask(ji,jj,jk-1) * 0.5 
                END DO 
             END DO 
@@ -405,4 +447,5 @@
       
       CALL wrk_dealloc( jpi,jpj,jpk, zwz, zww, zdzr, zgru, zgrv )
+      CALL wrk_dealloc( jpi,jpj,     zhmlpu, zhmlpv)
       !
       IF( nn_timing == 1 )  CALL timing_stop('ldf_slp')
@@ -435,7 +478,5 @@
       REAL(wp) ::   zdyrho_raw, ztj_coord, ztj_raw, ztj_lim, ztj_g_raw, ztj_g_lim
       REAL(wp) ::   zdzrho_raw
-      REAL(wp) ::   zbeta0
       REAL(wp), POINTER, DIMENSION(:,:)     ::   z1_mlbw
-      REAL(wp), POINTER, DIMENSION(:,:,:)   ::   zalbet
       REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   zdxrho , zdyrho, zdzrho     ! Horizontal and vertical density gradients
       REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   zti_mlb, ztj_mlb            ! for Griffies operator only
@@ -445,5 +486,4 @@
       !
       CALL wrk_alloc( jpi,jpj, z1_mlbw )
-      CALL wrk_alloc( jpi,jpj,jpk, zalbet )
       CALL wrk_alloc( jpi,jpj,jpk,2, zdxrho , zdyrho, zdzrho,              klstart = 0  )
       CALL wrk_alloc( jpi,jpj,  2,2, zti_mlb, ztj_mlb,        kkstart = 0, klstart = 0  )
@@ -452,6 +492,4 @@
       !  Some preliminary calculation  !
       !--------------------------------!
-      !
-      CALL eos_alpbet( tsb, zalbet, zbeta0 )  !==  before local thermal/haline expension ratio at T-points  ==!
       !
       DO jl = 0, 1                            !==  unmasked before density i- j-, k-gradients  ==!
@@ -465,7 +503,7 @@
                   zdjt = ( tsb(ji,jj+1,jk,jp_tem) - tsb(ji,jj,jk,jp_tem) )    ! j-gradient of T & S at v-point
                   zdjs = ( tsb(ji,jj+1,jk,jp_sal) - tsb(ji,jj,jk,jp_sal) )
-                  zdxrho_raw = ( - zalbet(ji+ip,jj   ,jk) * zdit + zbeta0*zdis ) / e1u(ji,jj)
-                  zdyrho_raw = ( - zalbet(ji   ,jj+jp,jk) * zdjt + zbeta0*zdjs ) / e2v(ji,jj)
-                  zdxrho(ji+ip,jj   ,jk,1-ip) = SIGN( MAX(   repsln, ABS( zdxrho_raw ) ), zdxrho_raw )   ! keep the sign
+                  zdxrho_raw = ( - rab_b(ji+ip,jj   ,jk,jp_tem) * zdit + rab_b(ji+ip,jj   ,jk,jp_sal) * zdis ) / e1u(ji,jj)
+                  zdyrho_raw = ( - rab_b(ji   ,jj+jp,jk,jp_tem) * zdjt + rab_b(ji   ,jj+jp,jk,jp_sal) * zdjs ) / e2v(ji,jj)
+                  zdxrho(ji+ip,jj   ,jk,1-ip) = SIGN( MAX( repsln, ABS( zdxrho_raw ) ), zdxrho_raw )   ! keep the sign
                   zdyrho(ji   ,jj+jp,jk,1-jp) = SIGN( MAX( repsln, ABS( zdyrho_raw ) ), zdyrho_raw )
                END DO
@@ -473,17 +511,12 @@
          END DO
          !
-         IF( ln_zps.and.l_grad_zps ) THEN     ! partial steps: correction of i- & j-grad on bottom
-# if defined key_vectopt_loop
-            DO jj = 1, 1
-               DO ji = 1, jpij-jpi            ! vector opt. (forced unrolling)
-# else
+         IF( ln_zps .AND. l_grad_zps ) THEN     ! partial steps: correction of i- & j-grad on bottom
             DO jj = 1, jpjm1
                DO ji = 1, jpim1
-# endif
                   iku  = mbku(ji,jj)          ;   ikv  = mbkv(ji,jj)             ! last ocean level (u- & v-points)
                   zdit = gtsu(ji,jj,jp_tem)   ;   zdjt = gtsv(ji,jj,jp_tem)      ! i- & j-gradient of Temperature
                   zdis = gtsu(ji,jj,jp_sal)   ;   zdjs = gtsv(ji,jj,jp_sal)      ! i- & j-gradient of Salinity
-                  zdxrho_raw = ( - zalbet(ji+ip,jj   ,iku) * zdit + zbeta0*zdis ) / e1u(ji,jj)
-                  zdyrho_raw = ( - zalbet(ji   ,jj+jp,ikv) * zdjt + zbeta0*zdjs ) / e2v(ji,jj)
+                  zdxrho_raw = ( - rab_b(ji+ip,jj   ,iku,jp_tem) * zdit + rab_b(ji+ip,jj   ,iku,jp_sal) * zdis ) / e1u(ji,jj)
+                  zdyrho_raw = ( - rab_b(ji   ,jj+jp,ikv,jp_tem) * zdjt + rab_b(ji   ,jj+jp,ikv,jp_sal) * zdjs ) / e2v(ji,jj)
                   zdxrho(ji+ip,jj   ,iku,1-ip) = SIGN( MAX( repsln, ABS( zdxrho_raw ) ), zdxrho_raw )   ! keep the sign
                   zdyrho(ji   ,jj+jp,ikv,1-jp) = SIGN( MAX( repsln, ABS( zdyrho_raw ) ), zdyrho_raw )
@@ -505,6 +538,6 @@
                      zdks = 0._wp
                   ENDIF
-                  zdzrho_raw = ( - zalbet(ji   ,jj   ,jk) * zdkt + zbeta0*zdks ) / fse3w(ji,jj,jk+kp)
-                  zdzrho(ji   ,jj   ,jk,  kp) =     - MIN( - repsln,      zdzrho_raw )    ! force zdzrho >= repsln
+                  zdzrho_raw = ( - rab_b(ji,jj,jk,jp_tem) * zdkt + rab_b(ji,jj,jk,jp_sal) * zdks ) / fse3w(ji,jj,jk+kp)
+                  zdzrho(ji,jj,jk,kp) = - MIN( - repsln, zdzrho_raw )    ! force zdzrho >= repsln
                  END DO
             END DO
@@ -650,5 +683,4 @@
       !
       CALL wrk_dealloc( jpi,jpj, z1_mlbw )
-      CALL wrk_dealloc( jpi,jpj,jpk, zalbet )
       CALL wrk_dealloc( jpi,jpj,jpk,2, zdxrho , zdyrho, zdzrho,              klstart = 0  )
       CALL wrk_dealloc( jpi,jpj,  2,2, zti_mlb, ztj_mlb,        kkstart = 0, klstart = 0  )
@@ -701,13 +733,8 @@
       !                                            !==   surface mixed layer mask   !
       DO jk = 1, jpk                               ! =1 inside the mixed layer, =0 otherwise
-# if defined key_vectopt_loop
-         DO jj = 1, 1
-            DO ji = 1, jpij                        ! vector opt. (forced unrolling)
-# else
          DO jj = 1, jpj
             DO ji = 1, jpi
-# endif
                ik = nmln(ji,jj) - 1
-               IF( jk <= ik ) THEN   ;   omlmask(ji,jj,jk) = 1._wp
+               IF( jk <= ik .AND. jk >= mikt(ji,jj) ) THEN   ;   omlmask(ji,jj,jk) = 1._wp
                ELSE                  ;   omlmask(ji,jj,jk) = 0._wp
                ENDIF
@@ -727,16 +754,11 @@
       !-----------------------------------------------------------------------
       !
-# if defined key_vectopt_loop
-      DO jj = 1, 1
-         DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
-# else
       DO jj = 2, jpjm1
          DO ji = 2, jpim1
-# endif
             !                        !==   Slope at u- & v-points just below the Mixed Layer   ==!
             !
             !                        !- vertical density gradient for u- and v-slopes (from dzr at T-point)
-            iku = MIN(  MAX( 1, nmln(ji,jj) , nmln(ji+1,jj) ) , jpkm1  )   ! ML (MAX of T-pts, bound by jpkm1)
-            ikv = MIN(  MAX( 1, nmln(ji,jj) , nmln(ji,jj+1) ) , jpkm1  )   !
+            iku = MIN(  MAX( miku(ji,jj)+1, nmln(ji,jj) , nmln(ji+1,jj) ) , jpkm1  )   ! ML (MAX of T-pts, bound by jpkm1)
+            ikv = MIN(  MAX( mikv(ji,jj)+1, nmln(ji,jj) , nmln(ji,jj+1) ) , jpkm1  )   !
             zbu = 0.5_wp * ( p_dzr(ji,jj,iku) + p_dzr(ji+1,jj  ,iku) )
             zbv = 0.5_wp * ( p_dzr(ji,jj,ikv) + p_dzr(ji  ,jj+1,ikv) )
@@ -825,5 +847,5 @@
          wslpj(:,:,:) = 0._wp   ;   wslpjml(:,:) = 0._wp
 
-         IF( ln_traldf_hor .OR. ln_dynldf_hor ) THEN
+         IF(ln_sco .AND.  (ln_traldf_hor .OR. ln_dynldf_hor )) THEN
             IF(lwp)   WRITE(numout,*) '          Horizontal mixing in s-coordinate: slope = slope of s-surfaces'
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/ddatetoymdhms.h90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/ddatetoymdhms.h90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/ddatetoymdhms.h90	(revision 5075)
@@ -21,5 +21,5 @@
 
       !! * Arguments
-      REAL(dp), INTENT(IN) :: ddate
+      real(wp), INTENT(IN) :: ddate
       INTEGER, INTENT(OUT) :: kyea
       INTEGER, INTENT(OUT) :: kmon
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/diaobs.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/diaobs.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/diaobs.F90	(revision 5075)
@@ -486,14 +486,10 @@
       CALL obs_grid_setup( )
       IF ( ( n1dint < 0 ).OR.( n1dint > 1 ) ) THEN
-         IF(lwp) WRITE(numout,cform_err)
-         IF(lwp) WRITE(numout,*) ' Choice of vertical (1D) interpolation method', &
-            &                    ' is not available'
-         nstop = nstop + 1
+         CALL ctl_stop(' Choice of vertical (1D) interpolation method', &
+            &                    ' is not available')
       ENDIF
       IF ( ( n2dint < 0 ).OR.( n2dint > 4 ) ) THEN
-         IF(lwp) WRITE(numout,cform_err)
-         IF(lwp) WRITE(numout,*) ' Choice of horizontal (2D) interpolation method', &
-            &                    ' is not available'
-         nstop = nstop + 1
+         CALL ctl_stop(' Choice of horizontal (2D) interpolation method', &
+            &                    ' is not available')
       ENDIF
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_grid.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_grid.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_grid.F90	(revision 5075)
@@ -412,5 +412,7 @@
          ENDIF
 
-         IF (MAXVAL(ixpos(ipx1:ipx,ipy1:ipy)) == -1) CYCLE! cycle if no lookup points found
+         IF (.NOT. llfourflag) THEN
+            IF (MAXVAL(ixpos(ipx1:ipx,ipy1:ipy)) == -1) CYCLE! cycle if no lookup points found
+         ENDIF
          
          jimin = 0
@@ -996,5 +998,5 @@
                         df = ABS( iypos(ji+1,jj) - iypos(ji,jj) )
                         tmpy1 = df
-                        IF ( df < limxdiff ) numy1 = numy1 + 1
+                        IF ( df < limydiff ) numy1 = numy1 + 1
                         IF ( df < histsize ) histy1(df+1) = histy1(df+1) + 1
                      ENDIF
@@ -1002,5 +1004,5 @@
                         df = ABS( iypos(ji,jj+1) - iypos(ji,jj) )
                         tmpy2 = df
-                        IF ( df < limxdiff ) numy2 = numy2+1
+                        IF ( df < limydiff ) numy2 = numy2+1
                         IF ( df < histsize ) histy2(df+1) = histy2(df+1)+1
                      ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_prof.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_prof.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_prof.F90	(revision 5075)
@@ -128,10 +128,10 @@
          & zphi, &
          & zlam
-      REAL(dp), DIMENSION(:), ALLOCATABLE :: &
+      real(wp), DIMENSION(:), ALLOCATABLE :: &
          & zdat
       LOGICAL :: llvalprof
       TYPE(obfbdata), POINTER, DIMENSION(:) :: &
          & inpfiles
-      REAL(dp), DIMENSION(knumfiles) :: &
+      real(wp), DIMENSION(knumfiles) :: &
          & djulini, &
          & djulend
@@ -143,4 +143,6 @@
       INTEGER :: is3dt
       INTEGER :: ip3dt
+      INTEGER :: ios
+      INTEGER :: ioserrcount
       INTEGER, DIMENSION(kvars) :: &
          & iv3dt
@@ -280,4 +282,5 @@
                &           krefdate = irefdate(jj) )
 
+            ioserrcount=0
             IF ( ldavtimset ) THEN
                DO ji = 1, inpfiles(jj)%nobs
@@ -287,5 +290,8 @@
                   !  to be the  end of the day
                   !
-                  READ( inpfiles(jj)%cdtyp(ji), '(I4)' ) itype
+                  READ( inpfiles(jj)%cdtyp(ji), '(I4)', IOSTAT = ios, ERR = 900 ) itype
+900               IF ( ios /= 0 ) THEN
+                     itype = 0         ! Set type to zero if there is a problem in the string conversion
+                  ENDIF
                   IF ( ANY (idailyavtypes == itype ) ) THEN
                      inpfiles(jj)%ptim(ji) = &
@@ -468,5 +474,5 @@
       itypsmpp(:) = 0
       
-      
+      ioserrcount = 0      
       DO jk = 1, iproftot
          
@@ -552,5 +558,11 @@
                
                ! Instrument type
-               READ( inpfiles(jj)%cdtyp(ji), '(I4)' ) itype
+               READ( inpfiles(jj)%cdtyp(ji), '(I4)', IOSTAT = ios, ERR = 901 ) itype
+901            IF ( ios /= 0 ) THEN
+                  IF (ioserrcount == 0) CALL ctl_warn ( 'Problem converting an instrument type to integer. Setting type to zero' )
+                  ioserrcount = ioserrcount + 1
+                  itype = 0
+               ENDIF
+               
                profdata%ntyp(iprof) = itype
                
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_seaice.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_seaice.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_seaice.F90	(revision 5075)
@@ -110,14 +110,16 @@
          & zphi, &
          & zlam
-      REAL(dp), DIMENSION(:), ALLOCATABLE :: &
+      real(wp), DIMENSION(:), ALLOCATABLE :: &
          & zdat
       LOGICAL :: llvalprof
       TYPE(obfbdata), POINTER, DIMENSION(:) :: &
          & inpfiles
-      REAL(dp), DIMENSION(knumfiles) :: &
+      real(wp), DIMENSION(knumfiles) :: &
          & djulini, &
          & djulend
       INTEGER :: iobs
       INTEGER :: iobstot
+      INTEGER :: ios
+      INTEGER :: ioserrcount
       CHARACTER(len=8) :: cl_refdate
    
@@ -335,5 +337,7 @@
       ityp   (:) = 0
       itypmpp(:) = 0
-      
+
+      ioserrcount=0      
+
       DO jk = 1, iobstot
          
@@ -382,5 +386,10 @@
                
                ! Instrument type
-               READ( inpfiles(jj)%cdtyp(ji), '(I4)' ) itype
+               READ( inpfiles(jj)%cdtyp(ji), '(I4)', IOSTAT = ios, ERR = 901 ) itype
+901            IF ( ios /= 0 ) THEN
+                  IF (ioserrcount == 0) CALL ctl_warn ( 'Problem converting an instrument type to integer. Setting type to zero' ) 
+                  ioserrcount = ioserrcount + 1
+                  itype = 0
+               ENDIF
                seaicedata%ntyp(iobs) = itype
                IF ( itype < iseaicemaxtype + 1 ) THEN
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_sla.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_sla.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_sla.F90	(revision 5075)
@@ -111,5 +111,5 @@
          & zphi, &
          & zlam
-      REAL(dp), DIMENSION(:), ALLOCATABLE :: &
+      real(wp), DIMENSION(:), ALLOCATABLE :: &
          & zdat
       LOGICAL :: llvalprof
@@ -117,5 +117,5 @@
       TYPE(obfbdata), POINTER, DIMENSION(:) :: &
          & inpfiles
-      REAL(dp), DIMENSION(knumfiles) :: &
+      real(wp), DIMENSION(knumfiles) :: &
          & djulini, &
          & djulend
@@ -125,4 +125,6 @@
       INTEGER :: iobs
       INTEGER :: iobstot
+      INTEGER :: ios
+      INTEGER :: ioserrcount
       CHARACTER(len=8) :: cl_refdate
    
@@ -391,6 +393,5 @@
          &               iindx   )
       
-      CALL obs_surf_alloc( sladata, iobs, kvars, kextr, &
-         &                 jpi, jpj, kstp )
+      CALL obs_surf_alloc( sladata, iobs, kvars, kextr, kstp, jpi, jpj )
       
       ! * Read obs/positions, QC, all variable and assign to sladata
@@ -400,4 +401,6 @@
       ityp   (:) = 0
       itypmpp(:) = 0
+
+      ioserrcount = 0
       
       DO jk = 1, iobstot
@@ -451,5 +454,10 @@
                
                ! Instrument type
-               READ( inpfiles(jj)%cdtyp(ji), '(I4)' ) itype
+               READ( inpfiles(jj)%cdtyp(ji), '(I4)', IOSTAT = ios, ERR = 901 ) itype
+901            IF ( ios /= 0 ) THEN
+                  IF (ioserrcount == 0) CALL ctl_warn ( 'Problem converting an instrument type to integer. Setting type to zero' ) 
+                  ioserrcount = ioserrcount + 1
+                  itype = 0
+               ENDIF
                sladata%ntyp(iobs) = itype
                ityp(itype+1) = ityp(itype+1) + 1
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_sst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_sst.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_sst.F90	(revision 5075)
@@ -110,14 +110,16 @@
          & zphi, &
          & zlam
-      REAL(dp), DIMENSION(:), ALLOCATABLE :: &
+      real(wp), DIMENSION(:), ALLOCATABLE :: &
          & zdat
       LOGICAL :: llvalprof
       TYPE(obfbdata), POINTER, DIMENSION(:) :: &
          & inpfiles
-      REAL(dp), DIMENSION(knumfiles) :: &
+      real(wp), DIMENSION(knumfiles) :: &
          & djulini, &
          & djulend
       INTEGER :: iobs
       INTEGER :: iobstot
+      INTEGER :: ios
+      INTEGER :: ioserrcount
       CHARACTER(len=8) :: cl_refdate
    
@@ -335,4 +337,6 @@
       itypmpp(:) = 0
       
+      ioserrcount = 0
+      
       DO jk = 1, iobstot
          
@@ -381,5 +385,10 @@
                
                ! Instrument type
-               READ( inpfiles(jj)%cdtyp(ji), '(I4)' ) itype
+               READ( inpfiles(jj)%cdtyp(ji), '(I4)', IOSTAT = ios, ERR = 901 ) itype
+901            IF ( ios /= 0 ) THEN
+                  IF (ioserrcount == 0) CALL ctl_warn ( 'Problem converting an instrument type to integer. Setting type to zero' ) 
+                  ioserrcount = ioserrcount + 1
+                  itype = 0
+               ENDIF
                sstdata%ntyp(iobs) = itype
                IF ( itype < isstmaxtype + 1 ) THEN
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_vel.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_vel.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_read_vel.F90	(revision 5075)
@@ -118,5 +118,5 @@
          & zphi, &
          & zlam
-      REAL(dp), DIMENSION(:), ALLOCATABLE :: &
+      real(wp), DIMENSION(:), ALLOCATABLE :: &
          & zdat
       LOGICAL :: &
@@ -124,5 +124,5 @@
       TYPE(obfbdata), POINTER, DIMENSION(:) :: &
          & inpfiles
-      REAL(dp), DIMENSION(knumfiles) :: &
+      real(wp), DIMENSION(knumfiles) :: &
          & djulini, &
          & djulend
@@ -130,4 +130,6 @@
       INTEGER :: iproftot
       INTEGER :: iuv3dt
+      INTEGER :: ios
+      INTEGER :: ioserrcount
       INTEGER, DIMENSION(kvars) :: iv3dt
       CHARACTER(len=8) :: cl_refdate
@@ -459,5 +461,10 @@
                
                ! Instrument type
-               READ( inpfiles(jj)%cdtyp(ji), '(I4)' ) itype
+               READ( inpfiles(jj)%cdtyp(ji), '(I4)', IOSTAT = ios, ERR = 901 ) itype
+901            IF ( ios /= 0 ) THEN
+                  IF (ioserrcount == 0) CALL ctl_warn ( 'Problem converting an instrument type to integer. Setting type to zero' ) 
+                  ioserrcount = ioserrcount + 1
+                  itype = 0
+               ENDIF
                profdata%ntyp(iprof) = itype
                
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_write.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_write.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/OBS/obs_write.F90	(revision 5075)
@@ -6,9 +6,10 @@
 
    !!----------------------------------------------------------------------
-   !!   cdf_wri_p3d   : Write profile observation diagnostics in NetCDF format
+   !!   obs_wri_p3d   : Write profile observation diagnostics in NetCDF format
    !!   obs_wri_sla   : Write SLA observation related diagnostics
    !!   obs_wri_sst   : Write SST observation related diagnostics
    !!   obs_wri_seaice: Write seaice observation related diagnostics
-   !!   cdf_wri_vel   : Write velocity observation diagnostics in NetCDF format
+   !!   obs_wri_vel   : Write velocity observation diagnostics in NetCDF format
+   !!   obs_wri_stats : Print basic statistics on the data being written out
    !!----------------------------------------------------------------------
 
@@ -31,4 +32,6 @@
    USE obs_sla_types
    USE obs_rot_vel          ! Rotation of velocities
+   USE obs_mpp              ! MPP support routines for observation diagnostics
+   USE lib_mpp		    ! MPP routines
 
    IMPLICIT NONE
@@ -256,5 +259,8 @@
       ! Write the obfbdata structure
       CALL write_obfbdata( cfname, fbdata )
-      
+
+      ! Output some basic statistics
+      CALL obs_wri_stats( fbdata )
+
       CALL dealloc_obfbdata( fbdata )
      
@@ -414,4 +420,7 @@
       CALL write_obfbdata( cfname, fbdata )
 
+      ! Output some basic statistics
+      CALL obs_wri_stats( fbdata )
+
       CALL dealloc_obfbdata( fbdata )
 
@@ -565,4 +574,7 @@
       CALL write_obfbdata( cfname, fbdata )
 
+      ! Output some basic statistics
+      CALL obs_wri_stats( fbdata )
+
       CALL dealloc_obfbdata( fbdata )
 
@@ -715,4 +727,7 @@
       CALL write_obfbdata( cfname, fbdata )
 
+      ! Output some basic statistics
+      CALL obs_wri_stats( fbdata )
+
       CALL dealloc_obfbdata( fbdata )
 
@@ -722,5 +737,5 @@
       !!-----------------------------------------------------------------------
       !!
-      !!                     *** ROUTINE obs_wri_p3d  ***
+      !!                     *** ROUTINE obs_wri_vel  ***
       !!
       !! ** Purpose : Write current (profile) observation 
@@ -903,4 +918,7 @@
       CALL write_obfbdata( cfname, fbdata )
       
+      ! Output some basic statistics
+      CALL obs_wri_stats( fbdata )
+
       CALL dealloc_obfbdata( fbdata )
      
@@ -912,3 +930,73 @@
    END SUBROUTINE obs_wri_vel
 
+   SUBROUTINE obs_wri_stats( fbdata )
+      !!-----------------------------------------------------------------------
+      !!
+      !!                     *** ROUTINE obs_wri_stats  ***
+      !!
+      !! ** Purpose : Output some basic statistics of the data being written out
+      !!
+      !! ** Method  :
+      !! 
+      !! ** Action  :
+      !!
+      !!      ! 2014-08  (D. Lea) Initial version 
+      !!-----------------------------------------------------------------------
+
+      !! * Arguments
+      TYPE(obfbdata) :: fbdata
+
+      !! * Local declarations
+      INTEGER :: jvar
+      INTEGER :: jo
+      INTEGER :: jk
+
+!      INTEGER :: nlev
+!      INTEGER :: nlevmpp
+!      INTEGER :: nobsmpp
+      INTEGER :: numgoodobs
+      INTEGER :: numgoodobsmpp
+      REAL(wp) :: zsumx
+      REAL(wp) :: zsumx2
+      REAL(wp) :: zomb
+
+      IF (lwp) THEN
+         WRITE(numout,*) ''
+         WRITE(numout,*) 'obs_wri_stats :'
+         WRITE(numout,*) '~~~~~~~~~~~~~~~' 
+      ENDIF
+
+      DO jvar = 1, fbdata%nvar
+         zsumx=0.0_wp
+         zsumx2=0.0_wp
+         numgoodobs=0
+         DO jo = 1, fbdata%nobs
+            DO jk = 1, fbdata%nlev
+               IF ( ( fbdata%pob(jk,jo,jvar) < 9999.0 ) .AND. &
+                  & ( fbdata%pdep(jk,jo) < 9999.0 ) .AND. &
+                  & ( fbdata%padd(jk,jo,1,jvar) < 9999.0 ) ) THEN
+	    
+	          zomb=fbdata%pob(jk, jo, jvar)-fbdata%padd(jk, jo, 1, jvar)
+                  zsumx=zsumx+zomb
+                  zsumx2=zsumx2+zomb**2
+                  numgoodobs=numgoodobs+1
+	       ENDIF
+            ENDDO
+         ENDDO
+
+         CALL obs_mpp_sum_integer( numgoodobs, numgoodobsmpp )
+         CALL mpp_sum(zsumx)
+         CALL mpp_sum(zsumx2)
+
+         IF (lwp) THEN
+	    WRITE(numout,*) 'Type: ',fbdata%cname(jvar),'  Total number of good observations: ',numgoodobsmpp 
+	    WRITE(numout,*) 'Overall mean obs minus model of the good observations: ',zsumx/numgoodobsmpp
+            WRITE(numout,*) 'Overall RMS obs minus model of the good observations: ',sqrt( zsumx2/numgoodobsmpp )
+	    WRITE(numout,*) ''
+         ENDIF
+ 
+      ENDDO
+
+   END SUBROUTINE obs_wri_stats
+
 END MODULE obs_write
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/cpl_oasis3.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/cpl_oasis3.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/cpl_oasis3.F90	(revision 5075)
@@ -2,6 +2,5 @@
    !!======================================================================
    !!                    ***  MODULE cpl_oasis  ***
-   !! Coupled O/A : coupled ocean-atmosphere case using OASIS3 V. prism_2_4
-   !!               special case: NEMO OPA/LIM coupled to ECHAM5
+   !! Coupled O/A : coupled ocean-atmosphere case using OASIS3-MCT
    !!=====================================================================
    !! History :   
@@ -15,19 +14,16 @@
    !!   3.4  !  11-11  (C. Harris) Changes to allow mutiple category fields
    !!----------------------------------------------------------------------
+   !!----------------------------------------------------------------------
+   !!   'key_oasis3'                    coupled Ocean/Atmosphere via OASIS3
+   !!----------------------------------------------------------------------
+   !!   cpl_init     : initialization of coupled mode communication
+   !!   cpl_define   : definition of grid and fields
+   !!   cpl_snd     : snd out fields in coupled mode
+   !!   cpl_rcv     : receive fields in coupled mode
+   !!   cpl_finalize : finalize the coupled mode communication
+   !!----------------------------------------------------------------------
 #if defined key_oasis3
-   !!----------------------------------------------------------------------
-   !!   'key_oasis3'                    coupled Ocean/Atmosphere via OASIS3
-   !!----------------------------------------------------------------------
-   !!   cpl_prism_init     : initialization of coupled mode communication
-   !!   cpl_prism_define   : definition of grid and fields
-   !!   cpl_prism_snd     : snd out fields in coupled mode
-   !!   cpl_prism_rcv     : receive fields in coupled mode
-   !!   cpl_prism_finalize : finalize the coupled mode communication
-   !!----------------------------------------------------------------------
-   USE mod_prism_proto              ! OASIS3 prism module
-   USE mod_prism_def_partition_proto! OASIS3 prism module for partitioning
-   USE mod_prism_put_proto          ! OASIS3 prism module for snding
-   USE mod_prism_get_proto          ! OASIS3 prism module for receiving
-   USE mod_comprism_proto           ! OASIS3 prism module to get coupling frequency
+   USE mod_oasis                    ! OASIS3-MCT module
+#endif
    USE par_oce                      ! ocean parameters
    USE dom_oce                      ! ocean space and time domain
@@ -38,18 +34,34 @@
    PRIVATE
 
-   PUBLIC   cpl_prism_init
-   PUBLIC   cpl_prism_define
-   PUBLIC   cpl_prism_snd
-   PUBLIC   cpl_prism_rcv
-   PUBLIC   cpl_prism_freq
-   PUBLIC   cpl_prism_finalize
-
-   LOGICAL, PUBLIC, PARAMETER ::   lk_cpl = .TRUE.   !: coupled flag
+   PUBLIC   cpl_init
+   PUBLIC   cpl_define
+   PUBLIC   cpl_snd
+   PUBLIC   cpl_rcv
+   PUBLIC   cpl_freq
+   PUBLIC   cpl_finalize
+
    INTEGER, PUBLIC            ::   OASIS_Rcv  = 1    !: return code if received field
    INTEGER, PUBLIC            ::   OASIS_idle = 0    !: return code if nothing done by oasis
-   INTEGER                    ::   ncomp_id          ! id returned by prism_init_comp
+   INTEGER                    ::   ncomp_id          ! id returned by oasis_init_comp
    INTEGER                    ::   nerror            ! return error code
-
-   INTEGER, PARAMETER ::   nmaxfld=40    ! Maximum number of coupling fields
+#if ! defined key_oasis3
+   ! OASIS Variables not used. defined only for compilation purpose
+   INTEGER                    ::   OASIS_Out         = -1
+   INTEGER                    ::   OASIS_REAL        = -1
+   INTEGER                    ::   OASIS_Ok          = -1
+   INTEGER                    ::   OASIS_In          = -1
+   INTEGER                    ::   OASIS_Sent        = -1
+   INTEGER                    ::   OASIS_SentOut     = -1
+   INTEGER                    ::   OASIS_ToRest      = -1
+   INTEGER                    ::   OASIS_ToRestOut   = -1
+   INTEGER                    ::   OASIS_Recvd       = -1
+   INTEGER                    ::   OASIS_RecvOut     = -1
+   INTEGER                    ::   OASIS_FromRest    = -1
+   INTEGER                    ::   OASIS_FromRestOut = -1
+#endif
+
+   INTEGER, PUBLIC, PARAMETER ::   nmaxfld=40        ! Maximum number of coupling fields
+   INTEGER, PUBLIC, PARAMETER ::   nmaxcat=5    ! Maximum number of coupling fields
+   INTEGER, PUBLIC, PARAMETER ::   nmaxcpl=5    ! Maximum number of coupling fields
    
    TYPE, PUBLIC ::   FLD_CPL               !: Type for coupling field information
@@ -58,6 +70,7 @@
       CHARACTER(len = 1)    ::   clgrid    ! Grid type  
       REAL(wp)              ::   nsgn      ! Control of the sign change
-      INTEGER, DIMENSION(9) ::   nid       ! Id of the field (no more than 9 categories)
+      INTEGER, DIMENSION(nmaxcat,nmaxcpl) ::   nid   ! Id of the field (no more than 9 categories and 9 extrena models)
       INTEGER               ::   nct       ! Number of categories in field
+      INTEGER               ::   ncplmodel ! Maximum number of models to/from which this variable may be sent/received
    END TYPE FLD_CPL
 
@@ -73,7 +86,7 @@
 CONTAINS
 
-   SUBROUTINE cpl_prism_init( kl_comm )
+   SUBROUTINE cpl_init( kl_comm )
       !!-------------------------------------------------------------------
-      !!             ***  ROUTINE cpl_prism_init  ***
+      !!             ***  ROUTINE cpl_init  ***
       !!
       !! ** Purpose :   Initialize coupled mode communication for ocean
@@ -89,9 +102,9 @@
 
       !------------------------------------------------------------------
-      ! 1st Initialize the PRISM system for the application
+      ! 1st Initialize the OASIS system for the application
       !------------------------------------------------------------------
-      CALL prism_init_comp_proto ( ncomp_id, 'oceanx', nerror )
-      IF ( nerror /= PRISM_Ok ) &
-         CALL prism_abort_proto (ncomp_id, 'cpl_prism_init', 'Failure in prism_init_comp_proto')
+      CALL oasis_init_comp ( ncomp_id, 'oceanx', nerror )
+      IF ( nerror /= OASIS_Ok ) &
+         CALL oasis_abort (ncomp_id, 'cpl_init', 'Failure in oasis_init_comp')
 
       !------------------------------------------------------------------
@@ -99,14 +112,14 @@
       !------------------------------------------------------------------
 
-      CALL prism_get_localcomm_proto ( kl_comm, nerror )
-      IF ( nerror /= PRISM_Ok ) &
-         CALL prism_abort_proto (ncomp_id, 'cpl_prism_init','Failure in prism_get_localcomm_proto' )
-      !
-   END SUBROUTINE cpl_prism_init
-
-
-   SUBROUTINE cpl_prism_define( krcv, ksnd )
+      CALL oasis_get_localcomm ( kl_comm, nerror )
+      IF ( nerror /= OASIS_Ok ) &
+         CALL oasis_abort (ncomp_id, 'cpl_init','Failure in oasis_get_localcomm' )
+      !
+   END SUBROUTINE cpl_init
+
+
+   SUBROUTINE cpl_define( krcv, ksnd, kcplmodel )
       !!-------------------------------------------------------------------
-      !!             ***  ROUTINE cpl_prism_define  ***
+      !!             ***  ROUTINE cpl_define  ***
       !!
       !! ** Purpose :   Define grid and field information for ocean
@@ -116,17 +129,22 @@
       !!--------------------------------------------------------------------
       INTEGER, INTENT(in) ::   krcv, ksnd     ! Number of received and sent coupling fields
+      INTEGER, INTENT(in) ::   kcplmodel      ! Maximum number of models to/from which NEMO is potentialy sending/receiving data
       !
       INTEGER :: id_part
       INTEGER :: paral(5)       ! OASIS3 box partition
       INTEGER :: ishape(2,2)    ! shape of arrays passed to PSMILe
-      INTEGER :: ji,jc          ! local loop indicees
-      CHARACTER(LEN=8) :: zclname
+      INTEGER :: ji,jc,jm       ! local loop indicees
+      CHARACTER(LEN=64) :: zclname
+      CHARACTER(LEN=2) :: cli2
       !!--------------------------------------------------------------------
 
       IF(lwp) WRITE(numout,*)
-      IF(lwp) WRITE(numout,*) 'cpl_prism_define : initialization in coupled ocean/atmosphere case'
+      IF(lwp) WRITE(numout,*) 'cpl_define : initialization in coupled ocean/atmosphere case'
       IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~~~~'
       IF(lwp) WRITE(numout,*)
 
+      IF( kcplmodel > nmaxcpl ) THEN
+         CALL oasis_abort ( ncomp_id, 'cpl_define', 'kcplmodel is larger than nmaxcpl, increase nmaxcpl')   ;   RETURN
+      ENDIF
       !
       ! ... Define the shape for the area that excludes the halo
@@ -141,5 +159,5 @@
       ALLOCATE(exfld(nlei-nldi+1, nlej-nldj+1), stat = nerror)
       IF( nerror > 0 ) THEN
-         CALL prism_abort_proto ( ncomp_id, 'cpl_prism_define', 'Failure in allocating exfld')   ;   RETURN
+         CALL oasis_abort ( ncomp_id, 'cpl_define', 'Failure in allocating exfld')   ;   RETURN
       ENDIF
       !
@@ -161,23 +179,47 @@
       ENDIF
       
-      CALL prism_def_partition_proto ( id_part, paral, nerror )
+      CALL oasis_def_partition ( id_part, paral, nerror )
       !
       ! ... Announce send variables. 
       !
+      ssnd(:)%ncplmodel = kcplmodel
+      !
       DO ji = 1, ksnd
-         IF ( ssnd(ji)%laction ) THEN 
+         IF ( ssnd(ji)%laction ) THEN
+
+            IF( ssnd(ji)%nct > nmaxcat ) THEN
+               CALL oasis_abort ( ncomp_id, 'cpl_define', 'Number of categories of '//   &
+                  &              TRIM(ssnd(ji)%clname)//' is larger than nmaxcat, increase nmaxcat' )
+               RETURN
+            ENDIF
+            
             DO jc = 1, ssnd(ji)%nct
-               IF ( ssnd(ji)%nct .gt. 1 ) THEN
-                  WRITE(zclname,'( a7, i1)') ssnd(ji)%clname,jc
-               ELSE
-                  zclname=ssnd(ji)%clname
-               ENDIF
-               WRITE(numout,*) "Define",ji,jc,zclname," for",PRISM_Out
-               CALL prism_def_var_proto (ssnd(ji)%nid(jc), zclname, id_part, (/ 2, 0/),   &
-                    PRISM_Out, ishape, PRISM_REAL, nerror)
-               IF ( nerror /= PRISM_Ok ) THEN
-                  WRITE(numout,*) 'Failed to define transient ', ji, TRIM(zclname)
-                  CALL prism_abort_proto ( ssnd(ji)%nid(jc), 'cpl_prism_define', 'Failure in prism_def_var')
-               ENDIF
+               DO jm = 1, kcplmodel
+
+                  IF ( ssnd(ji)%nct .GT. 1 ) THEN
+                     WRITE(cli2,'(i2.2)') jc
+                     zclname = TRIM(ssnd(ji)%clname)//'_cat'//cli2
+                  ELSE
+                     zclname = ssnd(ji)%clname
+                  ENDIF
+                  IF ( kcplmodel  > 1 ) THEN
+                     WRITE(cli2,'(i2.2)') jm
+                     zclname = 'model'//cli2//'_'//TRIM(zclname)
+                  ENDIF
+#if defined key_agrif
+                  IF( agrif_fixed() /= 0 ) THEN 
+                     zclname=TRIM(Agrif_CFixed())//'_'//TRIM(zclname)
+                  END IF
+#endif
+                  IF( ln_ctl ) WRITE(numout,*) "Define", ji, jc, jm, " "//TRIM(zclname), " for ", OASIS_Out
+                  CALL oasis_def_var (ssnd(ji)%nid(jc,jm), zclname, id_part   , (/ 2, 0 /),   &
+                     &                OASIS_Out          , ishape , OASIS_REAL, nerror )
+                  IF ( nerror /= OASIS_Ok ) THEN
+                     WRITE(numout,*) 'Failed to define transient ', ji, jc, jm, " "//TRIM(zclname)
+                     CALL oasis_abort ( ssnd(ji)%nid(jc,jm), 'cpl_define', 'Failure in oasis_def_var' )
+                  ENDIF
+                  IF( ln_ctl .AND. ssnd(ji)%nid(jc,jm) /= -1 ) WRITE(numout,*) "variable defined in the namcouple"
+                  IF( ln_ctl .AND. ssnd(ji)%nid(jc,jm) == -1 ) WRITE(numout,*) "variable NOT defined in the namcouple"
+               END DO
             END DO
          ENDIF
@@ -186,19 +228,44 @@
       ! ... Announce received variables. 
       !
+      srcv(:)%ncplmodel = kcplmodel
+      !
       DO ji = 1, krcv
          IF ( srcv(ji)%laction ) THEN 
+            
+            IF( srcv(ji)%nct > nmaxcat ) THEN
+               CALL oasis_abort ( ncomp_id, 'cpl_define', 'Number of categories of '//   &
+                  &              TRIM(srcv(ji)%clname)//' is larger than nmaxcat, increase nmaxcat' )
+               RETURN
+            ENDIF
+            
             DO jc = 1, srcv(ji)%nct
-               IF ( srcv(ji)%nct .gt. 1 ) THEN
-                  WRITE(zclname,'( a7, i1)') srcv(ji)%clname,jc
-               ELSE
-                  zclname=srcv(ji)%clname
-               ENDIF
-               WRITE(numout,*) "Define",ji,jc,zclname," for",PRISM_In
-               CALL prism_def_var_proto ( srcv(ji)%nid(jc), zclname, id_part, (/ 2, 0/),   &
-                    &                      PRISM_In    , ishape   , PRISM_REAL, nerror)
-               IF ( nerror /= PRISM_Ok ) THEN
-                  WRITE(numout,*) 'Failed to define transient ', ji, TRIM(zclname)
-                  CALL prism_abort_proto ( srcv(ji)%nid(jc), 'cpl_prism_define', 'Failure in prism_def_var')
-               ENDIF
+               DO jm = 1, kcplmodel
+                  
+                  IF ( srcv(ji)%nct .GT. 1 ) THEN
+                     WRITE(cli2,'(i2.2)') jc
+                     zclname = TRIM(srcv(ji)%clname)//'_cat'//cli2
+                  ELSE
+                     zclname = srcv(ji)%clname
+                  ENDIF
+                  IF ( kcplmodel  > 1 ) THEN
+                     WRITE(cli2,'(i2.2)') jm
+                     zclname = 'model'//cli2//'_'//TRIM(zclname)
+                  ENDIF
+#if defined key_agrif
+                  IF( agrif_fixed() /= 0 ) THEN 
+                     zclname=TRIM(Agrif_CFixed())//'_'//TRIM(zclname)
+                  END IF
+#endif
+                  IF( ln_ctl ) WRITE(numout,*) "Define", ji, jc, jm, " "//TRIM(zclname), " for ", OASIS_In
+                  CALL oasis_def_var (srcv(ji)%nid(jc,jm), zclname, id_part   , (/ 2, 0 /),   &
+                     &                OASIS_In           , ishape , OASIS_REAL, nerror )
+                  IF ( nerror /= OASIS_Ok ) THEN
+                     WRITE(numout,*) 'Failed to define transient ', ji, jc, jm, " "//TRIM(zclname)
+                     CALL oasis_abort ( srcv(ji)%nid(jc,jm), 'cpl_define', 'Failure in oasis_def_var' )
+                  ENDIF
+                  IF( ln_ctl .AND. srcv(ji)%nid(jc,jm) /= -1 ) WRITE(numout,*) "variable defined in the namcouple"
+                  IF( ln_ctl .AND. srcv(ji)%nid(jc,jm) == -1 ) WRITE(numout,*) "variable NOT defined in the namcouple"
+
+               END DO
             END DO
          ENDIF
@@ -209,13 +276,13 @@
       !------------------------------------------------------------------
       
-      CALL prism_enddef_proto(nerror)
-      IF( nerror /= PRISM_Ok )   CALL prism_abort_proto ( ncomp_id, 'cpl_prism_define', 'Failure in prism_enddef')
-      !
-   END SUBROUTINE cpl_prism_define
+      CALL oasis_enddef(nerror)
+      IF( nerror /= OASIS_Ok )   CALL oasis_abort ( ncomp_id, 'cpl_define', 'Failure in oasis_enddef')
+      !
+   END SUBROUTINE cpl_define
    
    
-   SUBROUTINE cpl_prism_snd( kid, kstep, pdata, kinfo )
+   SUBROUTINE cpl_snd( kid, kstep, pdata, kinfo )
       !!---------------------------------------------------------------------
-      !!              ***  ROUTINE cpl_prism_snd  ***
+      !!              ***  ROUTINE cpl_snd  ***
       !!
       !! ** Purpose : - At each coupling time-step,this routine sends fields
@@ -227,5 +294,5 @@
       REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pdata
       !!
-      INTEGER                                   ::   jc        ! local loop index
+      INTEGER                                   ::   jc,jm     ! local loop index
       !!--------------------------------------------------------------------
       !
@@ -233,30 +300,35 @@
       !
       DO jc = 1, ssnd(kid)%nct
-
-         CALL prism_put_proto ( ssnd(kid)%nid(jc), kstep, pdata(nldi:nlei, nldj:nlej,jc), kinfo )
-         
-         IF ( ln_ctl ) THEN        
-            IF ( kinfo == PRISM_Sent     .OR. kinfo == PRISM_ToRest .OR.   &
-                 & kinfo == PRISM_SentOut  .OR. kinfo == PRISM_ToRestOut ) THEN
-               WRITE(numout,*) '****************'
-               WRITE(numout,*) 'prism_put_proto: Outgoing ', ssnd(kid)%clname
-               WRITE(numout,*) 'prism_put_proto: ivarid ', ssnd(kid)%nid(jc)
-               WRITE(numout,*) 'prism_put_proto:  kstep ', kstep
-               WRITE(numout,*) 'prism_put_proto:   info ', kinfo
-               WRITE(numout,*) '     - Minimum value is ', MINVAL(pdata(:,:,jc))
-               WRITE(numout,*) '     - Maximum value is ', MAXVAL(pdata(:,:,jc))
-               WRITE(numout,*) '     -     Sum value is ', SUM(pdata(:,:,jc))
-               WRITE(numout,*) '****************'
+         DO jm = 1, ssnd(kid)%ncplmodel
+        
+            IF( ssnd(kid)%nid(jc,jm) /= -1 ) THEN
+               CALL oasis_put ( ssnd(kid)%nid(jc,jm), kstep, pdata(nldi:nlei, nldj:nlej,jc), kinfo )
+               
+               IF ( ln_ctl ) THEN        
+                  IF ( kinfo == OASIS_Sent     .OR. kinfo == OASIS_ToRest .OR.   &
+                     & kinfo == OASIS_SentOut  .OR. kinfo == OASIS_ToRestOut ) THEN
+                     WRITE(numout,*) '****************'
+                     WRITE(numout,*) 'oasis_put: Outgoing ', ssnd(kid)%clname
+                     WRITE(numout,*) 'oasis_put: ivarid ', ssnd(kid)%nid(jc,jm)
+                     WRITE(numout,*) 'oasis_put:  kstep ', kstep
+                     WRITE(numout,*) 'oasis_put:   info ', kinfo
+                     WRITE(numout,*) '     - Minimum value is ', MINVAL(pdata(:,:,jc))
+                     WRITE(numout,*) '     - Maximum value is ', MAXVAL(pdata(:,:,jc))
+                     WRITE(numout,*) '     -     Sum value is ', SUM(pdata(:,:,jc))
+                     WRITE(numout,*) '****************'
+                  ENDIF
+               ENDIF
+               
             ENDIF
-         ENDIF
-
+            
+         ENDDO
       ENDDO
       !
-    END SUBROUTINE cpl_prism_snd
-
-
-   SUBROUTINE cpl_prism_rcv( kid, kstep, pdata, kinfo )
+    END SUBROUTINE cpl_snd
+
+
+   SUBROUTINE cpl_rcv( kid, kstep, pdata, pmask, kinfo )
       !!---------------------------------------------------------------------
-      !!              ***  ROUTINE cpl_prism_rcv  ***
+      !!              ***  ROUTINE cpl_rcv  ***
       !!
       !! ** Purpose : - At each coupling time-step,this routine receives fields
@@ -266,96 +338,177 @@
       INTEGER                   , INTENT(in   ) ::   kstep     ! ocean time-step in seconds
       REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pdata     ! IN to keep the value if nothing is done
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   pmask     ! coupling mask
       INTEGER                   , INTENT(  out) ::   kinfo     ! OASIS3 info argument
       !!
-      INTEGER                                   ::   jc        ! local loop index
-      LOGICAL                                   ::   llaction
+      INTEGER                                   ::   jc,jm     ! local loop index
+      LOGICAL                                   ::   llaction, llfisrt
       !!--------------------------------------------------------------------
       !
       ! receive local data from OASIS3 on every process
       !
+      kinfo = OASIS_idle
+      !
       DO jc = 1, srcv(kid)%nct
-
-         CALL prism_get_proto ( srcv(kid)%nid(jc), kstep, exfld, kinfo )         
-         
-         llaction = .false.
-         IF( kinfo == PRISM_Recvd   .OR. kinfo == PRISM_FromRest .OR.   &
-              kinfo == PRISM_RecvOut .OR. kinfo == PRISM_FromRestOut )   llaction = .TRUE.
-         
-         IF ( ln_ctl )   WRITE(numout,*) "llaction, kinfo, kstep, ivarid: " , llaction, kinfo, kstep, srcv(kid)%nid(jc)
-         
-         IF ( llaction ) THEN
-            
-            kinfo = OASIS_Rcv
-            pdata(nldi:nlei, nldj:nlej,jc) = exfld(:,:)
-            
-            !--- Fill the overlap areas and extra hallows (mpp)
-            !--- check periodicity conditions (all cases)
-            CALL lbc_lnk( pdata(:,:,jc), srcv(kid)%clgrid, srcv(kid)%nsgn )   
-            
-            IF ( ln_ctl ) THEN        
-               WRITE(numout,*) '****************'
-               WRITE(numout,*) 'prism_get_proto: Incoming ', srcv(kid)%clname
-               WRITE(numout,*) 'prism_get_proto: ivarid '  , srcv(kid)%nid(jc)
-               WRITE(numout,*) 'prism_get_proto:   kstep', kstep
-               WRITE(numout,*) 'prism_get_proto:   info ', kinfo
-               WRITE(numout,*) '     - Minimum value is ', MINVAL(pdata(:,:,jc))
-               WRITE(numout,*) '     - Maximum value is ', MAXVAL(pdata(:,:,jc))
-               WRITE(numout,*) '     -     Sum value is ', SUM(pdata(:,:,jc))
-               WRITE(numout,*) '****************'
+         llfisrt = .TRUE.
+
+         DO jm = 1, srcv(kid)%ncplmodel
+
+            IF( srcv(kid)%nid(jc,jm) /= -1 ) THEN
+
+               CALL oasis_get ( srcv(kid)%nid(jc,jm), kstep, exfld, kinfo )         
+               
+               llaction =  kinfo == OASIS_Recvd   .OR. kinfo == OASIS_FromRest .OR.   &
+                  &        kinfo == OASIS_RecvOut .OR. kinfo == OASIS_FromRestOut
+               
+               IF ( ln_ctl )   WRITE(numout,*) "llaction, kinfo, kstep, ivarid: " , llaction, kinfo, kstep, srcv(kid)%nid(jc,jm)
+               
+               IF ( llaction ) THEN
+                  
+                  kinfo = OASIS_Rcv
+                  IF( llfisrt ) THEN 
+                     pdata(nldi:nlei,nldj:nlej,jc) =                                 exfld(:,:) * pmask(nldi:nlei,nldj:nlej,jm)
+                     llfisrt = .FALSE.
+                  ELSE
+                     pdata(nldi:nlei,nldj:nlej,jc) = pdata(nldi:nlei,nldj:nlej,jc) + exfld(:,:) * pmask(nldi:nlei,nldj:nlej,jm)
+                  ENDIF
+                  
+                  IF ( ln_ctl ) THEN        
+                     WRITE(numout,*) '****************'
+                     WRITE(numout,*) 'oasis_get: Incoming ', srcv(kid)%clname
+                     WRITE(numout,*) 'oasis_get: ivarid '  , srcv(kid)%nid(jc,jm)
+                     WRITE(numout,*) 'oasis_get:   kstep', kstep
+                     WRITE(numout,*) 'oasis_get:   info ', kinfo
+                     WRITE(numout,*) '     - Minimum value is ', MINVAL(pdata(:,:,jc))
+                     WRITE(numout,*) '     - Maximum value is ', MAXVAL(pdata(:,:,jc))
+                     WRITE(numout,*) '     -     Sum value is ', SUM(pdata(:,:,jc))
+                     WRITE(numout,*) '****************'
+                  ENDIF
+                  
+               ENDIF
+               
             ENDIF
             
-         ELSE
-            kinfo = OASIS_idle     
-         ENDIF
-         
+         ENDDO
+
+         !--- Fill the overlap areas and extra hallows (mpp)
+         !--- check periodicity conditions (all cases)
+         IF( .not. llfisrt )   CALL lbc_lnk( pdata(:,:,jc), srcv(kid)%clgrid, srcv(kid)%nsgn )   
+ 
       ENDDO
       !
-   END SUBROUTINE cpl_prism_rcv
-
-
-   INTEGER FUNCTION cpl_prism_freq( kid )  
+   END SUBROUTINE cpl_rcv
+
+
+   INTEGER FUNCTION cpl_freq( kid )  
       !!---------------------------------------------------------------------
-      !!              ***  ROUTINE cpl_prism_freq  ***
+      !!              ***  ROUTINE cpl_freq  ***
       !!
       !! ** Purpose : - send back the coupling frequency for a particular field
       !!----------------------------------------------------------------------
-      INTEGER,INTENT(in) ::   kid   ! variable index 
+      INTEGER,INTENT(in) ::   kid   ! variable index
+      !!
+      INTEGER               :: info
+      INTEGER, DIMENSION(1) :: itmp
       !!----------------------------------------------------------------------
-      cpl_prism_freq = ig_def_freq( kid )
-      !
-   END FUNCTION cpl_prism_freq
-
-
-   SUBROUTINE cpl_prism_finalize
+      CALL oasis_get_freqs(kid, 1, itmp, info)
+      cpl_freq = itmp(1)
+      !
+   END FUNCTION cpl_freq
+
+
+   SUBROUTINE cpl_finalize
       !!---------------------------------------------------------------------
-      !!              ***  ROUTINE cpl_prism_finalize  ***
+      !!              ***  ROUTINE cpl_finalize  ***
       !!
       !! ** Purpose : - Finalizes the coupling. If MPI_init has not been
-      !!      called explicitly before cpl_prism_init it will also close
+      !!      called explicitly before cpl_init it will also close
       !!      MPI communication.
       !!----------------------------------------------------------------------
       !
       DEALLOCATE( exfld )
-      CALL prism_terminate_proto( nerror )         
-      !
-   END SUBROUTINE cpl_prism_finalize
-
-#else
-   !!----------------------------------------------------------------------
-   !!   Default case          Dummy module          Forced Ocean/Atmosphere
-   !!----------------------------------------------------------------------
-   USE in_out_manager               ! I/O manager
-   LOGICAL, PUBLIC, PARAMETER :: lk_cpl = .FALSE.   !: coupled flag
-   PUBLIC cpl_prism_init
-   PUBLIC cpl_prism_finalize
-CONTAINS
-   SUBROUTINE cpl_prism_init (kl_comm) 
-      INTEGER, INTENT(out)   :: kl_comm       ! local communicator of the model
-      kl_comm = -1
-      WRITE(numout,*) 'cpl_prism_init: Error you sould not be there...'
-   END SUBROUTINE cpl_prism_init
-   SUBROUTINE cpl_prism_finalize
-      WRITE(numout,*) 'cpl_prism_finalize: Error you sould not be there...'
-   END SUBROUTINE cpl_prism_finalize
+      IF (nstop == 0) THEN
+         CALL oasis_terminate( nerror )         
+      ELSE
+         CALL oasis_abort( ncomp_id, "cpl_finalize", "NEMO ABORT STOP" )
+      ENDIF       
+      !
+   END SUBROUTINE cpl_finalize
+
+#if ! defined key_oasis3
+
+   !!----------------------------------------------------------------------
+   !!   No OASIS Library          OASIS3 Dummy module...
+   !!----------------------------------------------------------------------
+
+   SUBROUTINE oasis_init_comp(k1,cd1,k2)
+      CHARACTER(*), INTENT(in   ) ::  cd1
+      INTEGER     , INTENT(  out) ::  k1,k2
+      k1 = -1 ; k2 = -1
+      WRITE(numout,*) 'oasis_init_comp: Error you sould not be there...', cd1
+   END SUBROUTINE oasis_init_comp
+
+   SUBROUTINE oasis_abort(k1,cd1,cd2)
+      INTEGER     , INTENT(in   ) ::  k1
+      CHARACTER(*), INTENT(in   ) ::  cd1,cd2
+      WRITE(numout,*) 'oasis_abort: Error you sould not be there...', cd1, cd2
+   END SUBROUTINE oasis_abort
+
+   SUBROUTINE oasis_get_localcomm(k1,k2)
+      INTEGER     , INTENT(  out) ::  k1,k2
+      k1 = -1 ; k2 = -1
+      WRITE(numout,*) 'oasis_get_localcomm: Error you sould not be there...'
+   END SUBROUTINE oasis_get_localcomm
+
+   SUBROUTINE oasis_def_partition(k1,k2,k3)
+      INTEGER     , INTENT(  out) ::  k1,k3
+      INTEGER     , INTENT(in   ) ::  k2(5)
+      k1 = k2(1) ; k3 = k2(5)
+      WRITE(numout,*) 'oasis_def_partition: Error you sould not be there...'
+   END SUBROUTINE oasis_def_partition
+
+   SUBROUTINE oasis_def_var(k1,cd1,k2,k3,k4,k5,k6,k7)
+      CHARACTER(*), INTENT(in   ) ::  cd1
+      INTEGER     , INTENT(in   ) ::  k2,k3(2),k4,k5(2,2),k6
+      INTEGER     , INTENT(  out) ::  k1,k7
+      k1 = -1 ; k7 = -1
+      WRITE(numout,*) 'oasis_def_var: Error you sould not be there...', cd1
+   END SUBROUTINE oasis_def_var
+
+   SUBROUTINE oasis_enddef(k1)
+      INTEGER     , INTENT(  out) ::  k1
+      k1 = -1
+      WRITE(numout,*) 'oasis_enddef: Error you sould not be there...'
+   END SUBROUTINE oasis_enddef
+  
+   SUBROUTINE oasis_put(k1,k2,p1,k3)
+      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::  p1
+      INTEGER                 , INTENT(in   ) ::  k1,k2
+      INTEGER                 , INTENT(  out) ::  k3
+      k3 = -1
+      WRITE(numout,*) 'oasis_put: Error you sould not be there...'
+   END SUBROUTINE oasis_put
+
+   SUBROUTINE oasis_get(k1,k2,p1,k3)
+      REAL(wp), DIMENSION(:,:), INTENT(  out) ::  p1
+      INTEGER                 , INTENT(in   ) ::  k1,k2
+      INTEGER                 , INTENT(  out) ::  k3
+      p1(1,1) = -1. ; k3 = -1
+      WRITE(numout,*) 'oasis_get: Error you sould not be there...'
+   END SUBROUTINE oasis_get
+
+   SUBROUTINE oasis_get_freqs(k1,k2,k3,k4)
+      INTEGER              , INTENT(in   ) ::  k1,k2
+      INTEGER, DIMENSION(1), INTENT(  out) ::  k3
+      INTEGER              , INTENT(  out) ::  k4
+      k3(1) = k1 ; k4 = k2
+      WRITE(numout,*) 'oasis_get_freqs: Error you sould not be there...'
+   END SUBROUTINE oasis_get_freqs
+
+   SUBROUTINE oasis_terminate(k1)
+      INTEGER     , INTENT(  out) ::  k1
+      k1 = -1
+      WRITE(numout,*) 'oasis_terminate: Error you sould not be there...'
+   END SUBROUTINE oasis_terminate
+   
 #endif
 
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/cpl_oasis4.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/cpl_oasis4.F90	(revision 5074)
+++ 	(revision )
@@ -1,481 +1,0 @@
-MODULE cpl_oasis4
-   !!======================================================================
-   !!                    ***  MODULE cpl_oasis  ***
-   !! Coupled O/A : coupled ocean-atmosphere case using OASIS4
-   !!=====================================================================
-   !! History :   
-   !!   9.0  !  2004-06  (R. Redler, NEC Laboratories Europe, St Augustin, Germany) Original code
-   !!    -   !  2004-11  (R. Redler, NEC Laboratories Europe; N. Keenlyside, W. Park, IFM-GEOMAR, Kiel, Germany) revision
-   !!    -   !  2004-11  (V. Gayler, MPI M&D) Grid writing
-   !!    -   !  2005-08  (R. Redler, W. Park) frld initialization, paral(2) revision
-   !!    -   !  2005-09  (R. Redler) extended to allow for communication over root only
-   !!    -   !  2006-01  (W. Park) modification of physical part
-   !!    -   !  2006-02  (R. Redler, W. Park) buffer array fix for root exchange
-   !!    -   !  2010-10  (E. Maisonnave and S. Masson) complete rewrite
-   !!----------------------------------------------------------------------
-#if defined key_oasis4
-   !!----------------------------------------------------------------------
-   !!   'key_oasis4'                    coupled Ocean/Atmosphere via OASIS4
-   !!----------------------------------------------------------------------
-   !!   cpl_prism_init     : initialization of coupled mode communication
-   !!   cpl_prism_define   : definition of grid and fields
-   !!   cpl_prism_snd      : snd out fields in coupled mode
-   !!   cpl_prism_rcv      : receive fields in coupled mode
-   !!   cpl_prism_update_time : update date sent to Oasis
-   !!   cpl_prism_finalize : finalize the coupled mode communication
-   !!----------------------------------------------------------------------
-   USE prism            ! OASIS4 prism module
-   USE par_oce          ! ocean parameters
-   USE dom_oce          ! ocean space and time domain
-   USE domwri           ! ocean space and time domain
-   USE in_out_manager   ! I/O manager
-   USE lbclnk           ! ocean lateral boundary conditions (or mpp link)
-   USE lib_mpp          ! MPP library
-   USE wrk_nemo         ! work arrays
-
-   IMPLICIT NONE
-   PRIVATE
-
-   PUBLIC cpl_prism_init
-   PUBLIC cpl_prism_define
-   PUBLIC cpl_prism_snd
-   PUBLIC cpl_prism_rcv
-   PUBLIC cpl_prism_update_time
-   PUBLIC cpl_prism_finalize
-   
-!   LOGICAL, PUBLIC, PARAMETER :: lk_cpl = .TRUE.    ! coupled flag
-   INTEGER                    :: ncomp_id           ! id returned by prism_init_comp
-   INTEGER                    :: nerror             ! return error code
-   INTEGER, PUBLIC            :: OASIS_Rcv  = 1     ! return code if received field
-   INTEGER, PUBLIC            :: OASIS_idle = 0     ! return code if nothing done by oasis
-
-   INTEGER, PARAMETER :: nmaxfld=40    ! Maximum number of coupling fields
-   
-   TYPE, PUBLIC ::   FLD_CPL            ! Type for coupling field information
-      LOGICAL            ::   laction   ! To be coupled or not
-      CHARACTER(len = 8) ::   clname    ! Name of the coupling field   
-      CHARACTER(len = 1) ::   clgrid    ! Grid type  
-      REAL(wp)           ::   nsgn      ! Control of the sign change
-      INTEGER            ::   nid       ! Id of the field
-   END TYPE FLD_CPL
-
-   TYPE(FLD_CPL), DIMENSION(nmaxfld), PUBLIC :: srcv, ssnd   ! Coupling fields
-
-   REAL(wp), DIMENSION(:,:,:), ALLOCATABLE :: exfld  ! Temporary buffer for receiving
-
-   TYPE(PRISM_Time_struct), PUBLIC    :: date            ! date info for send operation
-   TYPE(PRISM_Time_struct), PUBLIC    :: date_bound(2)   ! date info for send operation
-
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$
-   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-CONTAINS
-
-   SUBROUTINE cpl_prism_init( kl_comm ) 
-      !!-------------------------------------------------------------------
-      !!             ***  ROUTINE cpl_prism_init  ***
-      !!
-      !! ** Purpose :   Initialize coupled mode communication for ocean
-      !!    exchange between AGCM, OGCM and COUPLER. (OASIS4 software)
-      !!
-      !! ** Method  :   OASIS4 MPI communication 
-      !!--------------------------------------------------------------------
-      INTEGER, INTENT(out) ::   kl_comm   ! local communicator of the model
-      !!--------------------------------------------------------------------
-      
-      CALL prism_init( 'nemo', nerror )
-
-      !------------------------------------------------------------------
-      ! 2nd Initialize the PRISM system for the component
-      !------------------------------------------------------------------
-      CALL prism_init_comp( ncomp_id, 'oceanx', nerror )
-      IF( nerror /= PRISM_Success )   CALL prism_abort( ncomp_id, 'cpl_prism_init', 'Failure in prism_init_comp' )
-
-      !------------------------------------------------------------------
-      ! 3rd Get an MPI communicator fr OPA local communication
-      !------------------------------------------------------------------
-      CALL prism_get_localcomm( ncomp_id, kl_comm, nerror )
-      IF( nerror /= PRISM_Success )   CALL prism_abort( ncomp_id, 'cpl_prism_init', 'Failure in prism_get_localcomm' )
-      !
-   END SUBROUTINE cpl_prism_init
-
-
-   SUBROUTINE cpl_prism_define( krcv, ksnd )
-      !!-------------------------------------------------------------------
-      !!             ***  ROUTINE cpl_prism_define  ***
-      !!
-      !! ** Purpose :   Define grid and field information for ocean
-      !!    exchange between AGCM, OGCM and COUPLER. (OASIS4 software)
-      !!
-      !! ** Method  :   OASIS4 MPI communication 
-      !!--------------------------------------------------------------------
-      INTEGER, INTENT(in) :: krcv, ksnd     ! Number of received and sent coupling fields
-      !
-      INTEGER, DIMENSION(4)      :: igrid     ! ids returned by prism_def_grid
-      INTEGER, DIMENSION(4)      :: iptid     ! ids returned by prism_set_points
-      INTEGER, DIMENSION(4)      :: imskid    ! ids returned by prism_set_mask
-      INTEGER, DIMENSION(4)      :: iishift   ! 
-      INTEGER, DIMENSION(4)      :: ijshift   ! 
-      INTEGER, DIMENSION(4)      :: iioff     ! 
-      INTEGER, DIMENSION(4)      :: ijoff     ! 
-      INTEGER, DIMENSION(4)      :: itmp      ! 
-      INTEGER, DIMENSION(1,3)    :: iextent   ! 
-      INTEGER, DIMENSION(1,3)    :: ioffset   ! 
-
-      INTEGER                    :: ishape(2,3)    ! shape of arrays passed to PSMILe
-      INTEGER                    :: data_type      ! data type of transients
-
-      LOGICAL                    :: new_points
-      LOGICAL                    :: new_mask
-      LOGICAL, ALLOCATABLE, SAVE :: llmask(:,:,:) ! jpi,jpj,1
-
-      INTEGER                    :: ji, jj, jg, jc   ! local loop indicees
-      INTEGER                    :: ii, ij           ! index
-      INTEGER, DIMENSION(1)      :: ind              ! index
-
-      CHARACTER(len=32)          :: clpt_name     ! name of the grid points
-      CHARACTER(len=7)           :: cltxt 
-      CHARACTER(len=1), DIMENSION(4) :: clgrd = (/ 'T','U','V','F' /)     ! name of the grid points
-
-      TYPE(PRISM_Time_struct)    :: tmpdate
-      INTEGER                    :: idate_incr      ! date increment
-      REAL(wp), POINTER, DIMENSION(:,:)   ::   zlon, zlat
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zclo, zcla
-      !!--------------------------------------------------------------------
-      
-      CALL wrk_alloc( jpi,jpj, zlon, zlat )
-      CALL wrk_alloc( jpi,jpj,jpk, zclo, zcla )
-
-      IF(lwp) WRITE(numout,*)
-      IF(lwp) WRITE(numout,*) 'cpl_prism_define : initialization in coupled ocean/atmosphere case'
-      IF(lwp) WRITE(numout,*) '~~~~~~~~~~~~~~~~~'
-      IF(lwp) WRITE(numout,*)
-
-      !
-      ! ... Allocate memory for data exchange
-      !
-      ALLOCATE( exfld(nlei-nldi+1, nlej-nldj+1, 1), stat = nerror )
-      IF ( nerror > 0 ) THEN
-         CALL prism_abort( ncomp_id, 'cpl_prism_define', 'Failure in allocating exfld' )
-         RETURN
-      ENDIF
-
-      IF(.not. ALLOCATED(mask))THEN
-         ALLOCATE(llmask(jpi,jpj,1), Stat=ji)
-         IF(ji /= 0)THEN
-            CALL prism_abort( ncomp_id, 'cpl_prism_define', 'Failure in allocating llmask' )
-            RETURN
-         END IF
-      END IF
-
-      ! -----------------------------------------------------------------
-      ! ... Define the shape of the valid region without the halo and overlaps between cpus
-      !     For serial configuration (key_mpp_mpi not being active)
-      !     nl* is set to the global values 1 and jp*glo.
-      ! -----------------------------------------------------------------
-
-      ishape(:,1) = (/ 1, nlei-nldi+1 /)
-      ishape(:,2) = (/ 1, nlej-nldj+1 /)
-      ishape(:,3) = (/ 1,           1 /)
-          
-      DO ji = 1, 4
-         CALL prism_def_grid( igrid(ji), 'orca'//clgrd(ji), ncomp_id, ishape, PRISM_irrlonlat_regvrt, nerror )
-         IF( nerror /= PRISM_Success )   CALL prism_abort (ncomp_id, 'cpl_prism_define',   &
-            &                                                        'Failure in prism_def_grid of '//clgrd(jg)//'-point' )
-      END DO
-      
-      ! -----------------------------------------------------------------
-      ! ... Define the partition 
-      ! -----------------------------------------------------------------
-      
-      iextent(1,:) = (/    nlei-nldi+1,    nlej-nldj+1, 1 /)
-      ioffset(1,:) = (/ nldi-1+nimpp-1, nldj-1+njmpp-1, 0 /)
-      
-      DO ji = 1, 4
-         CALL prism_def_partition( igrid(ji), 1, ioffset, iextent, nerror )
-         IF( nerror /= PRISM_Success )   CALL prism_abort (ncomp_id, 'cpl_prism_define',   &
-            &                                                        'Failure in prism_def_partition of '//clgrd(jg)//'-point' )
-      END DO
-
-      ! -----------------------------------------------------------------
-      ! ... Define the elements, i.e. specify the corner points for each
-      !     volume element. In case OPA runs on level coordinates (regular
-      !     in the vertical) we only need to give the 4 horizontal corners
-      !     for a volume element plus the vertical position of the upper
-      !     and lower face. Nevertheless the volume element has 8 corners.
-      ! -----------------------------------------------------------------
-      
-      iioff(:) = (/0,1,0,1/)
-      ijoff(:) = (/0,0,1,1/) 
-      iishift(:) = (/0,1,1,0/)
-      ijshift(:) = (/0,0,1,1/)
-
-      DO jg = 1, 4    ! ... the t,u,v,f-points
-
-         cltxt = clgrd(jg)//'-point'
-         
-         ! -----------------------------------------------------------------
-         ! ... Convert OPA masks to logicals and define the masks
-         ! -----------------------------------------------------------------
-         SELECT CASE( jg ) 
-         CASE(1)   ;   llmask(:,:,1) = ( tmask(:,:,1)  ) == 1.
-         CASE(2)   ;   llmask(:,:,1) = ( umask(:,:,1)  ) == 1.
-         CASE(3)   ;   llmask(:,:,1) = ( vmask(:,:,1)  ) == 1.
-         CASE(4)   ;   llmask(:,:,1) = ( fmask(:,:,1)  ) == 1.
-!         CASE(1)   ;   llmask(:,:,1) = ( tmask(:,:,1) * dom_uniq('T') ) == 1.
-!         CASE(2)   ;   llmask(:,:,1) = ( umask(:,:,1) * dom_uniq('U') ) == 1.
-!         CASE(3)   ;   llmask(:,:,1) = ( vmask(:,:,1) * dom_uniq('V') ) == 1.
-!         CASE(4)   ;   llmask(:,:,1) = ( fmask(:,:,1) * dom_uniq('F') ) == 1.
-         END SELECT
-         CALL prism_set_mask( imskid(jg), igrid(jg), ishape, llmask(nldi:nlei, nldj:nlej, 1), .TRUE., nerror )
-         IF( nerror /= PRISM_Success )   CALL prism_abort( ncomp_id, 'cpl_prism_define', 'Failure in prism_set_mask for '//cltxt )
-
-         ! -----------------------------------------------------------------
-         ! ... Define the corners
-         ! -----------------------------------------------------------------
-         SELECT CASE( jg ) 
-         CASE(1)   ;   zlon(:,:) = glamf(:,:)   ;   zlat(:,:) = gphif(:,:)
-         CASE(2)   ;   zlon(:,:) = glamv(:,:)   ;   zlat(:,:) = gphiv(:,:)
-         CASE(3)   ;   zlon(:,:) = glamu(:,:)   ;   zlat(:,:) = gphiu(:,:) 
-         CASE(4)   ;   zlon(:,:) = glamt(:,:)   ;   zlat(:,:) = gphit(:,:)
-         END SELECT
-
-         DO jc = 1, 4   ! corner number (anti-clockwise, starting from the bottom left corner)
-            DO jj = 2, jpjm1
-               DO ji = 2, jpim1   ! NO vector opt.
-                  ii = ji-1 + iioff(jg) + iishift(jc)
-                  ij = jj-1 + ijoff(jg) + ijshift(jc)
-                  zclo(ji,jj,jc) = zlon(ii,ij)
-                  zcla(ji,jj,jc) = zlat(ii,ij)
-               END DO
-            END DO
-            CALL lbc_lnk( zclo(:,:,jc), clgrd(jg), 1. )   ;   CALL lbc_lnk( zcla(:,:,jc), clgrd(jg), 1. )
-         END DO
-
-         CALL prism_set_corners( igrid(jg), 8, ishape, zclo(nldi:nlei, nldj:nlej,:),   &
-            &                                          zcla(nldi:nlei, nldj:nlej,:), RESHAPE( (/-1.,1./), (/1,2/) ), nerror )
-         IF( nerror /= PRISM_Success )   CALL prism_abort( ncomp_id, 'cpl_prism_define', 'Failure in prism_set_corners of '//cltxt )    
-
-         ! -----------------------------------------------------------------
-         ! ... Define the center points
-         ! -----------------------------------------------------------------
-         SELECT CASE( jg ) 
-         CASE(1)   ;   zlon(:,:) = glamt(:,:)   ;   zlat(:,:) = gphit(:,:)
-         CASE(2)   ;   zlon(:,:) = glamu(:,:)   ;   zlat(:,:) = gphiu(:,:)
-         CASE(3)   ;   zlon(:,:) = glamv(:,:)   ;   zlat(:,:) = gphiv(:,:)
-         CASE(4)   ;   zlon(:,:) = glamf(:,:)   ;   zlat(:,:) = gphif(:,:)
-         END SELECT
-
-         CALL prism_set_points ( iptid(jg), cltxt, igrid(jg), ishape, zlon(nldi:nlei, nldj:nlej),   &
-         &                                                            zlat(nldi:nlei, nldj:nlej), (/0./), .TRUE., nerror )
-         IF( nerror /= PRISM_Success )   CALL prism_abort ( ncomp_id, 'cpl_prism_define', 'Failure in prism_set_points '//cltxt )
-
-      END DO
-
-      ! ... Announce send variables. 
-      !
-      DO ji = 1, ksnd
-         IF ( ssnd(ji)%laction ) THEN 
-            
-            itmp(:) = 0
-            WHERE( clgrd == ssnd(ji)%clgrid  ) itmp = 1
-            ind(:) = maxloc( itmp )
-            WRITE(6,*) ' grid for field ', ind(1), ssnd(ji)%clname
-             ind(1) = 1
-
-            CALL prism_def_var( ssnd(ji)%nid, ssnd(ji)%clname, igrid(ind(1)), iptid(ind(1)),  imskid(ind(1)), (/ 3, 0/),   &
-               &                ishape, PRISM_Double_Precision, nerror )
-            IF ( nerror /= PRISM_Success )   CALL prism_abort( ssnd(ji)%nid, 'cpl_prism_define',   &
-               &                                               'Failure in prism_def_var for '//TRIM(ssnd(ji)%clname))
-
-         ENDIF
-      END DO
-      !
-      ! ... Announce received variables. 
-      !
-      DO ji = 1, krcv
-         IF ( srcv(ji)%laction ) THEN 
-
-            itmp(:) = 0
-            WHERE( clgrd == srcv(ji)%clgrid  ) itmp = 1
-            ind(:) = maxloc( itmp )
-            WRITE(6,*) ' grid for field ', ind(1), srcv(ji)%clname
-             ind(1) = 1
- 
-            CALL prism_def_var( srcv(ji)%nid, srcv(ji)%clname, igrid(ind(1)), iptid(ind(1)), imskid(ind(1)), (/ 3, 0/),   &
-               &                ishape, PRISM_Double_Precision, nerror )
-            IF ( nerror /= PRISM_Success )   CALL prism_abort( srcv(ji)%nid, 'cpl_prism_define',   &
-               &                                               'Failure in prism_def_var for '//TRIM(srcv(ji)%clname))
-
-         ENDIF
-      END DO
-      
-      !------------------------------------------------------------------
-      ! End of definition phase
-      !------------------------------------------------------------------
-      
-      CALL prism_enddef( nerror )
-      IF ( nerror /= PRISM_Success )   CALL prism_abort ( ncomp_id, 'cpl_prism_define', 'Failure in prism_enddef')
-      
-      CALL wrk_dealloc( jpi,jpj, zlon, zlat )
-      CALL wrk_dealloc( jpi,jpj,jpk, zclo, zcla )
-      !
-   END SUBROUTINE cpl_prism_define
-   
-   
-   SUBROUTINE cpl_prism_snd( kid, kstep, pdata, kinfo )
-      !!---------------------------------------------------------------------
-      !!              ***  ROUTINE cpl_prism_snd  ***
-      !!
-      !! ** Purpose : - At each coupling time-step,this routine sends fields
-      !!      like sst or ice cover to the coupler or remote application.
-      !!----------------------------------------------------------------------
-      INTEGER                 , INTENT(in   ) ::   kid     ! variable intex in the array
-      INTEGER                 , INTENT(  out) ::   kinfo   ! OASIS4 info argument
-      INTEGER                 , INTENT(in   ) ::   kstep   ! ocean time-step in seconds
-      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   pdata
-      !!--------------------------------------------------------------------
-      !
-      ! snd data to OASIS4
-      !
-      exfld(:,:,1) = pdata(nldi:nlei, nldj:nlej)
-      CALL prism_put( ssnd(kid)%nid, date, date_bound, exfld, kinfo, nerror )
-      IF ( nerror /= PRISM_Success )   CALL prism_abort( ssnd(kid)%nid, 'cpl_prism_snd',   &
-         &                                               'Failure in prism_put for '//TRIM(ssnd(kid)%clname) )
-
-      IF( ln_ctl ) THEN        
-         IF ( kinfo >= PRISM_Cpl     .OR. kinfo == PRISM_Rst .OR.   &
-            & kinfo == PRISM_RstTimeop ) THEN
-            WRITE(numout,*) '****************'
-            WRITE(numout,*) 'prism_put: Outgoing ', ssnd(kid)%clname
-            WRITE(numout,*) 'prism_put: ivarid ', ssnd(kid)%nid
-            WRITE(numout,*) 'prism_put:  kstep ', kstep
-            WRITE(numout,*) 'prism_put:   info ', kinfo
-            WRITE(numout,*) '     - Minimum value is ', MINVAL(pdata)
-            WRITE(numout,*) '     - Maximum value is ', MAXVAL(pdata)
-            WRITE(numout,*) '     -     Sum value is ', SUM(pdata)
-            WRITE(numout,*) '****************'
-         ENDIF
-      ENDIF
-      !
-   END SUBROUTINE cpl_prism_snd
-
-
-   SUBROUTINE cpl_prism_rcv( kid, kstep, pdata, kinfo )
-      !!---------------------------------------------------------------------
-      !!              ***  ROUTINE cpl_prism_rcv  ***
-      !!
-      !! ** Purpose : - At each coupling time-step,this routine receives fields
-      !!      like stresses and fluxes from the coupler or remote application.
-      !!----------------------------------------------------------------------
-      INTEGER                 , INTENT(in   ) ::   kid     ! variable intex in the array
-      INTEGER                 , INTENT(in   ) ::   kstep   ! ocean time-step in seconds
-      REAL(wp), DIMENSION(:,:), INTENT(inout) ::   pdata   ! IN to keep the value if nothing is done
-      INTEGER                 , INTENT(  out) ::   kinfo   ! OASIS4 info argument
-      !
-      LOGICAL                :: llaction
-      !!--------------------------------------------------------------------
-      !
-      ! receive local data from OASIS4 on every process
-      !
-      CALL prism_get( srcv(kid)%nid, date, date_bound, exfld, kinfo, nerror )         
-      IF ( nerror /= PRISM_Success )   CALL prism_abort( srcv(kid)%nid, 'cpl_prism_rcv',   &
-         &                                               'Failure in prism_get for '//TRIM(srcv(kid)%clname) )
-
-      WRITE(numout,*) 'prism_get: Incoming ', srcv(kid)%clname
-      call flush(numout)
-      llaction = .false.
-      IF( kinfo == PRISM_Cpl )  llaction = .TRUE.
-
-      IF ( ln_ctl )   WRITE(numout,*) "llaction, kinfo, kstep, ivarid: " , llaction, kinfo, kstep, srcv(kid)%nid
-
-      IF ( llaction ) THEN
-
-         kinfo = OASIS_Rcv
-         pdata(nldi:nlei, nldj:nlej) = exfld(:,:,1)
-         
-         !--- Fill the overlap areas and extra hallows (mpp)
-         !--- check periodicity conditions (all cases)
-         CALL lbc_lnk( pdata, srcv(kid)%clgrid, srcv(kid)%nsgn )   
-         
-         IF ( ln_ctl ) THEN        
-            WRITE(numout,*) '****************'
-            WRITE(numout,*) 'prism_get: Incoming ', srcv(kid)%clname
-            WRITE(numout,*) 'prism_get: ivarid '  , srcv(kid)%nid
-            WRITE(numout,*) 'prism_get:   kstep', kstep
-            WRITE(numout,*) 'prism_get:   info ', kinfo
-            WRITE(numout,*) '     - Minimum value is ', MINVAL(pdata)
-            WRITE(numout,*) '     - Maximum value is ', MAXVAL(pdata)
-            WRITE(numout,*) '     -     Sum value is ', SUM(pdata)
-            WRITE(numout,*) '****************'
-         ENDIF
-
-      ELSE
-         kinfo = OASIS_idle     
-      ENDIF
-      !
-   END SUBROUTINE cpl_prism_rcv
-
-
-   SUBROUTINE cpl_prism_finalize
-      !!---------------------------------------------------------------------
-      !!              ***  ROUTINE cpl_prism_finalize  ***
-      !!
-      !! ** Purpose : - Finalizes the coupling. If MPI_init has not been
-      !!      called explicitly before cpl_prism_init it will also close
-      !!      MPI communication.
-      !!----------------------------------------------------------------------
-      !
-      DEALLOCATE(exfld)
-      CALL prism_terminate ( nerror )         
-      !
-   END SUBROUTINE cpl_prism_finalize
-
-
-   SUBROUTINE cpl_prism_update_time(kt)
-      !!---------------------------------------------------------------------
-      !!              ***  ROUTINE cpl_prism_update_time  ***
-      !!
-      !! ** Purpose : - Increment date with model timestep
-      !!                called explicitly at the end of each timestep
-      !!----------------------------------------------------------------------
-      INTEGER, INTENT(in) ::   kt   ! ocean model time step index
-
-      TYPE(PRISM_Time_struct) ::   tmpdate
-      INTEGER                 ::   idate_incr   ! date increment
-      !!----------------------------------------------------------------------
-
-      IF( kt == nit000 ) THEN      ! Define the actual date 
-         !
-         ! date is determined by adding days since beginning of the run to the corresponding initial date.
-         ! Note that OPA internal info about the start date of the experiment is bypassed.
-         ! Instead we rely sololy on the info provided by the SCC.xml file.
-         !
-         date = PRISM_Jobstart_date
-         !
-         !
-         ! lower/upper bound is determined by adding half a time step
-         !
-         idate_incr = 0.5 * NINT ( rdttra(1) )
-         tmpdate = date   ;   CALL PRISM_calc_newdate ( tmpdate, -idate_incr, nerror )   ;   date_bound(1) = tmpdate
-         tmpdate = date   ;   CALL PRISM_calc_newdate ( tmpdate,  idate_incr, nerror )   ;   date_bound(2) = tmpdate
-         !
-      ELSE      ! Date update
-         !
-         idate_incr  = rdttra(1)
-         CALL PRISM_calc_newdate( date, idate_incr, nerror )
-         date_bound(1) = date_bound(2)
-         tmpdate = date_bound(2)
-         CALL PRISM_calc_newdate( tmpdate, idate_incr, nerror )
-         date_bound(2) = tmpdate
-         !
-      END IF
-      !
-   END SUBROUTINE cpl_prism_update_time
-
-#endif
-
-   !!=====================================================================
-END MODULE cpl_oasis4
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/fldread.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/fldread.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/fldread.F90	(revision 5075)
@@ -40,5 +40,5 @@
       LOGICAL              ::   ln_clim     ! climatology or not (T/F)
       CHARACTER(len = 8)   ::   cltype      ! type of data file 'daily', 'monthly' or yearly'
-      CHARACTER(len = 34)  ::   wname       ! generic name of a NetCDF weights file to be used, blank if not
+      CHARACTER(len = 256) ::   wname       ! generic name of a NetCDF weights file to be used, blank if not
       CHARACTER(len = 34)  ::   vcomp       ! symbolic component name if a vector that needs rotation
       !                                     ! a string starting with "U" or "V" for each component   
@@ -473,9 +473,12 @@
             !       forcing record :    1 
             !                            
-            ztmp = REAL( nday, wp ) / REAL( nyear_len(1), wp ) + 0.5 + REAL( it_offset, wp )
+            ztmp = REAL( nsec_year, wp ) / ( REAL( nyear_len(1), wp ) * rday ) + 0.5 &
+           &       + REAL( it_offset, wp ) / ( REAL( nyear_len(1), wp ) * rday )
             sdjf%nrec_a(1) = 1 + INT( ztmp ) - COUNT((/llbefore/))
             ! swap at the middle of the year
-            IF( llbefore ) THEN   ;   sdjf%nrec_a(2) = nsec1jan000 - NINT(0.5 * rday) * nyear_len(0)
-            ELSE                  ;   sdjf%nrec_a(2) = nsec1jan000 + NINT(0.5 * rday) * nyear_len(1)   
+            IF( llbefore ) THEN   ;   sdjf%nrec_a(2) = nsec1jan000 - (1 - INT(ztmp)) * NINT(0.5 * rday) * nyear_len(0) + &
+                                    & INT(ztmp) * NINT( 0.5 * rday) * nyear_len(1) 
+            ELSE                  ;   sdjf%nrec_a(2) = nsec1jan000 + (1 - INT(ztmp)) * NINT(0.5 * rday) * nyear_len(1) + &
+                                    & INT(ztmp) * INT(rday) * nyear_len(1) + INT(ztmp) * NINT( 0.5 * rday) * nyear_len(2) 
             ENDIF
          ELSE                                    ! no time interpolation
@@ -501,5 +504,6 @@
             !       forcing record :  nmonth 
             !                            
-            ztmp = REAL( nday, wp ) / REAL( nmonth_len(nmonth), wp ) + 0.5 + REAL( it_offset, wp )
+            ztmp = REAL( nsec_month, wp ) / ( REAL( nmonth_len(nmonth), wp ) * rday ) + 0.5 &
+           &       + REAL( it_offset, wp ) / ( REAL( nmonth_len(nmonth), wp ) * rday )
             imth = nmonth + INT( ztmp ) - COUNT((/llbefore/))
             IF( sdjf%cltype == 'monthly' ) THEN   ;   sdjf%nrec_a(1) = 1 + INT( ztmp ) - COUNT((/llbefore/))
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/oasis4_date.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/oasis4_date.F90	(revision 5074)
+++ 	(revision )
@@ -1,41 +1,0 @@
-MODULE oasis4_date
-   !!======================================================================
-   !!                     ***  MODULE oasis_date  ***  
-   !!   Date and related information required to couple NEMO via OASIS4
-   !!   Made separate from cpl_oasis4 module to allow wider use.
-   !!======================================================================
-   !! History :  2.0  ! 2005-12  (R. Hill, Met. Office) Original code
-   !!----------------------------------------------------------------------
-#if defined key_oasis4
-   !!----------------------------------------------------------------------
-   !!   'key_oasis4'                                   coupled with OASIS-4
-   !!----------------------------------------------------------------------
-   !##################### WARNING coupled mode ###############################
-   !##################### WARNING coupled mode ###############################
-   !   Following line must be enabled if coupling with OASIS
-   !   USE PRISM
-   !##################### WARNING coupled mode ###############################
-   !##################### WARNING coupled mode ###############################
-
-   PRIVATE
-   IMPLICIT NONE
-
-   INTEGER, PUBLIC :: date_err, date_info   !: 
-
-   TYPE(PRISM_Time_struct), PUBLIC ::   dates            !: date info for send operation
-   TYPE(PRISM_Time_struct), PUBLIC ::   dates_bound(2)   !: date info for send operation
-   TYPE(PRISM_Time_struct), PUBLIC ::   dater            !: date info for receive operation
-   TYPE(PRISM_Time_struct), PUBLIC ::   dater_bound(2)   !: date info for receive operation
-   TYPE(PRISM_Time_struct), PUBLIC ::   tmpdate          !:
-   
-#else
-   !!----------------------------------------------------------------------
-   !!   Default option            Dummy module                   NO OASIS-4
-   !!----------------------------------------------------------------------
-#endif
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$
-   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
-   !!======================================================================
-END MODULE oasis4_date
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_ice.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_ice.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_ice.F90	(revision 5075)
@@ -14,4 +14,5 @@
    !!----------------------------------------------------------------------
    USE par_oce          ! ocean parameters
+   USE sbc_oce          ! surface boundary condition: ocean
 # if defined key_lim3
    USE par_ice          ! LIM-3 parameters
@@ -21,5 +22,5 @@
    USE ice_2
 # endif
-# if defined key_cice 
+# if defined key_cice
    USE ice_domain_size, only: ncat 
 #endif
@@ -55,36 +56,30 @@
 # endif
 
-#if defined key_lim3 || defined key_lim2 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qns_ice       !: non solar heat flux over ice                  [W/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qsr_ice       !: solar heat flux over ice                      [W/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qsr_ice_mean  !: dauly mean solar heat flux over ice       [W/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qla_ice       !: latent flux over ice                          [W/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dqla_ice      !: latent sensibility over ice                 [W/m2/K]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dqns_ice      !: non solar heat flux over ice (LW+SEN+LA)    [W/m2/K]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tn_ice        !: ice surface temperature                          [K]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   alb_ice       !: albedo of ice
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qns_ice        !: non solar heat flux over ice                  [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qsr_ice        !: solar heat flux over ice                      [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qsr_ice_mean   !: daily mean solar heat flux over ice           [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qla_ice        !: latent flux over ice                          [W/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dqla_ice       !: latent sensibility over ice                 [W/m2/K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   dqns_ice       !: non solar heat flux over ice (LW+SEN+LA)    [W/m2/K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tn_ice         !: ice surface temperature                          [K]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   alb_ice        !: ice albedo                                       [-]
 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   utau_ice  !: atmos-ice u-stress. VP: I-pt ; EVP: U,V-pts   [N/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   vtau_ice  !: atmos-ice v-stress. VP: I-pt ; EVP: U,V-pts   [N/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fr1_i0    !: 1st Qsr fraction penetrating inside ice cover    [-]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fr2_i0    !: 2nd Qsr fraction penetrating inside ice cover    [-]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   emp_ice   !: sublimation-snow budget over ice             [kg/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   utau_ice       !: atmos-ice u-stress. VP: I-pt ; EVP: U,V-pts   [N/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   vtau_ice       !: atmos-ice v-stress. VP: I-pt ; EVP: U,V-pts   [N/m2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fr1_i0         !: Solar surface transmission parameter, thick ice  [-]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fr2_i0         !: Solar surface transmission parameter, thin ice   [-]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   emp_ice        !: sublimation - precip over sea ice            [kg/m2]
 
-# if defined key_lim3
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   tatm_ice  !: air temperature
-# endif
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   topmelt            !: category topmelt
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   botmelt            !: category botmelt
 
-#elif defined key_cice
+#if defined key_cice
    !
    ! for consistency with LIM, these are declared with three dimensions
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qlw_ice            !: incoming long-wave
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qla_ice            !: latent flux over ice           [W/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qsr_ice            !: solar heat flux over ice       [W/m2]
    !
    ! other forcing arrays are two dimensional
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ss_iou             !: x ice-ocean surface stress at NEMO U point
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ss_iov             !: y ice-ocean surface stress at NEMO V point
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   emp_ice            !: sublimation-snow budget over ice    [kg/m2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   tatm_ice           !: air temperature
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qatm_ice           !: specific humidity
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   wndi_ice           !: i wind at T point
@@ -93,10 +88,22 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fr_iu              !: ice fraction at NEMO U point
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fr_iv              !: ice fraction at NEMO V point
-   !
-   ! finally, arrays corresponding to different ice categories
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   a_i                !: category ice fraction
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   topmelt            !: category topmelt
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   botmelt            !: category botmelt
+   
+   ! variables used in the coupled interface
+   INTEGER , PUBLIC, PARAMETER ::   jpl = ncat
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   u_ice, v_ice          ! jpi, jpj
 #endif
+   
+#if defined key_lim2 || defined key_cice
+   ! already defined in ice.F90 for LIM3
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  a_i
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  ht_i, ht_s
+#endif
+
+#if defined key_lim3 || defined key_cice
+   ! not used with LIM2
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   tatm_ice       !: air temperature [K]
+#endif
+
+   REAL(wp), PUBLIC, SAVE ::   cldf_ice = 0.81    !: cloud fraction over sea ice, summer CLIO value   [-]
 
    !!----------------------------------------------------------------------
@@ -111,5 +118,5 @@
       !!                     ***  FUNCTION sbc_ice_alloc  ***
       !!----------------------------------------------------------------------
-      INTEGER :: ierr(2)
+      INTEGER :: ierr(5)
       !!----------------------------------------------------------------------
       ierr(:) = 0
@@ -123,22 +130,34 @@
          &      fr1_i0  (jpi,jpj)     , fr2_i0  (jpi,jpj)     ,     &
 #if defined key_lim3
-         &      emp_ice(jpi,jpj)      , tatm_ice(jpi,jpj)     , STAT= ierr(1) )
-#else
-         &      emp_ice(jpi,jpj)                              , STAT= ierr(1) )
+         &      tatm_ice(jpi,jpj)     ,                             &
 #endif
-#elif defined key_cice
+#if defined key_lim2
+         &      a_i(jpi,jpj,jpl)      ,                             &
+#endif
+         &      emp_ice(jpi,jpj)      ,  STAT= ierr(1) )
+#endif
+
+#if defined key_cice
       ALLOCATE( qla_ice(jpi,jpj,1)    , qlw_ice(jpi,jpj,1)    , qsr_ice(jpi,jpj,1)    , &
                 wndi_ice(jpi,jpj)     , tatm_ice(jpi,jpj)     , qatm_ice(jpi,jpj)     , &
                 wndj_ice(jpi,jpj)     , nfrzmlt(jpi,jpj)      , ss_iou(jpi,jpj)       , &
                 ss_iov(jpi,jpj)       , fr_iu(jpi,jpj)        , fr_iv(jpi,jpj)        , &
-                a_i(jpi,jpj,ncat)     , topmelt(jpi,jpj,ncat) , botmelt(jpi,jpj,ncat), STAT= ierr(1) )
+                a_i(jpi,jpj,ncat)     , topmelt(jpi,jpj,ncat) , botmelt(jpi,jpj,ncat) , &
+                STAT= ierr(1) )
+      IF( lk_cpl )   ALLOCATE( u_ice(jpi,jpj)        , fr1_i0(jpi,jpj)       , tn_ice (jpi,jpj,1)    , &
+         &                     v_ice(jpi,jpj)        , fr2_i0(jpi,jpj)       , alb_ice(jpi,jpj,1)    , &
+         &                     emp_ice(jpi,jpj)      , qns_ice(jpi,jpj,1)    , dqns_ice(jpi,jpj,1)   , &
+         &                     STAT= ierr(2) )
+      
 #endif
          !
 #if defined key_lim2
-      IF( ltrcdm2dc_ice )THEN
-         ALLOCATE( qsr_ice_mean (jpi,jpj,jpl), STAT=ierr(2) )
-      ENDIF
+      IF( ltrcdm2dc_ice )   ALLOCATE( qsr_ice_mean (jpi,jpj,jpl), STAT=ierr(3) )
 #endif
          !
+#if defined key_cice || defined key_lim2
+      IF( lk_cpl )   ALLOCATE( ht_i(jpi,jpj,jpl) , ht_s(jpi,jpj,jpl) , STAT=ierr(5) )
+#endif
+
       sbc_ice_alloc = MAXVAL( ierr )
       IF( lk_mpp            )   CALL mpp_sum ( sbc_ice_alloc )
@@ -150,8 +169,18 @@
    !!   Default option                      NO LIM 2.0 or 3.0 or CICE sea-ice model
    !!----------------------------------------------------------------------
+   USE in_out_manager   ! I/O manager
    LOGICAL         , PUBLIC, PARAMETER ::   lk_lim2    = .FALSE.  !: no LIM-2 ice model
    LOGICAL         , PUBLIC, PARAMETER ::   lk_lim3    = .FALSE.  !: no LIM-3 ice model
    LOGICAL         , PUBLIC, PARAMETER ::   lk_cice    = .FALSE.  !: no CICE  ice model
    CHARACTER(len=1), PUBLIC, PARAMETER ::   cp_ice_msh = '-'      !: no grid ice-velocity
+   REAL            , PUBLIC, PARAMETER ::   cldf_ice = 0.81       !: cloud fraction over sea ice, summer CLIO value   [-]
+   INTEGER         , PUBLIC, PARAMETER ::   jpl = 1 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   u_ice, v_ice,fr1_i0,fr2_i0          ! jpi, jpj
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tn_ice, alb_ice, qns_ice, dqns_ice  ! (jpi,jpj,jpl)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   a_i
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   emp_ice
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qsr_ice
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   ht_i, ht_s
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   topmelt, botmelt
 #endif
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbc_oce.F90	(revision 5075)
@@ -35,5 +35,9 @@
    LOGICAL , PUBLIC ::   ln_blk_core    !: CORE bulk formulation
    LOGICAL , PUBLIC ::   ln_blk_mfs     !: MFS  bulk formulation
-   LOGICAL , PUBLIC ::   ln_cpl         !: coupled   formulation (overwritten by key_sbc_coupled )
+#if defined key_oasis3
+   LOGICAL , PUBLIC ::   lk_cpl = .TRUE.  !: coupled formulation
+#else
+   LOGICAL , PUBLIC ::   lk_cpl = .FALSE. !: coupled formulation
+#endif
    LOGICAL , PUBLIC ::   ln_dm2dc       !: Daily mean to Diurnal Cycle short wave (qsr)
    LOGICAL , PUBLIC ::   ln_rnf         !: runoffs / runoff mouths
@@ -41,8 +45,14 @@
    LOGICAL , PUBLIC ::   ln_apr_dyn     !: Atmospheric pressure forcing used on dynamics (ocean & ice)
    INTEGER , PUBLIC ::   nn_ice         !: flag for ice in the surface boundary condition (=0/1/2/3)
+   INTEGER , PUBLIC ::   nn_isf         !: flag for isf in the surface boundary condition (=0/1/2/3/4) 
    INTEGER , PUBLIC ::   nn_ice_embd    !: flag for levitating/embedding sea-ice in the ocean
    !                                             !: =0 levitating ice (no mass exchange, concentration/dilution effect)
    !                                             !: =1 levitating ice with mass and salt exchange but no presure effect
    !                                             !: =2 embedded sea-ice (full salt and mass exchanges and pressure)
+   INTEGER , PUBLIC :: nn_limflx        !: LIM3 Multi-category heat flux formulation
+   !                                             !: =-1  Use of per-category fluxes
+   !                                             !: = 0  Average per-category fluxes
+   !                                             !: = 1  Average then redistribute per-category fluxes
+   !                                             !: = 2  Redistribute a single flux over categories
    INTEGER , PUBLIC ::   nn_fwb         !: FreshWater Budget: 
    !                                             !:  = 0 unchecked 
@@ -55,9 +65,17 @@
    LOGICAL , PUBLIC ::   ln_icebergs    !: Icebergs
    !
-   CHARACTER (len=8), PUBLIC :: cn_iceflx  !: Flux handling over ice categories
-   LOGICAL, PUBLIC :: ln_iceflx_ave     ! Average heat fluxes over all ice categories
-   LOGICAL, PUBLIC :: ln_iceflx_linear  ! Redistribute mean heat fluxes over all ice categories, using ice temperature and albedo
-   !
-   INTEGER , PUBLIC ::   nn_lsm        !: Number of iteration if seaoverland is applied
+   INTEGER , PUBLIC ::   nn_lsm         !: Number of iteration if seaoverland is applied
+   !!----------------------------------------------------------------------
+   !!           switch definition (improve readability)
+   !!----------------------------------------------------------------------
+   INTEGER , PUBLIC, PARAMETER ::   jp_gyre    = 0        !: GYRE analytical formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_ana     = 1        !: analytical      formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_flx     = 2        !: flux            formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_clio    = 3        !: CLIO bulk       formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_core    = 4        !: CORE bulk       formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_cpl     = 5        !: Coupled         formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_mfs     = 6        !: MFS  bulk       formulation
+   INTEGER , PUBLIC, PARAMETER ::   jp_esopa   = -1       !: esopa test, ALL formulations
+   
    !!----------------------------------------------------------------------
    !!              Ocean Surface Boundary Condition fields
@@ -102,5 +120,5 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   sss_m     !: mean (nn_fsbc time-step) surface sea salinity            [psu]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   ssh_m     !: mean (nn_fsbc time-step) sea surface height                [m]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   e3t_m     !: mean (nn_fsbc time-step) sea surface height                [m]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   e3t_m     !: mean (nn_fsbc time-step) sea surface layer thickness       [m]
 
    !! * Substitutions
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_clio.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_clio.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_clio.F90	(revision 5075)
@@ -114,5 +114,5 @@
       !!              - utau, vtau  i- and j-component of the wind stress
       !!              - taum        wind stress module at T-point
-      !!              - wndm        10m wind module at T-point
+      !!              - wndm        10m wind module at T-point over free ocean or leads in presence of sea-ice
       !!              - qns         non-solar heat flux including latent heat of solid 
       !!                            precip. melting and emp heat content
@@ -204,5 +204,5 @@
       !!               - utau, vtau  i- and j-component of the wind stress
       !!               - taum        wind stress module at T-point
-      !!               - wndm        10m wind module at T-point
+      !!               - wndm        10m wind module at T-point over free ocean or leads in presence of sea-ice
       !!               - qns         non-solar heat flux including latent heat of solid 
       !!                             precip. melting and emp heat content
@@ -257,4 +257,7 @@
          END DO
       END DO
+      utau(:,:) = utau(:,:) * umask(:,:,1)
+      vtau(:,:) = vtau(:,:) * vmask(:,:,1)
+      taum(:,:) = taum(:,:) * tmask(:,:,1)
       CALL lbc_lnk( taum, 'T', 1. )
 
@@ -264,4 +267,5 @@
 !CDIR COLLAPSE
       wndm(:,:) = sf(jp_wndm)%fnow(:,:,1)
+      wndm(:,:) = wndm(:,:) * tmask(:,:,1)
 
       !------------------------------------------------!
@@ -270,5 +274,5 @@
       
       CALL blk_clio_qsr_oce( qsr )
-
+      qsr(:,:) = qsr(:,:) * tmask(:,:,1) ! no shortwave radiation into the ocean beneath ice shelf
       !------------------------!
       !   Other ocean fluxes   !
@@ -376,4 +380,5 @@
          &     - zqla(:,:)             * pst(:,:) * zcevap                &   ! remove evap.   heat content at SST in Celcius
          &     + sf(jp_prec)%fnow(:,:,1) * sf(jp_tair)%fnow(:,:,1) * zcprec   ! add    precip. heat content at Tair in Celcius
+      qns(:,:) = qns(:,:) * tmask(:,:,1)
       ! NB: if sea-ice model, the snow precip are computed and the associated heat is added to qns (see blk_ice_clio)
 
@@ -398,5 +403,5 @@
 
 
-   SUBROUTINE blk_ice_clio(  pst   , palb_cs, palb_os ,       &
+   SUBROUTINE blk_ice_clio(  pst   , palb_cs, palb_os, palb,  &
       &                      p_taui, p_tauj, p_qns , p_qsr,   &
       &                      p_qla , p_dqns, p_dqla,          &
@@ -427,6 +432,7 @@
       !!----------------------------------------------------------------------
       REAL(wp), INTENT(in   ), DIMENSION(:,:,:)   ::   pst      ! ice surface temperature                   [Kelvin]
-      REAL(wp), INTENT(in   ), DIMENSION(:,:,:)   ::   palb_cs  ! ice albedo (clear    sky) (alb_ice_cs)         [%]
-      REAL(wp), INTENT(in   ), DIMENSION(:,:,:)   ::   palb_os  ! ice albedo (overcast sky) (alb_ice_os)         [%]
+      REAL(wp), INTENT(in   ), DIMENSION(:,:,:)   ::   palb_cs  ! ice albedo (clear    sky) (alb_ice_cs)         [-]
+      REAL(wp), INTENT(in   ), DIMENSION(:,:,:)   ::   palb_os  ! ice albedo (overcast sky) (alb_ice_os)         [-]
+      REAL(wp), INTENT(  out), DIMENSION(:,:,:)   ::   palb     ! ice albedo (actual value)                      [-]
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   p_taui   ! surface ice stress at I-point (i-component) [N/m2]
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   p_tauj   ! surface ice stress at I-point (j-component) [N/m2]
@@ -438,6 +444,6 @@
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   p_tpr    ! total precipitation          (T-point)   [Kg/m2/s]
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   p_spr    ! solid precipitation          (T-point)   [Kg/m2/s]
-      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   p_fr1    ! 1sr fraction of qsr penetration in ice         [%]
-      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   p_fr2    ! 2nd fraction of qsr penetration in ice         [%]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   p_fr1    ! 1sr fraction of qsr penetration in ice         [-]
+      REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   p_fr2    ! 2nd fraction of qsr penetration in ice         [-]
       CHARACTER(len=1), INTENT(in   )             ::   cd_grid  ! type of sea-ice grid ("C" or "B" grid)
       INTEGER, INTENT(in   )                      ::   pdim     ! number of ice categories
@@ -542,4 +548,9 @@
       !-----------------------------------------------------------!
       CALL blk_clio_qsr_ice( palb_cs, palb_os, p_qsr )
+      
+      DO jl = 1, ijpl
+         palb(:,:,jl) = ( palb_cs(:,:,jl) * ( 1.e0 - sf(jp_ccov)%fnow(:,:,1) )   &
+            &         +   palb_os(:,:,jl) * sf(jp_ccov)%fnow(:,:,1) )
+      END DO
 
       !                                     ! ========================== !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_core.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_core.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_core.F90	(revision 5075)
@@ -5,22 +5,27 @@
    !!=====================================================================
    !! History :  1.0  !  2004-08  (U. Schweckendiek)  Original code
-   !!            2.0  !  2005-04  (L. Brodeau, A.M. Treguier) additions: 
+   !!            2.0  !  2005-04  (L. Brodeau, A.M. Treguier) additions:
    !!                           -  new bulk routine for efficiency
    !!                           -  WINDS ARE NOW ASSUMED TO BE AT T POINTS in input files !!!!
-   !!                           -  file names and file characteristics in namelist 
-   !!                           -  Implement reading of 6-hourly fields   
-   !!            3.0  !  2006-06  (G. Madec) sbc rewritting   
-   !!             -   !  2006-12  (L. Brodeau) Original code for TURB_CORE_2Z
+   !!                           -  file names and file characteristics in namelist
+   !!                           -  Implement reading of 6-hourly fields
+   !!            3.0  !  2006-06  (G. Madec) sbc rewritting
+   !!             -   !  2006-12  (L. Brodeau) Original code for turb_core_2z
    !!            3.2  !  2009-04  (B. Lemaire)  Introduce iom_put
    !!            3.3  !  2010-10  (S. Masson)  add diurnal cycle
    !!            3.4  !  2011-11  (C. Harris) Fill arrays required by CICE
+   !!            3.7  !  2014-06  (L. Brodeau) simplification and optimization of CORE bulk
    !!----------------------------------------------------------------------
 
    !!----------------------------------------------------------------------
-   !!   sbc_blk_core  : bulk formulation as ocean surface boundary condition
-   !!                   (forced mode, CORE bulk formulea)
-   !!   blk_oce_core  : ocean: computes momentum, heat and freshwater fluxes
-   !!   blk_ice_core  : ice  : computes momentum, heat and freshwater fluxes
-   !!   turb_core     : computes the CORE turbulent transfer coefficients 
+   !!   sbc_blk_core    : bulk formulation as ocean surface boundary condition (forced mode, CORE bulk formulea)
+   !!   blk_oce_core    : computes momentum, heat and freshwater fluxes over ocean
+   !!   blk_ice_core    : computes momentum, heat and freshwater fluxes over ice
+   !!   blk_bio_meanqsr : compute daily mean short wave radiation over the ocean
+   !!   blk_ice_meanqsr : compute daily mean short wave radiation over the ice
+   !!   turb_core_2z    : Computes turbulent transfert coefficients
+   !!   cd_neutral_10m  : Estimate of the neutral drag coefficient at 10m
+   !!   psi_m           : universal profile stability function for momentum
+   !!   psi_h           : universal profile stability function for temperature and humidity
    !!----------------------------------------------------------------------
    USE oce             ! ocean dynamics and tracers
@@ -38,8 +43,6 @@
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
    USE prtctl          ! Print control
-   USE sbcwave,ONLY :  cdn_wave !wave module 
-#if defined key_lim3 || defined key_cice
+   USE sbcwave, ONLY   :  cdn_wave ! wave module
    USE sbc_ice         ! Surface boundary condition: ice fields
-#endif
    USE lib_fortran     ! to use key_nosignedzero
 
@@ -52,5 +55,5 @@
    PUBLIC   turb_core_2z         ! routine calles in sbcblk_mfs module
 
-   INTEGER , PARAMETER ::   jpfld   = 9           ! maximum number of files to read 
+   INTEGER , PARAMETER ::   jpfld   = 9           ! maximum number of files to read
    INTEGER , PARAMETER ::   jp_wndi = 1           ! index of 10m wind velocity (i-component) (m/s)    at T-point
    INTEGER , PARAMETER ::   jp_wndj = 2           ! index of 10m wind velocity (j-component) (m/s)    at T-point
@@ -62,7 +65,7 @@
    INTEGER , PARAMETER ::   jp_snow = 8           ! index of snow (solid prcipitation)       (kg/m2/s)
    INTEGER , PARAMETER ::   jp_tdif = 9           ! index of tau diff associated to HF tau   (N/m2)   at T-point
-   
+
    TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf   ! structure of input fields (file informations, fields read)
-         
+
    !                                             !!! CORE bulk parameters
    REAL(wp), PARAMETER ::   rhoa =    1.22        ! air density
@@ -75,10 +78,8 @@
 
    !                                  !!* Namelist namsbc_core : CORE bulk parameters
-   LOGICAL  ::   ln_2m       ! logical flag for height of air temp. and hum
    LOGICAL  ::   ln_taudif   ! logical flag to use the "mean of stress module - module of mean stress" data
    REAL(wp) ::   rn_pfac     ! multiplication factor for precipitation
    REAL(wp) ::   rn_efac     ! multiplication factor for evaporation (clem)
    REAL(wp) ::   rn_vfac     ! multiplication factor for ice/ocean velocity in the calculation of wind stress (clem)
-   LOGICAL  ::   ln_bulk2z   ! logical flag for case where z(q,t) and z(u) are specified in the namelist
    REAL(wp) ::   rn_zqt      ! z(q,t) : height of humidity and temperature measurements
    REAL(wp) ::   rn_zu       ! z(u)   : height of wind measurements
@@ -88,5 +89,5 @@
 #  include "vectopt_loop_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO-consortium (2010) 
+   !! NEMO/OPA 3.7 , NEMO-consortium (2014)
    !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -97,7 +98,7 @@
       !!---------------------------------------------------------------------
       !!                    ***  ROUTINE sbc_blk_core  ***
-      !!                   
+      !!
       !! ** Purpose :   provide at each time step the surface ocean fluxes
-      !!      (momentum, heat, freshwater and runoff) 
+      !!      (momentum, heat, freshwater and runoff)
       !!
       !! ** Method  : (1) READ each fluxes in NetCDF files:
@@ -118,17 +119,21 @@
       !! ** Action  :   defined at each time-step at the air-sea interface
       !!              - utau, vtau  i- and j-component of the wind stress
-      !!              - taum, wndm  wind stress and 10m wind modules at T-point
+      !!              - taum        wind stress module at T-point
+      !!              - wndm        wind speed  module at T-point over free ocean or leads in presence of sea-ice
       !!              - qns, qsr    non-solar and solar heat fluxes
       !!              - emp         upward mass flux (evapo. - precip.)
       !!              - sfx         salt flux due to freezing/melting (non-zero only if ice is present)
       !!                            (set in limsbc(_2).F90)
+      !!
+      !! ** References :   Large & Yeager, 2004 / Large & Yeager, 2008
+      !!                   Brodeau et al. Ocean Modelling 2010
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt   ! ocean time step
-      !!
+      !
       INTEGER  ::   ierror   ! return error code
       INTEGER  ::   ifpr     ! dummy loop indice
       INTEGER  ::   jfld     ! dummy loop arguments
       INTEGER  ::   ios      ! Local integer output status for namelist read
-      !!
+      !
       CHARACTER(len=100) ::  cn_dir   !   Root directory for location of core files
       TYPE(FLD_N), DIMENSION(jpfld) ::   slf_i     ! array of namelist informations on the fields to read
@@ -136,10 +141,10 @@
       TYPE(FLD_N) ::   sn_qlw , sn_tair, sn_prec, sn_snow      !   "                                 "
       TYPE(FLD_N) ::   sn_tdif                                 !   "                                 "
-      NAMELIST/namsbc_core/ cn_dir , ln_2m  , ln_taudif, rn_pfac, rn_efac, rn_vfac,  &
+      NAMELIST/namsbc_core/ cn_dir , ln_taudif, rn_pfac, rn_efac, rn_vfac,  &
          &                  sn_wndi, sn_wndj, sn_humi  , sn_qsr ,           &
          &                  sn_qlw , sn_tair, sn_prec  , sn_snow,           &
-         &                  sn_tdif, rn_zqt , ln_bulk2z, rn_zu
-      !!---------------------------------------------------------------------
-
+         &                  sn_tdif, rn_zqt,  rn_zu
+      !!---------------------------------------------------------------------
+      !
       !                                         ! ====================== !
       IF( kt == nit000 ) THEN                   !  First call kt=nit000  !
@@ -149,16 +154,16 @@
          READ  ( numnam_ref, namsbc_core, IOSTAT = ios, ERR = 901)
 901      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namsbc_core in reference namelist', lwp )
-
+         !
          REWIND( numnam_cfg )              ! Namelist namsbc_core in configuration namelist : CORE bulk parameters
          READ  ( numnam_cfg, namsbc_core, IOSTAT = ios, ERR = 902 )
 902      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namsbc_core in configuration namelist', lwp )
 
-         IF(lwm) WRITE ( numond, namsbc_core )
+         IF(lwm) WRITE( numond, namsbc_core )
          !                                         ! check: do we plan to use ln_dm2dc with non-daily forcing?
-         IF( ln_dm2dc .AND. sn_qsr%nfreqh /= 24 )   & 
-            &   CALL ctl_stop( 'sbc_blk_core: ln_dm2dc can be activated only with daily short-wave forcing' ) 
+         IF( ln_dm2dc .AND. sn_qsr%nfreqh /= 24 )   &
+            &   CALL ctl_stop( 'sbc_blk_core: ln_dm2dc can be activated only with daily short-wave forcing' )
          IF( ln_dm2dc .AND. sn_qsr%ln_tint ) THEN
             CALL ctl_warn( 'sbc_blk_core: ln_dm2dc is taking care of the temporal interpolation of daily qsr',   &
-                 &         '              ==> We force time interpolation = .false. for qsr' )
+               &         '              ==> We force time interpolation = .false. for qsr' )
             sn_qsr%ln_tint = .false.
          ENDIF
@@ -169,5 +174,5 @@
          slf_i(jp_prec) = sn_prec   ;   slf_i(jp_snow) = sn_snow
          slf_i(jp_tdif) = sn_tdif
-         !                 
+         !
          lhftau = ln_taudif                        ! do we use HF tau information?
          jfld = jpfld - COUNT( (/.NOT. lhftau/) )
@@ -191,5 +196,5 @@
       IF( MOD( kt - 1, nn_fsbc ) == 0 )   CALL blk_oce_core( kt, sf, sst_m, ssu_m, ssv_m )
 
-      ! If diurnal cycle is activated, compute a daily mean short waves flux for biogeochemistery 
+      ! If diurnal cycle is activated, compute a daily mean short waves flux for biogeochemistery
       IF( ltrcdm2dc )   CALL blk_bio_meanqsr
 
@@ -226,5 +231,4 @@
       !!              - qsr     : Solar heat flux over the ocean        (W/m2)
       !!              - qns     : Non Solar heat flux over the ocean    (W/m2)
-      !!              - evap    : Evaporation over the ocean            (kg/m2/s)
       !!              - emp     : evaporation minus precipitation       (kg/m2/s)
       !!
@@ -269,8 +273,5 @@
       zwnd_j(:,:) = 0.e0
 #if defined key_cyclone
-# if defined key_vectopt_loop
-!CDIR COLLAPSE
-# endif
-      CALL wnd_cyc( kt, zwnd_i, zwnd_j )    ! add Manu !
+      CALL wnd_cyc( kt, zwnd_i, zwnd_j )    ! add analytical tropical cyclone (Vincent et al. JGR 2012)
       DO jj = 2, jpjm1
          DO ji = fs_2, fs_jpim1   ! vect. opt.
@@ -279,7 +280,4 @@
          END DO
       END DO
-#endif
-#if defined key_vectopt_loop
-!CDIR COLLAPSE
 #endif
       DO jj = 2, jpjm1
@@ -292,6 +290,4 @@
       CALL lbc_lnk( zwnd_j(:,:) , 'T', -1. )
       ! ... scalar wind ( = | U10m - U_oce | ) at T-point (masked)
-!CDIR NOVERRCHK
-!CDIR COLLAPSE
       wndm(:,:) = SQRT(  zwnd_i(:,:) * zwnd_i(:,:)   &
          &             + zwnd_j(:,:) * zwnd_j(:,:)  ) * tmask(:,:,1)
@@ -300,5 +296,5 @@
       !      I   Radiative FLUXES                                                     !
       ! ----------------------------------------------------------------------------- !
-    
+
       ! ocean albedo assumed to be constant + modify now Qsr to include the diurnal cycle                    ! Short Wave
       zztmp = 1. - albo
@@ -306,5 +302,4 @@
       ELSE                  ;   qsr(:,:) = zztmp *          sf(jp_qsr)%fnow(:,:,1)   * tmask(:,:,1)
       ENDIF
-!CDIR COLLAPSE
       zqlw(:,:) = (  sf(jp_qlw)%fnow(:,:,1) - Stef * zst(:,:)*zst(:,:)*zst(:,:)*zst(:,:)  ) * tmask(:,:,1)   ! Long  Wave
       ! ----------------------------------------------------------------------------- !
@@ -313,43 +308,10 @@
 
       ! ... specific humidity at SST and IST
-!CDIR NOVERRCHK
-!CDIR COLLAPSE
-      zqsatw(:,:) = zcoef_qsatw * EXP( -5107.4 / zst(:,:) ) 
+      zqsatw(:,:) = zcoef_qsatw * EXP( -5107.4 / zst(:,:) )
 
       ! ... NCAR Bulk formulae, computation of Cd, Ch, Ce at T-point :
-      IF( ln_2m ) THEN
-         !! If air temp. and spec. hum. are given at different height (2m) than wind (10m) :
-         CALL TURB_CORE_2Z(2.,10., zst   , sf(jp_tair)%fnow,         &
-            &                      zqsatw, sf(jp_humi)%fnow, wndm,   &
-            &                      Cd    , Ch              , Ce  ,   &
-            &                      zt_zu , zq_zu                   )
-      ELSE IF( ln_bulk2z ) THEN
-         !! If the height of the air temp./spec. hum. and wind are to be specified by hand :
-         IF( rn_zqt == rn_zu ) THEN
-            !! If air temp. and spec. hum. are at the same height as wind :
-            CALL TURB_CORE_1Z( rn_zu, zst   , sf(jp_tair)%fnow(:,:,1),       &
-               &                      zqsatw, sf(jp_humi)%fnow(:,:,1), wndm, &
-               &                      Cd    , Ch                     , Ce  )
-         ELSE
-            !! If air temp. and spec. hum. are at a different height to wind :
-            CALL TURB_CORE_2Z(rn_zqt, rn_zu , zst   , sf(jp_tair)%fnow,         &
-               &                              zqsatw, sf(jp_humi)%fnow, wndm,   &
-               &                              Cd    , Ch              , Ce  ,   &
-               &                              zt_zu , zq_zu                 )
-         ENDIF
-      ELSE
-         !! If air temp. and spec. hum. are given at same height than wind (10m) :
-!gm bug?  at the compiling phase, add a copy in temporary arrays...  ==> check perf
-!         CALL TURB_CORE_1Z( 10., zst   (:,:), sf(jp_tair)%fnow(:,:),              &
-!            &                    zqsatw(:,:), sf(jp_humi)%fnow(:,:), wndm(:,:),   &
-!            &                    Cd    (:,:),             Ch  (:,:), Ce  (:,:)  )
-!gm bug
-! ARPDBG - this won't compile with gfortran. Fix but check performance
-! as per comment above.
-         CALL TURB_CORE_1Z( 10., zst   , sf(jp_tair)%fnow(:,:,1),       &
-            &                    zqsatw, sf(jp_humi)%fnow(:,:,1), wndm, &
-            &                    Cd    , Ch              , Ce    )
-      ENDIF
-
+      CALL turb_core_2z( rn_zqt, rn_zu, zst, sf(jp_tair)%fnow, zqsatw, sf(jp_humi)%fnow, wndm,   &
+         &               Cd, Ch, Ce, zt_zu, zq_zu )
+    
       ! ... tau module, i and j component
       DO jj = 1, jpj
@@ -363,6 +325,5 @@
 
       ! ... add the HF tau contribution to the wind stress module?
-      IF( lhftau ) THEN 
-!CDIR COLLAPSE
+      IF( lhftau ) THEN
          taum(:,:) = taum(:,:) + sf(jp_tdif)%fnow(:,:,1)
       ENDIF
@@ -371,8 +332,11 @@
       ! ... utau, vtau at U- and V_points, resp.
       !     Note the use of 0.5*(2-umask) in order to unmask the stress along coastlines
+      !     Note the use of MAX(tmask(i,j),tmask(i+1,j) is to mask tau over ice shelves
       DO jj = 1, jpjm1
          DO ji = 1, fs_jpim1
-            utau(ji,jj) = 0.5 * ( 2. - umask(ji,jj,1) ) * ( zwnd_i(ji,jj) + zwnd_i(ji+1,jj  ) )
-            vtau(ji,jj) = 0.5 * ( 2. - vmask(ji,jj,1) ) * ( zwnd_j(ji,jj) + zwnd_j(ji  ,jj+1) )
+            utau(ji,jj) = 0.5 * ( 2. - umask(ji,jj,1) ) * ( zwnd_i(ji,jj) + zwnd_i(ji+1,jj  ) ) &
+               &          * MAX(tmask(ji,jj,1),tmask(ji+1,jj,1))
+            vtau(ji,jj) = 0.5 * ( 2. - vmask(ji,jj,1) ) * ( zwnd_j(ji,jj) + zwnd_j(ji  ,jj+1) ) &
+               &          * MAX(tmask(ji,jj,1),tmask(ji,jj+1,1))
          END DO
       END DO
@@ -380,17 +344,17 @@
       CALL lbc_lnk( vtau(:,:), 'V', -1. )
 
+    
       !  Turbulent fluxes over ocean
       ! -----------------------------
-      IF( ln_2m .OR. ( ln_bulk2z .AND. rn_zqt /= rn_zu ) ) THEN
-         ! Values of temp. and hum. adjusted to height of wind must be used
-         zevap(:,:) = rn_efac * MAX( 0.e0, rhoa    *Ce(:,:)*( zqsatw(:,:) - zq_zu(:,:) ) * wndm(:,:) )   ! Evaporation
-         zqsb (:,:) =                      rhoa*cpa*Ch(:,:)*( zst   (:,:) - zt_zu(:,:) ) * wndm(:,:)     ! Sensible Heat
+      IF( ABS( rn_zu - rn_zqt) < 0.01_wp ) THEN
+         !! q_air and t_air are (or "are almost") given at 10m (wind reference height)
+         zevap(:,:) = rn_efac*MAX( 0._wp,     rhoa*Ce(:,:)*( zqsatw(:,:) - sf(jp_humi)%fnow(:,:,1) )*wndm(:,:) ) ! Evaporation
+         zqsb (:,:) =                     cpa*rhoa*Ch(:,:)*( zst   (:,:) - sf(jp_tair)%fnow(:,:,1) )*wndm(:,:)   ! Sensible Heat
       ELSE
-!CDIR COLLAPSE
-         zevap(:,:) = rn_efac * MAX( 0.e0, rhoa    *Ce(:,:)*( zqsatw(:,:) - sf(jp_humi)%fnow(:,:,1) ) * wndm(:,:) )   ! Evaporation
-!CDIR COLLAPSE
-         zqsb (:,:) =            rhoa*cpa*Ch(:,:)*( zst   (:,:) - sf(jp_tair)%fnow(:,:,1) ) * wndm(:,:)     ! Sensible Heat
+         !! q_air and t_air are not given at 10m (wind reference height)
+         ! Values of temp. and hum. adjusted to height of wind during bulk algorithm iteration must be used!!!
+         zevap(:,:) = rn_efac*MAX( 0._wp,     rhoa*Ce(:,:)*( zqsatw(:,:) - zq_zu(:,:) )*wndm(:,:) )   ! Evaporation
+         zqsb (:,:) =                     cpa*rhoa*Ch(:,:)*( zst   (:,:) - zt_zu(:,:) )*wndm(:,:)     ! Sensible Heat
       ENDIF
-!CDIR COLLAPSE
       zqla (:,:) = Lv * zevap(:,:)                                                              ! Latent Heat
 
@@ -409,16 +373,14 @@
       !     III    Total FLUXES                                                       !
       ! ----------------------------------------------------------------------------- !
-     
-!CDIR COLLAPSE
+      !
       emp (:,:) = (  zevap(:,:)                                          &   ! mass flux (evap. - precip.)
          &         - sf(jp_prec)%fnow(:,:,1) * rn_pfac  ) * tmask(:,:,1)
-!CDIR COLLAPSE
       qns(:,:) = zqlw(:,:) - zqsb(:,:) - zqla(:,:)                                &   ! Downward Non Solar flux
          &     - sf(jp_snow)%fnow(:,:,1) * rn_pfac * lfus                         &   ! remove latent melting heat for solid precip
          &     - zevap(:,:) * pst(:,:) * rcp                                      &   ! remove evap heat content at SST
          &     + ( sf(jp_prec)%fnow(:,:,1) - sf(jp_snow)%fnow(:,:,1) ) * rn_pfac  &   ! add liquid precip heat content at Tair
-         &     * ( sf(jp_tair)%fnow(:,:,1) - rt0 ) * rcp                          &   
+         &     * ( sf(jp_tair)%fnow(:,:,1) - rt0 ) * rcp                          &
          &     + sf(jp_snow)%fnow(:,:,1) * rn_pfac                                &   ! add solid  precip heat content at min(Tair,Tsnow)
-         &     * ( MIN( sf(jp_tair)%fnow(:,:,1), rt0_snow ) - rt0 ) * cpic 
+         &     * ( MIN( sf(jp_tair)%fnow(:,:,1), rt0_snow ) - rt0 ) * cpic * tmask(:,:,1)
       !
       CALL iom_put( "qlw_oce",   zqlw )                 ! output downward longwave heat over the ocean
@@ -442,58 +404,4 @@
       !
    END SUBROUTINE blk_oce_core
-  
-   SUBROUTINE blk_bio_meanqsr
-      !!---------------------------------------------------------------------
-      !!                     ***  ROUTINE blk_bio_meanqsr
-      !!                     
-      !! ** Purpose :   provide daily qsr_mean for PISCES when
-      !!                analytic diurnal cycle is applied in physic
-      !!                
-      !! ** Method  :   add part where there is no ice
-      !! 
-      !!---------------------------------------------------------------------
-      IF( nn_timing == 1 )  CALL timing_start('blk_bio_meanqsr')
-
-      qsr_mean(:,:) = (1. - albo ) *  sf(jp_qsr)%fnow(:,:,1)
-
-      IF( nn_timing == 1 )  CALL timing_stop('blk_bio_meanqsr')
-
-   END SUBROUTINE blk_bio_meanqsr
- 
- 
-   SUBROUTINE blk_ice_meanqsr(palb,p_qsr_mean,pdim)
-      !!---------------------------------------------------------------------
-      !!
-      !! ** Purpose :   provide the daily qsr_mean over sea_ice for PISCES when
-      !!                analytic diurnal cycle is applied in physic
-      !!
-      !! ** Method  :   compute qsr
-      !! 
-      !!---------------------------------------------------------------------
-      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   palb       ! ice albedo (clear sky) (alb_ice_cs)               [%]
-      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   p_qsr_mean !     solar heat flux over ice (T-point)         [W/m2]
-      INTEGER                   , INTENT(in   ) ::   pdim       ! number of ice categories
-      !!
-      INTEGER  ::   ijpl          ! number of ice categories (size of 3rd dim of input arrays)
-      INTEGER  ::   ji, jj, jl    ! dummy loop indices
-      REAL(wp) ::   zztmp         ! temporary variable
-      !!---------------------------------------------------------------------
-      IF( nn_timing == 1 )  CALL timing_start('blk_ice_meanqsr')
-      !
-      ijpl  = pdim                            ! number of ice categories
-      zztmp = 1. / ( 1. - albo )
-      !                                     ! ========================== !
-      DO jl = 1, ijpl                       !  Loop over ice categories  !
-         !                                  ! ========================== !
-         DO jj = 1 , jpj
-            DO ji = 1, jpi
-                  p_qsr_mean(ji,jj,jl) = zztmp * ( 1. - palb(ji,jj,jl) ) * qsr_mean(ji,jj)
-            END DO
-         END DO
-      END DO
-      !
-      IF( nn_timing == 1 )  CALL timing_stop('blk_ice_meanqsr')
-      !
-   END SUBROUTINE blk_ice_meanqsr  
  
    
@@ -518,5 +426,5 @@
       REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   pui      ! ice surface velocity (i- and i- components      [m/s]
       REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   pvi      !    at I-point (B-grid) or U & V-point (C-grid)
-      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   palb     ! ice albedo (clear sky) (alb_ice_cs)               [%]
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   palb     ! ice albedo (all skies)                            [%]
       REAL(wp), DIMENSION(:,:)  , INTENT(  out) ::   p_taui   ! i- & j-components of surface ice stress        [N/m2]
       REAL(wp), DIMENSION(:,:)  , INTENT(  out) ::   p_tauj   !   at I-point (B-grid) or U & V-point (C-grid)
@@ -538,5 +446,4 @@
       REAL(wp) ::   zcoef_wnorm, zcoef_wnorm2, zcoef_dqlw, zcoef_dqla, zcoef_dqsb
       REAL(wp) ::   zztmp                                        ! temporary variable
-      REAL(wp) ::   zcoef_frca                                   ! fractional cloud amount
       REAL(wp) ::   zwnorm_f, zwndi_f , zwndj_f                  ! relative wind module and components at F-point
       REAL(wp) ::             zwndi_t , zwndj_t                  ! relative wind components at T-point
@@ -562,5 +469,4 @@
       zcoef_dqla   = -Ls * Cice * 11637800. * (-5897.8)
       zcoef_dqsb   = rhoa * cpa * Cice
-      zcoef_frca   = 1.0  - 0.3
 
 !!gm brutal....
@@ -579,5 +485,4 @@
       CASE( 'I' )                  ! B-grid ice dynamics :   I-point (i.e. F-point with sea-ice indexation)
          !                           and scalar wind at T-point ( = | U10m - U_ice | ) (masked)
-!CDIR NOVERRCHK
          DO jj = 2, jpjm1
             DO ji = 2, jpim1   ! B grid : NO vector opt
@@ -604,7 +509,4 @@
          !
       CASE( 'C' )                  ! C-grid ice dynamics :   U & V-points (same as ocean)
-#if defined key_vectopt_loop
-!CDIR COLLAPSE
-#endif
          DO jj = 2, jpj
             DO ji = fs_2, jpi   ! vect. opt.
@@ -614,7 +516,4 @@
             END DO
          END DO
-#if defined key_vectopt_loop
-!CDIR COLLAPSE
-#endif
          DO jj = 2, jpjm1
             DO ji = fs_2, fs_jpim1   ! vect. opt.
@@ -635,8 +534,5 @@
       DO jl = 1, ijpl                       !  Loop over ice categories  !
          !                                  ! ========================== !
-!CDIR NOVERRCHK
-!CDIR COLLAPSE
          DO jj = 1 , jpj
-!CDIR NOVERRCHK
             DO ji = 1, jpi
                ! ----------------------------!
@@ -648,10 +544,5 @@
                p_qsr(ji,jj,jl) = zztmp * ( 1. - palb(ji,jj,jl) ) * qsr(ji,jj)
                ! Long  Wave (lw)
-               ! iovino
-               IF( ff(ji,jj) .GT. 0._wp ) THEN
-                  z_qlw(ji,jj,jl) = ( 0.95 * sf(jp_qlw)%fnow(ji,jj,1) - Stef * pst(ji,jj,jl) * zst3 ) * tmask(ji,jj,1)
-               ELSE
-                  z_qlw(ji,jj,jl) = 0.95 * ( sf(jp_qlw)%fnow(ji,jj,1) - Stef * pst(ji,jj,jl) * zst3 ) * tmask(ji,jj,1)
-               ENDIF
+               z_qlw(ji,jj,jl) = 0.95 * ( sf(jp_qlw)%fnow(ji,jj,1) - Stef * pst(ji,jj,jl) * zst3 ) * tmask(ji,jj,1)
                ! lw sensitivity
                z_dqlw(ji,jj,jl) = zcoef_dqlw * zst3                                               
@@ -668,5 +559,10 @@
                   &                         * (  11637800. * EXP( -5897.8 / pst(ji,jj,jl) ) / rhoa - sf(jp_humi)%fnow(ji,jj,1)  ) )
                ! Latent heat sensitivity for ice (Dqla/Dt)
-               p_dqla(ji,jj,jl) = rn_efac * zcoef_dqla * z_wnds_t(ji,jj) / ( zst2 ) * EXP( -5897.8 / pst(ji,jj,jl) )
+               IF( p_qla(ji,jj,jl) > 0._wp ) THEN
+                  p_dqla(ji,jj,jl) = rn_efac * zcoef_dqla * z_wnds_t(ji,jj) / ( zst2 ) * EXP( -5897.8 / pst(ji,jj,jl) )
+               ELSE
+                  p_dqla(ji,jj,jl) = 0._wp
+               ENDIF
+
                ! Sensible heat sensitivity (Dqsb_ice/Dtn_ice)
                z_dqsb(ji,jj,jl) = zcoef_dqsb * z_wnds_t(ji,jj)
@@ -676,7 +572,7 @@
                ! ----------------------------!
                ! Downward Non Solar flux
-               p_qns (ji,jj,jl) =     z_qlw (ji,jj,jl) - z_qsb (ji,jj,jl) - p_qla (ji,jj,jl)      
+               p_qns (ji,jj,jl) =     z_qlw (ji,jj,jl) - z_qsb (ji,jj,jl) - p_qla (ji,jj,jl)
                ! Total non solar heat flux sensitivity for ice
-               p_dqns(ji,jj,jl) = - ( z_dqlw(ji,jj,jl) + z_dqsb(ji,jj,jl) + p_dqla(ji,jj,jl) )    
+               p_dqns(ji,jj,jl) = - ( z_dqlw(ji,jj,jl) + z_dqsb(ji,jj,jl) + p_dqla(ji,jj,jl) )
             END DO
             !
@@ -689,16 +585,12 @@
       ! thin surface layer and penetrates inside the ice cover
       ! ( Maykut and Untersteiner, 1971 ; Ebert and Curry, 1993 )
-    
-!CDIR COLLAPSE
-      p_fr1(:,:) = ( 0.18 * ( 1.0 - zcoef_frca ) + 0.35 * zcoef_frca )
-!CDIR COLLAPSE
-      p_fr2(:,:) = ( 0.82 * ( 1.0 - zcoef_frca ) + 0.65 * zcoef_frca )
-       
-!CDIR COLLAPSE
+      !
+      p_fr1(:,:) = ( 0.18 * ( 1.0 - cldf_ice ) + 0.35 * cldf_ice )
+      p_fr2(:,:) = ( 0.82 * ( 1.0 - cldf_ice ) + 0.65 * cldf_ice )
+      !
       p_tpr(:,:) = sf(jp_prec)%fnow(:,:,1) * rn_pfac      ! total precipitation [kg/m2/s]
-!CDIR COLLAPSE
       p_spr(:,:) = sf(jp_snow)%fnow(:,:,1) * rn_pfac      ! solid precipitation [kg/m2/s]
-      CALL iom_put( 'snowpre', p_spr * 86400. )                  ! Snow precipitation 
-      CALL iom_put( 'precip', p_tpr * 86400. )                   ! Total precipitation 
+      CALL iom_put( 'snowpre', p_spr * 86400. )                  ! Snow precipitation
+      CALL iom_put( 'precip' , p_tpr * 86400. )                  ! Total precipitation
       !
       IF(ln_ctl) THEN
@@ -713,160 +605,90 @@
       ENDIF
 
-      CALL wrk_dealloc( jpi,jpj, z_wnds_t )
-      CALL wrk_dealloc( jpi,jpj,pdim, z_qlw, z_qsb, z_dqlw, z_dqsb ) 
+      CALL wrk_dealloc( jpi,jpj,   z_wnds_t )
+      CALL wrk_dealloc( jpi,jpj,   pdim, z_qlw, z_qsb, z_dqlw, z_dqsb )
       !
       IF( nn_timing == 1 )  CALL timing_stop('blk_ice_core')
       !
    END SUBROUTINE blk_ice_core
-  
-
-   SUBROUTINE TURB_CORE_1Z(zu, sst, T_a, q_sat, q_a,   &
-      &                        dU , Cd , Ch   , Ce   )
+
+
+   SUBROUTINE blk_bio_meanqsr
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE blk_bio_meanqsr
+      !!                     
+      !! ** Purpose :   provide daily qsr_mean for PISCES when
+      !!                analytic diurnal cycle is applied in physic
+      !!                
+      !! ** Method  :   add part where there is no ice
+      !! 
+      !!---------------------------------------------------------------------
+      IF( nn_timing == 1 )  CALL timing_start('blk_bio_meanqsr')
+      !
+      qsr_mean(:,:) = (1. - albo ) *  sf(jp_qsr)%fnow(:,:,1)
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('blk_bio_meanqsr')
+      !
+   END SUBROUTINE blk_bio_meanqsr
+ 
+ 
+   SUBROUTINE blk_ice_meanqsr( palb, p_qsr_mean, pdim )
+      !!---------------------------------------------------------------------
+      !!
+      !! ** Purpose :   provide the daily qsr_mean over sea_ice for PISCES when
+      !!                analytic diurnal cycle is applied in physic
+      !!
+      !! ** Method  :   compute qsr
+      !! 
+      !!---------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   palb       ! ice albedo (clear sky) (alb_ice_cs)               [%]
+      REAL(wp), DIMENSION(:,:,:), INTENT(  out) ::   p_qsr_mean !     solar heat flux over ice (T-point)         [W/m2]
+      INTEGER                   , INTENT(in   ) ::   pdim       ! number of ice categories
+      !
+      INTEGER  ::   ijpl          ! number of ice categories (size of 3rd dim of input arrays)
+      INTEGER  ::   ji, jj, jl    ! dummy loop indices
+      REAL(wp) ::   zztmp         ! temporary variable
+      !!---------------------------------------------------------------------
+      IF( nn_timing == 1 )  CALL timing_start('blk_ice_meanqsr')
+      !
+      ijpl  = pdim                            ! number of ice categories
+      zztmp = 1. / ( 1. - albo )
+      !                                     ! ========================== !
+      DO jl = 1, ijpl                       !  Loop over ice categories  !
+         !                                  ! ========================== !
+         DO jj = 1 , jpj
+            DO ji = 1, jpi
+                  p_qsr_mean(ji,jj,jl) = zztmp * ( 1. - palb(ji,jj,jl) ) * qsr_mean(ji,jj)
+            END DO
+         END DO
+      END DO
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('blk_ice_meanqsr')
+      !
+   END SUBROUTINE blk_ice_meanqsr  
+
+
+   SUBROUTINE turb_core_2z( zt, zu, sst, T_zt, q_sat, q_zt, dU,    &
+      &                      Cd, Ch, Ce , T_zu, q_zu )
       !!----------------------------------------------------------------------
       !!                      ***  ROUTINE  turb_core  ***
       !!
       !! ** Purpose :   Computes turbulent transfert coefficients of surface
-      !!                fluxes according to Large & Yeager (2004)
-      !!
-      !! ** Method  :   I N E R T I A L   D I S S I P A T I O N   M E T H O D
-      !!      Momentum, Latent and sensible heat exchange coefficients
-      !!      Caution: this procedure should only be used in cases when air
-      !!      temperature (T_air), air specific humidity (q_air) and wind (dU)
-      !!      are provided at the same height 'zzu'!
-      !!
-      !! References :   Large & Yeager, 2004 : ???
-      !!----------------------------------------------------------------------
-      REAL(wp)                , INTENT(in   ) ::   zu      ! altitude of wind measurement       [m]
-      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   sst     ! sea surface temperature         [Kelvin]
-      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   T_a     ! potential air temperature       [Kelvin]
-      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   q_sat   ! sea surface specific humidity   [kg/kg]
-      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   q_a     ! specific air humidity           [kg/kg]
-      REAL(wp), DIMENSION(:,:), INTENT(in   ) ::   dU      ! wind module |U(zu)-U(0)|        [m/s]
-      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   Cd      ! transfert coefficient for momentum       (tau)
-      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   Ch      ! transfert coefficient for temperature (Q_sens)
-      REAL(wp), DIMENSION(:,:), INTENT(  out) ::   Ce      ! transfert coefficient for evaporation  (Q_lat)
-      !!
-      INTEGER :: j_itt
-      INTEGER , PARAMETER ::   nb_itt = 3
-      REAL(wp), PARAMETER ::   grav   = 9.8   ! gravity                       
-      REAL(wp), PARAMETER ::   kappa  = 0.4   ! von Karman s constant
-
-      REAL(wp), DIMENSION(:,:), POINTER  ::   dU10          ! dU                                   [m/s]
-      REAL(wp), DIMENSION(:,:), POINTER  ::   dT            ! air/sea temperature differeence      [K]
-      REAL(wp), DIMENSION(:,:), POINTER  ::   dq            ! air/sea humidity difference          [K]
-      REAL(wp), DIMENSION(:,:), POINTER  ::   Cd_n10        ! 10m neutral drag coefficient
-      REAL(wp), DIMENSION(:,:), POINTER  ::   Ce_n10        ! 10m neutral latent coefficient
-      REAL(wp), DIMENSION(:,:), POINTER  ::   Ch_n10        ! 10m neutral sensible coefficient
-      REAL(wp), DIMENSION(:,:), POINTER  ::   sqrt_Cd_n10   ! root square of Cd_n10
-      REAL(wp), DIMENSION(:,:), POINTER  ::   sqrt_Cd       ! root square of Cd
-      REAL(wp), DIMENSION(:,:), POINTER  ::   T_vpot        ! virtual potential temperature        [K]
-      REAL(wp), DIMENSION(:,:), POINTER  ::   T_star        ! turbulent scale of tem. fluct.
-      REAL(wp), DIMENSION(:,:), POINTER  ::   q_star        ! turbulent humidity of temp. fluct.
-      REAL(wp), DIMENSION(:,:), POINTER  ::   U_star        ! turb. scale of velocity fluct.
-      REAL(wp), DIMENSION(:,:), POINTER  ::   L             ! Monin-Obukov length                  [m]
-      REAL(wp), DIMENSION(:,:), POINTER  ::   zeta          ! stability parameter at height zu
-      REAL(wp), DIMENSION(:,:), POINTER  ::   U_n10         ! neutral wind velocity at 10m         [m]   
-      REAL(wp), DIMENSION(:,:), POINTER  ::   xlogt, xct, zpsi_h, zpsi_m
-      
-      INTEGER , DIMENSION(:,:), POINTER  ::   stab          ! 1st guess stability test integer
-      !!----------------------------------------------------------------------
-      !
-      IF( nn_timing == 1 )  CALL timing_start('TURB_CORE_1Z')
-      !
-      CALL wrk_alloc( jpi,jpj, stab )   ! integer
-      CALL wrk_alloc( jpi,jpj, dU10, dT, dq, Cd_n10, Ce_n10, Ch_n10, sqrt_Cd_n10, sqrt_Cd, L )
-      CALL wrk_alloc( jpi,jpj, T_vpot, T_star, q_star, U_star, zeta, U_n10, xlogt, xct, zpsi_h, zpsi_m )
-
-      !! * Start
-      !! Air/sea differences
-      dU10 = max(0.5, dU)     ! we don't want to fall under 0.5 m/s
-      dT = T_a - sst          ! assuming that T_a is allready the potential temp. at zzu
-      dq = q_a - q_sat
-      !!    
-      !! Virtual potential temperature
-      T_vpot = T_a*(1. + 0.608*q_a)
-      !!
-      !! Neutral Drag Coefficient
-      stab    = 0.5 + sign(0.5,dT)    ! stable : stab = 1 ; unstable : stab = 0 
-      IF  ( ln_cdgw ) THEN
-        cdn_wave = cdn_wave - rsmall*(tmask(:,:,1)-1)
-        Cd_n10(:,:) =   cdn_wave
-      ELSE
-        Cd_n10  = 1.e-3 * ( 2.7/dU10 + 0.142 + dU10/13.09 )    !   L & Y eq. (6a)
-      ENDIF
-      sqrt_Cd_n10 = sqrt(Cd_n10)
-      Ce_n10  = 1.e-3 * ( 34.6 * sqrt_Cd_n10 )               !   L & Y eq. (6b)
-      Ch_n10  = 1.e-3*sqrt_Cd_n10*(18.*stab + 32.7*(1.-stab)) !   L & Y eq. (6c), (6d)
-      !!
-      !! Initializing transfert coefficients with their first guess neutral equivalents :
-      Cd = Cd_n10 ;  Ce = Ce_n10 ;  Ch = Ch_n10 ;  sqrt_Cd = sqrt(Cd)
-
-      !! * Now starting iteration loop
-      DO j_itt=1, nb_itt
-         !! Turbulent scales :
-         U_star  = sqrt_Cd*dU10                !   L & Y eq. (7a)
-         T_star  = Ch/sqrt_Cd*dT               !   L & Y eq. (7b)
-         q_star  = Ce/sqrt_Cd*dq               !   L & Y eq. (7c)
-
-         !! Estimate the Monin-Obukov length :
-         L  = (U_star**2)/( kappa*grav*(T_star/T_vpot + q_star/(q_a + 1./0.608)) )
-
-         !! Stability parameters :
-         zeta  = zu/L ;  zeta   = sign( min(abs(zeta),10.0), zeta )
-         zpsi_h  = psi_h(zeta)
-         zpsi_m  = psi_m(zeta)
-
-         IF  ( ln_cdgw ) THEN
-           sqrt_Cd=kappa/((kappa/sqrt_Cd_n10) - zpsi_m) ; Cd=sqrt_Cd*sqrt_Cd;
-         ELSE
-           !! Shifting the wind speed to 10m and neutral stability :
-           U_n10 = dU10*1./(1. + sqrt_Cd_n10/kappa*(log(zu/10.) - zpsi_m)) !  L & Y eq. (9a)
-
-           !! Updating the neutral 10m transfer coefficients :
-           Cd_n10  = 1.e-3 * (2.7/U_n10 + 0.142 + U_n10/13.09)              !  L & Y eq. (6a)
-           sqrt_Cd_n10 = sqrt(Cd_n10)
-           Ce_n10  = 1.e-3 * (34.6 * sqrt_Cd_n10)                           !  L & Y eq. (6b)
-           stab    = 0.5 + sign(0.5,zeta)
-           Ch_n10  = 1.e-3*sqrt_Cd_n10*(18.*stab + 32.7*(1.-stab))           !  L & Y eq. (6c), (6d)
-
-           !! Shifting the neutral  10m transfer coefficients to ( zu , zeta ) :
-           !!
-           xct = 1. + sqrt_Cd_n10/kappa*(log(zu/10) - zpsi_m)
-           Cd  = Cd_n10/(xct*xct) ;  sqrt_Cd = sqrt(Cd)
-         ENDIF
-         !!
-         xlogt = log(zu/10.) - zpsi_h
-         !!
-         xct = 1. + Ch_n10*xlogt/kappa/sqrt_Cd_n10
-         Ch  = Ch_n10*sqrt_Cd/sqrt_Cd_n10/xct
-         !!
-         xct = 1. + Ce_n10*xlogt/kappa/sqrt_Cd_n10
-         Ce  = Ce_n10*sqrt_Cd/sqrt_Cd_n10/xct
-         !!
-      END DO
-      !!
-      CALL wrk_dealloc( jpi,jpj, stab )   ! integer
-      CALL wrk_dealloc( jpi,jpj, dU10, dT, dq, Cd_n10, Ce_n10, Ch_n10, sqrt_Cd_n10, sqrt_Cd, L )
-      CALL wrk_dealloc( jpi,jpj, T_vpot, T_star, q_star, U_star, zeta, U_n10, xlogt, xct, zpsi_h, zpsi_m )
-      !
-      IF( nn_timing == 1 )  CALL timing_stop('TURB_CORE_1Z')
-      !
-    END SUBROUTINE TURB_CORE_1Z
-
-
-    SUBROUTINE TURB_CORE_2Z(zt, zu, sst, T_zt, q_sat, q_zt, dU, Cd, Ch, Ce, T_zu, q_zu)
-      !!----------------------------------------------------------------------
-      !!                      ***  ROUTINE  turb_core  ***
-      !!
-      !! ** Purpose :   Computes turbulent transfert coefficients of surface 
-      !!                fluxes according to Large & Yeager (2004).
-      !!
-      !! ** Method  :   I N E R T I A L   D I S S I P A T I O N   M E T H O D
-      !!      Momentum, Latent and sensible heat exchange coefficients
-      !!      Caution: this procedure should only be used in cases when air
-      !!      temperature (T_air) and air specific humidity (q_air) are at a
-      !!      different height to wind (dU).
-      !!
-      !! References :   Large & Yeager, 2004 : ???
+      !!                fluxes according to Large & Yeager (2004) and Large & Yeager (2008)
+      !!                If relevant (zt /= zu), adjust temperature and humidity from height zt to zu
+      !!
+      !! ** Method : Monin Obukhov Similarity Theory 
+      !!             + Large & Yeager (2004,2008) closure: CD_n10 = f(U_n10)
+      !!
+      !! ** References :   Large & Yeager, 2004 / Large & Yeager, 2008
+      !!
+      !! ** Last update: Laurent Brodeau, June 2014:
+      !!    - handles both cases zt=zu and zt/=zu
+      !!    - optimized: less 2D arrays allocated and less operations
+      !!    - better first guess of stability by checking air-sea difference of virtual temperature
+      !!       rather than temperature difference only...
+      !!    - added function "cd_neutral_10m" that uses the improved parametrization of 
+      !!      Large & Yeager 2008. Drag-coefficient reduction for Cyclone conditions!
+      !!    - using code-wide physical constants defined into "phycst.mod" rather than redifining them
+      !!      => 'vkarmn' and 'grav'
       !!----------------------------------------------------------------------
       REAL(wp), INTENT(in   )                     ::   zt       ! height for T_zt and q_zt                   [m]
@@ -876,5 +698,5 @@
       REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   q_sat    ! sea surface specific humidity         [kg/kg]
       REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   q_zt     ! specific air humidity                 [kg/kg]
-      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   dU       ! relative wind module |U(zu)-U(0)|       [m/s]
+      REAL(wp), INTENT(in   ), DIMENSION(jpi,jpj) ::   dU       ! relative wind module at zu            [m/s]
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Cd       ! transfer coefficient for momentum         (tau)
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   Ch       ! transfer coefficient for sensible heat (Q_sens)
@@ -882,168 +704,199 @@
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   T_zu     ! air temp. shifted at zu                     [K]
       REAL(wp), INTENT(  out), DIMENSION(jpi,jpj) ::   q_zu     ! spec. hum.  shifted at zu               [kg/kg]
-
-      INTEGER :: j_itt
-      INTEGER , PARAMETER :: nb_itt = 5              ! number of itterations
-      REAL(wp), PARAMETER ::   grav   = 9.8          ! gravity                       
-      REAL(wp), PARAMETER ::   kappa  = 0.4          ! von Karman's constant
-      
-      REAL(wp), DIMENSION(:,:), POINTER ::   dU10          ! dU                                [m/s]
-      REAL(wp), DIMENSION(:,:), POINTER ::   dT            ! air/sea temperature differeence   [K]
-      REAL(wp), DIMENSION(:,:), POINTER ::   dq            ! air/sea humidity difference       [K]
-      REAL(wp), DIMENSION(:,:), POINTER ::   Cd_n10        ! 10m neutral drag coefficient
+      !
+      INTEGER ::   j_itt
+      INTEGER , PARAMETER ::   nb_itt = 5       ! number of itterations
+      LOGICAL ::   l_zt_equal_zu = .FALSE.      ! if q and t are given at different height than U
+      !
+      REAL(wp), DIMENSION(:,:), POINTER ::   U_zu          ! relative wind at zu                            [m/s]
       REAL(wp), DIMENSION(:,:), POINTER ::   Ce_n10        ! 10m neutral latent coefficient
       REAL(wp), DIMENSION(:,:), POINTER ::   Ch_n10        ! 10m neutral sensible coefficient
       REAL(wp), DIMENSION(:,:), POINTER ::   sqrt_Cd_n10   ! root square of Cd_n10
       REAL(wp), DIMENSION(:,:), POINTER ::   sqrt_Cd       ! root square of Cd
-      REAL(wp), DIMENSION(:,:), POINTER ::   T_vpot        ! virtual potential temperature        [K]
-      REAL(wp), DIMENSION(:,:), POINTER ::   T_star        ! turbulent scale of tem. fluct.
-      REAL(wp), DIMENSION(:,:), POINTER ::   q_star        ! turbulent humidity of temp. fluct.
-      REAL(wp), DIMENSION(:,:), POINTER ::   U_star        ! turb. scale of velocity fluct.
-      REAL(wp), DIMENSION(:,:), POINTER ::   L             ! Monin-Obukov length                  [m]
       REAL(wp), DIMENSION(:,:), POINTER ::   zeta_u        ! stability parameter at height zu
       REAL(wp), DIMENSION(:,:), POINTER ::   zeta_t        ! stability parameter at height zt
-      REAL(wp), DIMENSION(:,:), POINTER ::   U_n10         ! neutral wind velocity at 10m        [m]
-      REAL(wp), DIMENSION(:,:), POINTER ::   xlogt, xct, zpsi_hu, zpsi_ht, zpsi_m
-
-      INTEGER , DIMENSION(:,:), POINTER ::   stab          ! 1st stability test integer
+      REAL(wp), DIMENSION(:,:), POINTER ::   zpsi_h_u, zpsi_m_u
+      REAL(wp), DIMENSION(:,:), POINTER ::   ztmp0, ztmp1, ztmp2
+      REAL(wp), DIMENSION(:,:), POINTER ::   stab          ! 1st stability test integer
       !!----------------------------------------------------------------------
-      !
-      IF( nn_timing == 1 )  CALL timing_start('TURB_CORE_2Z')
-      !
-      CALL wrk_alloc( jpi,jpj, dU10, dT, dq, Cd_n10, Ce_n10, Ch_n10, sqrt_Cd_n10, sqrt_Cd, L )
-      CALL wrk_alloc( jpi,jpj, T_vpot, T_star, q_star, U_star, zeta_u, zeta_t, U_n10 )
-      CALL wrk_alloc( jpi,jpj, xlogt, xct, zpsi_hu, zpsi_ht, zpsi_m )
-      CALL wrk_alloc( jpi,jpj, stab )   ! interger
-
-      !! Initial air/sea differences
-      dU10 = max(0.5, dU)      !  we don't want to fall under 0.5 m/s
-      dT = T_zt - sst 
-      dq = q_zt - q_sat
-
-      !! Neutral Drag Coefficient :
-      stab = 0.5 + sign(0.5,dT)                 ! stab = 1  if dT > 0  -> STABLE
-      IF( ln_cdgw ) THEN
-        cdn_wave = cdn_wave - rsmall*(tmask(:,:,1)-1)
-        Cd_n10(:,:) =   cdn_wave
+
+      IF( nn_timing == 1 )  CALL timing_start('turb_core_2z')
+    
+      CALL wrk_alloc( jpi,jpj, U_zu, Ce_n10, Ch_n10, sqrt_Cd_n10, sqrt_Cd )
+      CALL wrk_alloc( jpi,jpj, zeta_u, stab )
+      CALL wrk_alloc( jpi,jpj, zpsi_h_u, zpsi_m_u, ztmp0, ztmp1, ztmp2 )
+
+      l_zt_equal_zu = .FALSE.
+      IF( ABS(zu - zt) < 0.01 ) l_zt_equal_zu = .TRUE.    ! testing "zu == zt" is risky with double precision
+
+      IF( .NOT. l_zt_equal_zu )   CALL wrk_alloc( jpi,jpj, zeta_t )
+
+      U_zu = MAX( 0.5 , dU )   !  relative wind speed at zu (normally 10m), we don't want to fall under 0.5 m/s
+
+      !! First guess of stability: 
+      ztmp0 = T_zt*(1. + 0.608*q_zt) - sst*(1. + 0.608*q_sat) ! air-sea difference of virtual pot. temp. at zt
+      stab  = 0.5 + sign(0.5,ztmp0)                           ! stab = 1 if dTv > 0  => STABLE, 0 if unstable
+
+      !! Neutral coefficients at 10m:
+      IF( ln_cdgw ) THEN      ! wave drag case
+         cdn_wave(:,:) = cdn_wave(:,:) + rsmall * ( 1._wp - tmask(:,:,1) )
+         ztmp0   (:,:) = cdn_wave(:,:)
       ELSE
-        Cd_n10  = 1.e-3*( 2.7/dU10 + 0.142 + dU10/13.09 ) 
+         ztmp0 = cd_neutral_10m( U_zu )
       ENDIF
-      sqrt_Cd_n10 = sqrt(Cd_n10)
+      sqrt_Cd_n10 = SQRT( ztmp0 )
       Ce_n10  = 1.e-3*( 34.6 * sqrt_Cd_n10 )
       Ch_n10  = 1.e-3*sqrt_Cd_n10*(18.*stab + 32.7*(1. - stab))
-
+    
       !! Initializing transf. coeff. with their first guess neutral equivalents :
-      Cd = Cd_n10 ;  Ce = Ce_n10 ;  Ch = Ch_n10 ;  sqrt_Cd = sqrt(Cd)
-
-      !! Initializing z_u values with z_t values :
-      T_zu = T_zt ;  q_zu = q_zt
+      Cd = ztmp0   ;   Ce = Ce_n10   ;   Ch = Ch_n10   ;   sqrt_Cd = sqrt_Cd_n10
+
+      !! Initializing values at z_u with z_t values:
+      T_zu = T_zt   ;   q_zu = q_zt
 
       !!  * Now starting iteration loop
       DO j_itt=1, nb_itt
-         dT = T_zu - sst ;  dq = q_zu - q_sat ! Updating air/sea differences
-         T_vpot = T_zu*(1. + 0.608*q_zu)    ! Updating virtual potential temperature at zu
-         U_star = sqrt_Cd*dU10                ! Updating turbulent scales :   (L & Y eq. (7))
-         T_star  = Ch/sqrt_Cd*dT              !
-         q_star  = Ce/sqrt_Cd*dq              !
-         !!
-         L = (U_star*U_star) &                ! Estimate the Monin-Obukov length at height zu
-              & / (kappa*grav/T_vpot*(T_star*(1.+0.608*q_zu) + 0.608*T_zu*q_star))
+         !
+         ztmp1 = T_zu - sst   ! Updating air/sea differences
+         ztmp2 = q_zu - q_sat 
+
+         ! Updating turbulent scales :   (L&Y 2004 eq. (7))
+         ztmp1  = Ch/sqrt_Cd*ztmp1    ! theta*
+         ztmp2  = Ce/sqrt_Cd*ztmp2    ! q*
+       
+         ztmp0 = T_zu*(1. + 0.608*q_zu) ! virtual potential temperature at zu
+
+         ! Estimate the inverse of Monin-Obukov length (1/L) at height zu:
+         ztmp0 =  (vkarmn*grav/ztmp0*(ztmp1*(1.+0.608*q_zu) + 0.608*T_zu*ztmp2)) / (Cd*U_zu*U_zu) 
+         !                                                                     ( Cd*U_zu*U_zu is U*^2 at zu)
+
          !! Stability parameters :
-         zeta_u  = zu/L  ;  zeta_u = sign( min(abs(zeta_u),10.0), zeta_u )
-         zeta_t  = zt/L  ;  zeta_t = sign( min(abs(zeta_t),10.0), zeta_t )
-         zpsi_hu = psi_h(zeta_u)
-         zpsi_ht = psi_h(zeta_t)
-         zpsi_m  = psi_m(zeta_u)
-         !!
-         !! Shifting the wind speed to 10m and neutral stability : (L & Y eq.(9a))
-!        U_n10 = dU10/(1. + sqrt_Cd_n10/kappa*(log(zu/10.) - psi_m(zeta_u)))
-         U_n10 = dU10/(1. + sqrt_Cd_n10/kappa*(log(zu/10.) - zpsi_m))
-         !!
-         !! Shifting temperature and humidity at zu :          (L & Y eq. (9b-9c))
-!        T_zu = T_zt - T_star/kappa*(log(zt/zu) + psi_h(zeta_u) - psi_h(zeta_t))
-         T_zu = T_zt - T_star/kappa*(log(zt/zu) + zpsi_hu - zpsi_ht)
-!        q_zu = q_zt - q_star/kappa*(log(zt/zu) + psi_h(zeta_u) - psi_h(zeta_t))
-         q_zu = q_zt - q_star/kappa*(log(zt/zu) + zpsi_hu - zpsi_ht)
-         !!
-         !! q_zu cannot have a negative value : forcing 0
-         stab = 0.5 + sign(0.5,q_zu) ;  q_zu = stab*q_zu
-         !!
-         IF( ln_cdgw ) THEN
-            sqrt_Cd=kappa/((kappa/sqrt_Cd_n10) - zpsi_m) ; Cd=sqrt_Cd*sqrt_Cd;
+         zeta_u   = zu*ztmp0   ;  zeta_u = sign( min(abs(zeta_u),10.0), zeta_u )
+         zpsi_h_u = psi_h( zeta_u )
+         zpsi_m_u = psi_m( zeta_u )
+       
+         !! Shifting temperature and humidity at zu (L&Y 2004 eq. (9b-9c))
+         IF ( .NOT. l_zt_equal_zu ) THEN
+            zeta_t = zt*ztmp0 ;  zeta_t = sign( min(abs(zeta_t),10.0), zeta_t )
+            stab = LOG(zu/zt) - zpsi_h_u + psi_h(zeta_t)  ! stab just used as temp array!!!
+            T_zu = T_zt + ztmp1/vkarmn*stab    ! ztmp1 is still theta*
+            q_zu = q_zt + ztmp2/vkarmn*stab    ! ztmp2 is still q*
+            q_zu = max(0., q_zu)
+         END IF
+       
+         IF( ln_cdgw ) THEN      ! surface wave case
+            sqrt_Cd = vkarmn / ( vkarmn / sqrt_Cd_n10 - zpsi_m_u ) 
+            Cd      = sqrt_Cd * sqrt_Cd
          ELSE
-           !! Updating the neutral 10m transfer coefficients :
-           Cd_n10  = 1.e-3 * (2.7/U_n10 + 0.142 + U_n10/13.09)    ! L & Y eq. (6a)
-           sqrt_Cd_n10 = sqrt(Cd_n10)
-           Ce_n10  = 1.e-3 * (34.6 * sqrt_Cd_n10)                 ! L & Y eq. (6b)
-           stab    = 0.5 + sign(0.5,zeta_u)
-           Ch_n10  = 1.e-3*sqrt_Cd_n10*(18.*stab + 32.7*(1.-stab)) ! L & Y eq. (6c-6d)
-           !!
-           !!
-           !! Shifting the neutral 10m transfer coefficients to (zu,zeta_u) :
-           xct = 1. + sqrt_Cd_n10/kappa*(log(zu/10.) - zpsi_m)   ! L & Y eq. (10a)
-           Cd = Cd_n10/(xct*xct) ; sqrt_Cd = sqrt(Cd)
+           ! Update neutral wind speed at 10m and neutral Cd at 10m (L&Y 2004 eq. 9a)...
+           !   In very rare low-wind conditions, the old way of estimating the
+           !   neutral wind speed at 10m leads to a negative value that causes the code
+           !   to crash. To prevent this a threshold of 0.25m/s is imposed.
+           ztmp0 = MAX( 0.25 , U_zu/(1. + sqrt_Cd_n10/vkarmn*(LOG(zu/10.) - zpsi_m_u)) ) !  U_n10
+           ztmp0 = cd_neutral_10m(ztmp0)                                                 ! Cd_n10
+           sqrt_Cd_n10 = sqrt(ztmp0)
+       
+           Ce_n10  = 1.e-3 * (34.6 * sqrt_Cd_n10)                     ! L&Y 2004 eq. (6b)
+           stab    = 0.5 + sign(0.5,zeta_u)                           ! update stability
+           Ch_n10  = 1.e-3*sqrt_Cd_n10*(18.*stab + 32.7*(1. - stab))  ! L&Y 2004 eq. (6c-6d)
+
+           !! Update of transfer coefficients:
+           ztmp1 = 1. + sqrt_Cd_n10/vkarmn*(LOG(zu/10.) - zpsi_m_u)   ! L&Y 2004 eq. (10a)
+           Cd      = ztmp0 / ( ztmp1*ztmp1 )   
+           sqrt_Cd = SQRT( Cd )
          ENDIF
-         !!
-         xlogt = log(zu/10.) - zpsi_hu
-         !!
-         xct = 1. + Ch_n10*xlogt/kappa/sqrt_Cd_n10               ! L & Y eq. (10b)
-         Ch  = Ch_n10*sqrt_Cd/sqrt_Cd_n10/xct
-         !!
-         xct = 1. + Ce_n10*xlogt/kappa/sqrt_Cd_n10               ! L & Y eq. (10c)
-         Ce  = Ce_n10*sqrt_Cd/sqrt_Cd_n10/xct
-         !!
-         !!
+         !
+         ztmp0 = (LOG(zu/10.) - zpsi_h_u) / vkarmn / sqrt_Cd_n10
+         ztmp2 = sqrt_Cd / sqrt_Cd_n10
+         ztmp1 = 1. + Ch_n10*ztmp0               
+         Ch  = Ch_n10*ztmp2 / ztmp1  ! L&Y 2004 eq. (10b)
+         !
+         ztmp1 = 1. + Ce_n10*ztmp0               
+         Ce  = Ce_n10*ztmp2 / ztmp1  ! L&Y 2004 eq. (10c)
+         !
       END DO
-      !!
-      CALL wrk_dealloc( jpi,jpj, dU10, dT, dq, Cd_n10, Ce_n10, Ch_n10, sqrt_Cd_n10, sqrt_Cd, L )
-      CALL wrk_dealloc( jpi,jpj, T_vpot, T_star, q_star, U_star, zeta_u, zeta_t, U_n10 )
-      CALL wrk_dealloc( jpi,jpj, xlogt, xct, zpsi_hu, zpsi_ht, zpsi_m )
-      CALL wrk_dealloc( jpi,jpj, stab )   ! interger
-      !
-      IF( nn_timing == 1 )  CALL timing_stop('TURB_CORE_2Z')
-      !
-    END SUBROUTINE TURB_CORE_2Z
-
-
-    FUNCTION psi_m(zta)   !! Psis, L & Y eq. (8c), (8d), (8e)
+
+      CALL wrk_dealloc( jpi,jpj, U_zu, Ce_n10, Ch_n10, sqrt_Cd_n10, sqrt_Cd )
+      CALL wrk_dealloc( jpi,jpj, zeta_u, stab )
+      CALL wrk_dealloc( jpi,jpj, zpsi_h_u, zpsi_m_u, ztmp0, ztmp1, ztmp2 )
+
+      IF( .NOT. l_zt_equal_zu ) CALL wrk_dealloc( jpi,jpj, zeta_t )
+
+      IF( nn_timing == 1 )  CALL timing_stop('turb_core_2z')
+      !
+   END SUBROUTINE turb_core_2z
+
+
+   FUNCTION cd_neutral_10m( zw10 )
+      !!----------------------------------------------------------------------
+      !! Estimate of the neutral drag coefficient at 10m as a function 
+      !! of neutral wind  speed at 10m
+      !!
+      !! Origin: Large & Yeager 2008 eq.(11a) and eq.(11b)
+      !!
+      !! Author: L. Brodeau, june 2014
+      !!----------------------------------------------------------------------    
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   zw10           ! scalar wind speed at 10m (m/s)
+      REAL(wp), DIMENSION(jpi,jpj)             ::   cd_neutral_10m
+      !
+      REAL(wp), DIMENSION(:,:), POINTER ::   rgt33
+      !!----------------------------------------------------------------------    
+      !
+      CALL wrk_alloc( jpi,jpj, rgt33 )
+      !
+      !! When wind speed > 33 m/s => Cyclone conditions => special treatment
+      rgt33 = 0.5_wp + SIGN( 0.5_wp, (zw10 - 33._wp) )   ! If zw10 < 33. => 0, else => 1  
+      cd_neutral_10m = 1.e-3 * ( &
+         &       (1._wp - rgt33)*( 2.7_wp/zw10 + 0.142_wp + zw10/13.09_wp - 3.14807E-10*zw10**6) & ! zw10< 33.
+         &      + rgt33         *      2.34   )                                                    ! zw10 >= 33.
+      !
+      CALL wrk_dealloc( jpi,jpj, rgt33)
+      !
+   END FUNCTION cd_neutral_10m
+
+
+   FUNCTION psi_m(pta)   !! Psis, L&Y 2004 eq. (8c), (8d), (8e)
       !-------------------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: zta
-
-      REAL(wp), PARAMETER :: pi = 3.141592653589793_wp
+      ! universal profile stability function for momentum
+      !-------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) :: pta
+      !
       REAL(wp), DIMENSION(jpi,jpj)             :: psi_m
       REAL(wp), DIMENSION(:,:), POINTER        :: X2, X, stabit
       !-------------------------------------------------------------------------------
-
+      !
       CALL wrk_alloc( jpi,jpj, X2, X, stabit )
-
-      X2 = sqrt(abs(1. - 16.*zta))  ;  X2 = max(X2 , 1.0) ;  X  = sqrt(X2)
-      stabit    = 0.5 + sign(0.5,zta)
-      psi_m = -5.*zta*stabit  &                                                          ! Stable
-         &    + (1. - stabit)*(2*log((1. + X)/2) + log((1. + X2)/2) - 2*atan(X) + pi/2)  ! Unstable 
-
+      !
+      X2 = SQRT( ABS( 1. - 16.*pta ) )  ;  X2 = MAX( X2 , 1. )   ;   X = SQRT( X2 )
+      stabit = 0.5 + SIGN( 0.5 , pta )
+      psi_m = -5.*pta*stabit  &                                                          ! Stable
+         &    + (1. - stabit)*(2.*LOG((1. + X)*0.5) + LOG((1. + X2)*0.5) - 2.*ATAN(X) + rpi*0.5)  ! Unstable
+      !
       CALL wrk_dealloc( jpi,jpj, X2, X, stabit )
       !
-    END FUNCTION psi_m
-
-
-    FUNCTION psi_h( zta )    !! Psis, L & Y eq. (8c), (8d), (8e)
+   END FUNCTION psi_m
+
+
+   FUNCTION psi_h( pta )    !! Psis, L&Y 2004 eq. (8c), (8d), (8e)
       !-------------------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   zta
+      ! universal profile stability function for temperature and humidity
+      !-------------------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in) ::   pta
       !
       REAL(wp), DIMENSION(jpi,jpj)             ::   psi_h
-      REAL(wp), DIMENSION(:,:), POINTER        :: X2, X, stabit
+      REAL(wp), DIMENSION(:,:), POINTER        ::   X2, X, stabit
       !-------------------------------------------------------------------------------
-
+      !
       CALL wrk_alloc( jpi,jpj, X2, X, stabit )
-
-      X2 = sqrt(abs(1. - 16.*zta))  ;  X2 = max(X2 , 1.) ;  X  = sqrt(X2)
-      stabit    = 0.5 + sign(0.5,zta)
-      psi_h = -5.*zta*stabit  &                                       ! Stable
-         &    + (1. - stabit)*(2.*log( (1. + X2)/2. ))                 ! Unstable
-
+      !
+      X2 = SQRT( ABS( 1. - 16.*pta ) )   ;   X2 = MAX( X2 , 1. )   ;   X = SQRT( X2 )
+      stabit = 0.5 + SIGN( 0.5 , pta )
+      psi_h = -5.*pta*stabit   &                                       ! Stable
+         &    + (1. - stabit)*(2.*LOG( (1. + X2)*0.5 ))                ! Unstable
+      !
       CALL wrk_dealloc( jpi,jpj, X2, X, stabit )
       !
-    END FUNCTION psi_h
-  
+   END FUNCTION psi_h
+
    !!======================================================================
 END MODULE sbcblk_core
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_mfs.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_mfs.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcblk_mfs.F90	(revision 5075)
@@ -82,5 +82,5 @@
       !!              - utau, vtau  i- and j-component of the wind stress
       !!              - taum        wind stress module at T-point
-      !!              - wndm        10m wind module at T-point
+      !!              - wndm        10m wind module at T-point over free ocean or leads in presence of sea-ice
       !!              - qns, qsr    non-slor and solar heat flux
       !!              - emp         evaporation minus precipitation
@@ -233,11 +233,14 @@
          ! Interpolate utau, vtau into the grid_V and grid_V
          !-------------------------------------------------
-
+      !     Note the use of 0.5*(2-umask) in order to unmask the stress along coastlines
+      !     Note the use of MAX(tmask(i,j),tmask(i+1,j) is to mask tau over ice shelves
          DO jj = 1, jpjm1
             DO ji = 1, fs_jpim1
                utau(ji,jj) = 0.5 * ( 2. - umask(ji,jj,1) ) * ( utau(ji,jj) * tmask(ji,jj,1) &
-               &                                + utau(ji+1,jj) * tmask(ji+1,jj,1) )
+               &                                + utau(ji+1,jj) * tmask(ji+1,jj,1) )        &
+               &                 * MAX(tmask(ji,jj,1),tmask(ji+1,jj  ,1))
                vtau(ji,jj) = 0.5 * ( 2. - vmask(ji,jj,1) ) * ( vtau(ji,jj) * tmask(ji,jj,1) &
-               &                                + vtau(ji,jj+1) * tmask(ji,jj+1,1) )
+               &                                + vtau(ji,jj+1) * tmask(ji,jj+1,1) )        &
+               &                 * MAX(tmask(ji,jj,1),tmask(ji  ,jj+1,1))
             END DO
          END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbccpl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbccpl.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbccpl.F90	(revision 5075)
@@ -9,7 +9,4 @@
    !!            3.4  ! 2011_11  (C. Harris) more flexibility + multi-category fields
    !!----------------------------------------------------------------------
-#if defined key_oasis3 || defined key_oasis4
-   !!----------------------------------------------------------------------
-   !!   'key_oasis3' or 'key_oasis4'   Coupled Ocean/Atmosphere formulation
    !!----------------------------------------------------------------------
    !!   namsbc_cpl      : coupled formulation namlist
@@ -34,10 +31,5 @@
    USE ice_2           ! ice variables
 #endif
-#if defined key_oasis3
    USE cpl_oasis3      ! OASIS3 coupling
-#endif
-#if defined key_oasis4
-   USE cpl_oasis4      ! OASIS4 coupling
-#endif
    USE geo2ocean       ! 
    USE oce   , ONLY : tsn, un, vn
@@ -52,5 +44,4 @@
    USE p4zflx, ONLY : oce_co2
 #endif
-   USE diaar5, ONLY :   lk_diaar5
 #if defined key_cice
    USE ice_domain_size, only: ncat
@@ -58,9 +49,11 @@
    IMPLICIT NONE
    PRIVATE
-
+!EM XIOS-OASIS-MCT compliance
+   PUBLIC   sbc_cpl_init       ! routine called by sbcmod.F90
    PUBLIC   sbc_cpl_rcv        ! routine called by sbc_ice_lim(_2).F90
    PUBLIC   sbc_cpl_snd        ! routine called by step.F90
    PUBLIC   sbc_cpl_ice_tau    ! routine called by sbc_ice_lim(_2).F90
    PUBLIC   sbc_cpl_ice_flx    ! routine called by sbc_ice_lim(_2).F90
+   PUBLIC   sbc_cpl_alloc      ! routine called in sbcice_cice.F90
 
    INTEGER, PARAMETER ::   jpr_otx1   =  1            ! 3 atmosphere-ocean stress components on grid 1
@@ -129,4 +122,10 @@
    TYPE(FLD_C) ::   sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau, sn_rcv_dqnsdt, sn_rcv_qsr, sn_rcv_qns, sn_rcv_emp, sn_rcv_rnf
    TYPE(FLD_C) ::   sn_rcv_cal, sn_rcv_iceflx, sn_rcv_co2                        
+   ! Other namelist parameters                        !
+   INTEGER     ::   nn_cplmodel            ! Maximum number of models to/from which NEMO is potentialy sending/receiving data
+   LOGICAL     ::   ln_usecplmask          !  use a coupling mask file to merge data received from several models
+                                           !   -> file cplmask.nc with the float variable called cplmask (jpi,jpj,nn_cplmodel)
+
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) :: xcplmask
 
    TYPE ::   DYNARR     
@@ -139,29 +138,4 @@
 
    INTEGER , ALLOCATABLE, SAVE, DIMENSION(    :) ::   nrcvinfo           ! OASIS info argument
-
-#if ! defined key_lim2   &&   ! defined key_lim3
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   u_ice, v_ice,fr1_i0,fr2_i0          ! jpi, jpj
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   tn_ice, alb_ice, qns_ice, dqns_ice  ! (jpi,jpj,jpl)
-#endif
-
-#if defined key_cice
-   INTEGER, PARAMETER ::   jpl = ncat
-#elif ! defined key_lim2   &&   ! defined key_lim3
-   INTEGER, PARAMETER ::   jpl = 1 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   emp_ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   qsr_ice
-#endif
-
-#if ! defined key_lim3   &&  ! defined key_cice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  a_i
-#endif
-
-#if ! defined key_lim3
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  ht_i, ht_s
-#endif
-
-#if ! defined key_cice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  topmelt, botmelt
-#endif
 
    !! Substitution
@@ -179,24 +153,15 @@
       !!             ***  FUNCTION sbc_cpl_alloc  ***
       !!----------------------------------------------------------------------
-      INTEGER :: ierr(4),jn
+      INTEGER :: ierr(3)
       !!----------------------------------------------------------------------
       ierr(:) = 0
       !
       ALLOCATE( albedo_oce_mix(jpi,jpj), nrcvinfo(jprcv),  STAT=ierr(1) )
-      !
-#if ! defined key_lim2 && ! defined key_lim3
-      ! quick patch to be able to run the coupled model without sea-ice...
-      ALLOCATE( u_ice(jpi,jpj) , fr1_i0(jpi,jpj) , tn_ice (jpi,jpj,1) ,     &
-                v_ice(jpi,jpj) , fr2_i0(jpi,jpj) , alb_ice(jpi,jpj,1),      &
-                emp_ice(jpi,jpj) , qns_ice(jpi,jpj,1) , dqns_ice(jpi,jpj,1) , STAT=ierr(2) )
+      
+#if ! defined key_lim3 && ! defined key_lim2 && ! defined key_cice
+      ALLOCATE( a_i(jpi,jpj,1) , STAT=ierr(2) )  ! used in sbcice_if.F90 (done here as there is no sbc_ice_if_init)
 #endif
-
-#if ! defined key_lim3 && ! defined key_cice
-      ALLOCATE( a_i(jpi,jpj,jpl) , STAT=ierr(3) )
-#endif
-
-#if defined key_cice || defined key_lim2
-      ALLOCATE( ht_i(jpi,jpj,jpl) , ht_s(jpi,jpj,jpl) , STAT=ierr(4) )
-#endif
+      ALLOCATE( xcplmask(jpi,jpj,nn_cplmodel) , STAT=ierr(3) )
+      !
       sbc_cpl_alloc = MAXVAL( ierr )
       IF( lk_mpp            )   CALL mpp_sum ( sbc_cpl_alloc )
@@ -210,5 +175,5 @@
       !!             ***  ROUTINE sbc_cpl_init  ***
       !!
-      !! ** Purpose :   Initialisation of send and recieved information from
+      !! ** Purpose :   Initialisation of send and received information from
       !!                the atmospheric component
       !!
@@ -222,9 +187,11 @@
       INTEGER ::   jn   ! dummy loop index
       INTEGER ::   ios  ! Local integer output status for namelist read
+      INTEGER ::   inum 
       REAL(wp), POINTER, DIMENSION(:,:) ::   zacs, zaos
       !!
-      NAMELIST/namsbc_cpl/  sn_snd_temp, sn_snd_alb   , sn_snd_thick, sn_snd_crt   , sn_snd_co2,   &
-         &                  sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau  , sn_rcv_dqnsdt, sn_rcv_qsr,   &
-         &                  sn_rcv_qns , sn_rcv_emp   , sn_rcv_rnf  , sn_rcv_cal   , sn_rcv_iceflx  , sn_rcv_co2
+      NAMELIST/namsbc_cpl/  sn_snd_temp, sn_snd_alb   , sn_snd_thick, sn_snd_crt   , sn_snd_co2,      &
+         &                  sn_rcv_w10m, sn_rcv_taumod, sn_rcv_tau  , sn_rcv_dqnsdt, sn_rcv_qsr,      &
+         &                  sn_rcv_qns , sn_rcv_emp   , sn_rcv_rnf  , sn_rcv_cal   , sn_rcv_iceflx,   &
+         &                  sn_rcv_co2 , nn_cplmodel  , ln_usecplmask
       !!---------------------------------------------------------------------
       !
@@ -274,4 +241,6 @@
          WRITE(numout,*)'                      - mesh          = ', sn_snd_crt%clvgrd
          WRITE(numout,*)'      oce co2 flux                    = ', TRIM(sn_snd_co2%cldes   ), ' (', TRIM(sn_snd_co2%clcat   ), ')'
+         WRITE(numout,*)'  nn_cplmodel                         = ', nn_cplmodel
+         WRITE(numout,*)'  ln_usecplmask                       = ', ln_usecplmask
       ENDIF
 
@@ -485,9 +454,9 @@
       END DO
       ! Allocate taum part of frcv which is used even when not received as coupling field
-      IF ( .NOT. srcv(jpr_taum)%laction ) ALLOCATE( frcv(jpr_taum)%z3(jpi,jpj,srcv(jn)%nct) )
+      IF ( .NOT. srcv(jpr_taum)%laction ) ALLOCATE( frcv(jpr_taum)%z3(jpi,jpj,srcv(jpr_taum)%nct) )
       ! Allocate itx1 and ity1 as they are used in sbc_cpl_ice_tau even if srcv(jpr_itx1)%laction = .FALSE.
       IF( k_ice /= 0 ) THEN
-         IF ( .NOT. srcv(jpr_itx1)%laction ) ALLOCATE( frcv(jpr_itx1)%z3(jpi,jpj,srcv(jn)%nct) )
-         IF ( .NOT. srcv(jpr_ity1)%laction ) ALLOCATE( frcv(jpr_ity1)%z3(jpi,jpj,srcv(jn)%nct) )
+         IF ( .NOT. srcv(jpr_itx1)%laction ) ALLOCATE( frcv(jpr_itx1)%z3(jpi,jpj,srcv(jpr_itx1)%nct) )
+         IF ( .NOT. srcv(jpr_ity1)%laction ) ALLOCATE( frcv(jpr_ity1)%z3(jpi,jpj,srcv(jpr_ity1)%nct) )
       END IF
 
@@ -604,7 +573,16 @@
       ! ================================ !
 
-      CALL cpl_prism_define(jprcv, jpsnd)            
-      !
-      IF( ln_dm2dc .AND. ( cpl_prism_freq( jpr_qsroce ) + cpl_prism_freq( jpr_qsrmix ) /= 86400 ) )   &
+      CALL cpl_define(jprcv, jpsnd,nn_cplmodel)            
+      IF (ln_usecplmask) THEN 
+         xcplmask(:,:,:) = 0.
+         CALL iom_open( 'cplmask', inum )
+         CALL iom_get( inum, jpdom_unknown, 'cplmask', xcplmask(1:nlci,1:nlcj,1:nn_cplmodel),   &
+            &          kstart = (/ mig(1),mjg(1),1 /), kcount = (/ nlci,nlcj,nn_cplmodel /) )
+         CALL iom_close( inum )
+      ELSE
+         xcplmask(:,:,:) = 1.
+      ENDIF
+      !
+      IF( ln_dm2dc .AND. ( cpl_freq( jpr_qsroce ) + cpl_freq( jpr_qsrmix ) /= 86400 ) )   &
          &   CALL ctl_stop( 'sbc_cpl_init: diurnal cycle reconstruction (ln_dm2dc) needs daily couping for solar radiation' )
 
@@ -654,5 +632,6 @@
       !!
       !! ** Action  :   update  utau, vtau   ocean stress at U,V grid 
-      !!                        taum, wndm   wind stres and wind speed module at T-point
+      !!                        taum         wind stress module at T-point
+      !!                        wndm         wind speed  module at T-point over free ocean or leads in presence of sea-ice
       !!                        qns          non solar heat fluxes including emp heat content    (ocean only case)
       !!                                     and the latent heat flux of solid precip. melting
@@ -678,11 +657,8 @@
       !
       CALL wrk_alloc( jpi,jpj, ztx, zty )
-
-      IF( kt == nit000 )   CALL sbc_cpl_init( k_ice )          ! initialisation
-
       !                                                 ! Receive all the atmos. fields (including ice information)
       isec = ( kt - nit000 ) * NINT( rdttra(1) )             ! date of exchanges
       DO jn = 1, jprcv                                       ! received fields sent by the atmosphere
-         IF( srcv(jn)%laction )   CALL cpl_prism_rcv( jn, isec, frcv(jn)%z3, nrcvinfo(jn) )
+         IF( srcv(jn)%laction )   CALL cpl_rcv( jn, isec, frcv(jn)%z3, xcplmask, nrcvinfo(jn) )
       END DO
 
@@ -848,8 +824,8 @@
          IF( srcv(jpr_qnsoce)%laction )   qns(:,:) = frcv(jpr_qnsoce)%z3(:,:,1)
          IF( srcv(jpr_qnsmix)%laction )   qns(:,:) = frcv(jpr_qnsmix)%z3(:,:,1)
-         ! add the latent heat of solid precip. melting
-         IF( srcv(jpr_snow  )%laction )   THEN                         ! update qns over the free ocean with:
-              qns(:,:) = qns(:,:) - frcv(jpr_snow)%z3(:,:,1) * lfus  & ! energy for melting solid precipitation over the free ocean
-           &           - emp(:,:) * sst_m(:,:) * rcp                   ! remove heat content due to mass flux (assumed to be at SST)
+         ! update qns over the free ocean with:
+         qns(:,:) =  qns(:,:) - emp(:,:) * sst_m(:,:) * rcp            ! remove heat content due to mass flux (assumed to be at SST)
+         IF( srcv(jpr_snow  )%laction )   THEN
+              qns(:,:) = qns(:,:) - frcv(jpr_snow)%z3(:,:,1) * lfus    ! energy for melting solid precipitation over the free ocean
          ENDIF
 
@@ -914,6 +890,5 @@
       CALL wrk_alloc( jpi,jpj, ztx, zty )
 
-!AC Pour eviter un stress nul sur la glace dans le cas mixed oce-ice
-      IF( srcv(jpr_itx1)%laction .AND. TRIM( sn_rcv_tau%cldes ) == 'oce and ice') THEN   ;   itx =  jpr_itx1   
+      IF( srcv(jpr_itx1)%laction ) THEN   ;   itx =  jpr_itx1   
       ELSE                                ;   itx =  jpr_otx1
       ENDIF
@@ -922,8 +897,7 @@
       IF(  nrcvinfo(itx) == OASIS_Rcv ) THEN
 
-         !                                                                                              ! ======================= !
-!AC Pour eviter un stress nul sur la glace dans le cas mixes oce-ice
-         IF( srcv(jpr_itx1)%laction .AND. TRIM( sn_rcv_tau%cldes ) == 'oce and ice') THEN               !   ice stress received   !
-            !                                                                                           ! ======================= !
+         !                                                      ! ======================= !
+         IF( srcv(jpr_itx1)%laction ) THEN                      !   ice stress received   !
+            !                                                   ! ======================= !
             !  
             IF( TRIM( sn_rcv_tau%clvref ) == 'cartesian' ) THEN            ! 2 components on the sphere
@@ -1125,6 +1099,6 @@
       REAL(wp), INTENT(in   ), DIMENSION(:,:)   ::   p_frld     ! lead fraction                [0 to 1]
       ! optional arguments, used only in 'mixed oce-ice' case
-      REAL(wp), INTENT(in   ), DIMENSION(:,:,:), OPTIONAL ::   palbi   ! ice albedo 
-      REAL(wp), INTENT(in   ), DIMENSION(:,:  ), OPTIONAL ::   psst    ! sea surface temperature     [Celcius]
+      REAL(wp), INTENT(in   ), DIMENSION(:,:,:), OPTIONAL ::   palbi   ! all skies ice albedo 
+      REAL(wp), INTENT(in   ), DIMENSION(:,:  ), OPTIONAL ::   psst    ! sea surface temperature     [Celsius]
       REAL(wp), INTENT(in   ), DIMENSION(:,:,:), OPTIONAL ::   pist    ! ice surface temperature     [Kelvin]
       !
@@ -1153,9 +1127,13 @@
          emp_tot(:,:) = frcv(jpr_tevp)%z3(:,:,1) - tprecip(:,:)
          emp_ice(:,:) = frcv(jpr_ievp)%z3(:,:,1) - frcv(jpr_snow)%z3(:,:,1)
-                           CALL iom_put( 'rain'         , frcv(jpr_rain)%z3(:,:,1)              )   ! liquid precipitation 
-         IF( lk_diaar5 )   CALL iom_put( 'hflx_rain_cea', frcv(jpr_rain)%z3(:,:,1) * zcptn(:,:) )   ! heat flux from liq. precip. 
-         ztmp(:,:) = frcv(jpr_tevp)%z3(:,:,1) - frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:)
-                           CALL iom_put( 'evap_ao_cea'  , ztmp                            )   ! ice-free oce evap (cell average)
-         IF( lk_diaar5 )   CALL iom_put( 'hflx_evap_cea', ztmp(:,:         ) * zcptn(:,:) )   ! heat flux from from evap (cell ave)
+            CALL iom_put( 'rain'         , frcv(jpr_rain)%z3(:,:,1)              )   ! liquid precipitation 
+         IF( iom_use('hflx_rain_cea') )   &
+            CALL iom_put( 'hflx_rain_cea', frcv(jpr_rain)%z3(:,:,1) * zcptn(:,:) )   ! heat flux from liq. precip. 
+         IF( iom_use('evap_ao_cea') .OR. iom_use('hflx_evap_cea') )   &
+            ztmp(:,:) = frcv(jpr_tevp)%z3(:,:,1) - frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:)
+         IF( iom_use('evap_ao_cea'  ) )   &
+            CALL iom_put( 'evap_ao_cea'  , ztmp                   )   ! ice-free oce evap (cell average)
+         IF( iom_use('hflx_evap_cea') )   &
+            CALL iom_put( 'hflx_evap_cea', ztmp(:,:) * zcptn(:,:) )   ! heat flux from from evap (cell average)
       CASE( 'oce and ice'   )   ! received fields: jpr_sbpr, jpr_semp, jpr_oemp, jpr_ievp
          emp_tot(:,:) = p_frld(:,:) * frcv(jpr_oemp)%z3(:,:,1) + zicefr(:,:) * frcv(jpr_sbpr)%z3(:,:,1)
@@ -1164,14 +1142,18 @@
       END SELECT
 
-      CALL iom_put( 'snowpre'    , sprecip                                )   ! Snow
-      CALL iom_put( 'snow_ao_cea', sprecip(:,:         ) * p_frld(:,:)    )   ! Snow        over ice-free ocean  (cell average)
-      CALL iom_put( 'snow_ai_cea', sprecip(:,:         ) * zicefr(:,:)    )   ! Snow        over sea-ice         (cell average)
-      CALL iom_put( 'subl_ai_cea', frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:) )   ! Sublimation over sea-ice         (cell average)
+         CALL iom_put( 'snowpre'    , sprecip                                )   ! Snow
+      IF( iom_use('snow_ao_cea') )   &
+         CALL iom_put( 'snow_ao_cea', sprecip(:,:) * p_frld(:,:)             )   ! Snow        over ice-free ocean  (cell average)
+      IF( iom_use('snow_ai_cea') )   &
+         CALL iom_put( 'snow_ai_cea', sprecip(:,:) * zicefr(:,:)             )   ! Snow        over sea-ice         (cell average)
+      IF( iom_use('subl_ai_cea') )   &
+         CALL iom_put( 'subl_ai_cea', frcv(jpr_ievp)%z3(:,:,1) * zicefr(:,:) )   ! Sublimation over sea-ice         (cell average)
       !   
       !                                                           ! runoffs and calving (put in emp_tot)
       IF( srcv(jpr_rnf)%laction ) THEN 
          emp_tot(:,:) = emp_tot(:,:) - frcv(jpr_rnf)%z3(:,:,1)
-                           CALL iom_put( 'runoffs'      , frcv(jpr_rnf)%z3(:,:,1)              )   ! rivers
-         IF( lk_diaar5 )   CALL iom_put( 'hflx_rnf_cea' , frcv(jpr_rnf)%z3(:,:,1) * zcptn(:,:) )   ! heat flux from rivers
+            CALL iom_put( 'runoffs'      , frcv(jpr_rnf)%z3(:,:,1)              )   ! rivers
+         IF( iom_use('hflx_rnf_cea') )   &
+            CALL iom_put( 'hflx_rnf_cea' , frcv(jpr_rnf)%z3(:,:,1) * zcptn(:,:) )   ! heat flux from rivers
       ENDIF
       IF( srcv(jpr_cal)%laction ) THEN 
@@ -1235,5 +1217,6 @@
          &          - (  emp_tot(:,:)                     &            ! remove the heat content of mass flux (assumed to be at SST)
          &             - emp_ice(:,:) * zicefr(:,:)  ) * zcptn(:,:) 
-      IF( lk_diaar5 )   CALL iom_put( 'hflx_snow_cea', ztmp + sprecip(:,:) * zcptn(:,:) )   ! heat flux from snow (cell average)
+      IF( iom_use('hflx_snow_cea') )   &
+         CALL iom_put( 'hflx_snow_cea', ztmp + sprecip(:,:) * zcptn(:,:) )   ! heat flux from snow (cell average)
 !!gm
 !!    currently it is taken into account in leads budget but not in the qns_tot, and thus not in 
@@ -1247,5 +1230,6 @@
          ztmp(:,:) = frcv(jpr_cal)%z3(:,:,1) * lfus               ! add the latent heat of iceberg melting 
          qns_tot(:,:) = qns_tot(:,:) - ztmp(:,:)
-         IF( lk_diaar5 )   CALL iom_put( 'hflx_cal_cea', ztmp + frcv(jpr_cal)%z3(:,:,1) * zcptn(:,:) )   ! heat flux from calving
+         IF( iom_use('hflx_cal_cea') )   &
+            CALL iom_put( 'hflx_cal_cea', ztmp + frcv(jpr_cal)%z3(:,:,1) * zcptn(:,:) )   ! heat flux from calving
       ENDIF
 
@@ -1296,5 +1280,7 @@
       ENDIF
 
-      SELECT CASE( TRIM( sn_rcv_dqnsdt%cldes ) )
+      !                                                      ! ========================= !
+      SELECT CASE( TRIM( sn_rcv_dqnsdt%cldes ) )             !          d(qns)/dt        !
+      !                                                      ! ========================= !
       CASE ('coupled')
          IF ( TRIM(sn_rcv_dqnsdt%clcat) == 'yes' ) THEN
@@ -1308,5 +1294,7 @@
       END SELECT
 
-      SELECT CASE( TRIM( sn_rcv_iceflx%cldes ) )
+      !                                                      ! ========================= !
+      SELECT CASE( TRIM( sn_rcv_iceflx%cldes ) )             !    topmelt and botmelt    !
+      !                                                      ! ========================= !
       CASE ('coupled')
          topmelt(:,:,:)=frcv(jpr_topm)%z3(:,:,:)
@@ -1314,12 +1302,10 @@
       END SELECT
 
-      !    Ice Qsr penetration used (only?)in lim2 or lim3 
-      ! fraction of net shortwave radiation which is not absorbed in the thin surface layer 
-      ! and penetrates inside the ice cover ( Maykut and Untersteiner, 1971 ; Elbert anbd Curry, 1993 )
+      ! Surface transimission parameter io (Maykut Untersteiner , 1971 ; Ebert and Curry, 1993 )
+      ! Used for LIM2 and LIM3
       ! Coupled case: since cloud cover is not received from atmosphere 
-      !               ===> defined as constant value -> definition done in sbc_cpl_init
-      fr1_i0(:,:) = 0.18
-      fr2_i0(:,:) = 0.82
-
+      !               ===> used prescribed cloud fraction representative for polar oceans in summer (0.81)
+      fr1_i0(:,:) = ( 0.18 * ( 1.0 - cldf_ice ) + 0.35 * cldf_ice )
+      fr2_i0(:,:) = ( 0.82 * ( 1.0 - cldf_ice ) + 0.65 * cldf_ice )
 
       CALL wrk_dealloc( jpi,jpj, zcptn, ztmp, zicefr )
@@ -1336,5 +1322,5 @@
       !! ** Purpose :   provide the ocean-ice informations to the atmosphere
       !!
-      !! ** Method  :   send to the atmosphere through a call to cpl_prism_snd
+      !! ** Method  :   send to the atmosphere through a call to cpl_snd
       !!              all the needed fields (as defined in sbc_cpl_init)
       !!----------------------------------------------------------------------
@@ -1355,5 +1341,4 @@
 
       zfr_l(:,:) = 1.- fr_i(:,:)
-
       !                                                      ! ------------------------- !
       !                                                      !    Surface temperature    !   in Kelvin
@@ -1374,5 +1359,5 @@
             END SELECT
          CASE( 'mixed oce-ice'        )   
-            ztmp1(:,:) = ( tsn(:,:,1,1) + rt0 ) * zfr_l(:,:) 
+            ztmp1(:,:) = ( tsn(:,:,1,jp_tem) + rt0 ) * zfr_l(:,:) 
             DO jl=1,jpl
                ztmp1(:,:) = ztmp1(:,:) + tn_ice(:,:,jl) * a_i(:,:,jl)
@@ -1380,9 +1365,8 @@
          CASE default                     ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_temp%cldes' )
          END SELECT
-         IF( ssnd(jps_toce)%laction )   CALL cpl_prism_snd( jps_toce, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info )
-         IF( ssnd(jps_tice)%laction )   CALL cpl_prism_snd( jps_tice, isec, ztmp3, info )
-         IF( ssnd(jps_tmix)%laction )   CALL cpl_prism_snd( jps_tmix, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info )
-      ENDIF
-      !
+         IF( ssnd(jps_toce)%laction )   CALL cpl_snd( jps_toce, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info )
+         IF( ssnd(jps_tice)%laction )   CALL cpl_snd( jps_tice, isec, ztmp3, info )
+         IF( ssnd(jps_tmix)%laction )   CALL cpl_snd( jps_tmix, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info )
+      ENDIF
       !                                                      ! ------------------------- !
       !                                                      !           Albedo          !
@@ -1390,5 +1374,5 @@
       IF( ssnd(jps_albice)%laction ) THEN                         ! ice 
          ztmp3(:,:,1:jpl) = alb_ice(:,:,1:jpl) * a_i(:,:,1:jpl)
-         CALL cpl_prism_snd( jps_albice, isec, ztmp3, info )
+         CALL cpl_snd( jps_albice, isec, ztmp3, info )
       ENDIF
       IF( ssnd(jps_albmix)%laction ) THEN                         ! mixed ice-ocean
@@ -1397,5 +1381,5 @@
             ztmp1(:,:) = ztmp1(:,:) + alb_ice(:,:,jl) * a_i(:,:,jl)
          ENDDO
-         CALL cpl_prism_snd( jps_albmix, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info )
+         CALL cpl_snd( jps_albmix, isec, RESHAPE ( ztmp1, (/jpi,jpj,1/) ), info )
       ENDIF
       !                                                      ! ------------------------- !
@@ -1409,5 +1393,5 @@
          CASE default    ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_thick%clcat' )
          END SELECT
-         CALL cpl_prism_snd( jps_fice, isec, ztmp3, info )
+         CALL cpl_snd( jps_fice, isec, ztmp3, info )
       ENDIF
 
@@ -1434,6 +1418,6 @@
          CASE default                     ;   CALL ctl_stop( 'sbc_cpl_snd: wrong definition of sn_snd_thick%cldes' )
          END SELECT
-         IF( ssnd(jps_hice)%laction )   CALL cpl_prism_snd( jps_hice, isec, ztmp3, info )
-         IF( ssnd(jps_hsnw)%laction )   CALL cpl_prism_snd( jps_hsnw, isec, ztmp4, info )
+         IF( ssnd(jps_hice)%laction )   CALL cpl_snd( jps_hice, isec, ztmp3, info )
+         IF( ssnd(jps_hsnw)%laction )   CALL cpl_snd( jps_hsnw, isec, ztmp4, info )
       ENDIF
       !
@@ -1442,5 +1426,5 @@
       !                                                      !  CO2 flux from PISCES     ! 
       !                                                      ! ------------------------- !
-      IF( ssnd(jps_co2)%laction )   CALL cpl_prism_snd( jps_co2, isec, RESHAPE ( oce_co2, (/jpi,jpj,1/) ) , info )
+      IF( ssnd(jps_co2)%laction )   CALL cpl_snd( jps_co2, isec, RESHAPE ( oce_co2, (/jpi,jpj,1/) ) , info )
       !
 #endif
@@ -1565,11 +1549,11 @@
          ENDIF
          !
-         IF( ssnd(jps_ocx1)%laction )   CALL cpl_prism_snd( jps_ocx1, isec, RESHAPE ( zotx1, (/jpi,jpj,1/) ), info )   ! ocean x current 1st grid
-         IF( ssnd(jps_ocy1)%laction )   CALL cpl_prism_snd( jps_ocy1, isec, RESHAPE ( zoty1, (/jpi,jpj,1/) ), info )   ! ocean y current 1st grid
-         IF( ssnd(jps_ocz1)%laction )   CALL cpl_prism_snd( jps_ocz1, isec, RESHAPE ( zotz1, (/jpi,jpj,1/) ), info )   ! ocean z current 1st grid
+         IF( ssnd(jps_ocx1)%laction )   CALL cpl_snd( jps_ocx1, isec, RESHAPE ( zotx1, (/jpi,jpj,1/) ), info )   ! ocean x current 1st grid
+         IF( ssnd(jps_ocy1)%laction )   CALL cpl_snd( jps_ocy1, isec, RESHAPE ( zoty1, (/jpi,jpj,1/) ), info )   ! ocean y current 1st grid
+         IF( ssnd(jps_ocz1)%laction )   CALL cpl_snd( jps_ocz1, isec, RESHAPE ( zotz1, (/jpi,jpj,1/) ), info )   ! ocean z current 1st grid
          !
-         IF( ssnd(jps_ivx1)%laction )   CALL cpl_prism_snd( jps_ivx1, isec, RESHAPE ( zitx1, (/jpi,jpj,1/) ), info )   ! ice   x current 1st grid
-         IF( ssnd(jps_ivy1)%laction )   CALL cpl_prism_snd( jps_ivy1, isec, RESHAPE ( zity1, (/jpi,jpj,1/) ), info )   ! ice   y current 1st grid
-         IF( ssnd(jps_ivz1)%laction )   CALL cpl_prism_snd( jps_ivz1, isec, RESHAPE ( zitz1, (/jpi,jpj,1/) ), info )   ! ice   z current 1st grid
+         IF( ssnd(jps_ivx1)%laction )   CALL cpl_snd( jps_ivx1, isec, RESHAPE ( zitx1, (/jpi,jpj,1/) ), info )   ! ice   x current 1st grid
+         IF( ssnd(jps_ivy1)%laction )   CALL cpl_snd( jps_ivy1, isec, RESHAPE ( zity1, (/jpi,jpj,1/) ), info )   ! ice   y current 1st grid
+         IF( ssnd(jps_ivz1)%laction )   CALL cpl_snd( jps_ivz1, isec, RESHAPE ( zitz1, (/jpi,jpj,1/) ), info )   ! ice   z current 1st grid
          ! 
       ENDIF
@@ -1582,35 +1566,4 @@
    END SUBROUTINE sbc_cpl_snd
    
-#else
-   !!----------------------------------------------------------------------
-   !!   Dummy module                                            NO coupling
-   !!----------------------------------------------------------------------
-   USE par_kind        ! kind definition
-CONTAINS
-   SUBROUTINE sbc_cpl_snd( kt )
-      WRITE(*,*) 'sbc_cpl_snd: You should not have seen this print! error?', kt
-   END SUBROUTINE sbc_cpl_snd
-   !
-   SUBROUTINE sbc_cpl_rcv( kt, k_fsbc, k_ice )     
-      WRITE(*,*) 'sbc_cpl_snd: You should not have seen this print! error?', kt, k_fsbc, k_ice
-   END SUBROUTINE sbc_cpl_rcv
-   !
-   SUBROUTINE sbc_cpl_ice_tau( p_taui, p_tauj )     
-      REAL(wp), INTENT(out), DIMENSION(:,:) ::   p_taui   ! i- & j-components of atmos-ice stress [N/m2]
-      REAL(wp), INTENT(out), DIMENSION(:,:) ::   p_tauj   ! at I-point (B-grid) or U & V-point (C-grid)
-      p_taui(:,:) = 0.   ;   p_tauj(:,:) = 0. ! stupid definition to avoid warning message when compiling...
-      WRITE(*,*) 'sbc_cpl_snd: You should not have seen this print! error?'
-   END SUBROUTINE sbc_cpl_ice_tau
-   !
-   SUBROUTINE sbc_cpl_ice_flx( p_frld , palbi   , psst    , pist  )
-      REAL(wp), INTENT(in   ), DIMENSION(:,:  ) ::   p_frld     ! lead fraction                [0 to 1]
-      REAL(wp), INTENT(in   ), DIMENSION(:,:,:), OPTIONAL ::   palbi   ! ice albedo
-      REAL(wp), INTENT(in   ), DIMENSION(:,:  ), OPTIONAL ::   psst    ! sea surface temperature      [Celcius]
-      REAL(wp), INTENT(in   ), DIMENSION(:,:,:), OPTIONAL ::   pist    ! ice surface temperature      [Kelvin]
-      WRITE(*,*) 'sbc_cpl_snd: You should not have seen this print! error?', p_frld(1,1), palbi(1,1,1), psst(1,1), pist(1,1,1) 
-   END SUBROUTINE sbc_cpl_ice_flx
-   
-#endif
-
    !!======================================================================
 END MODULE sbccpl
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcflx.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcflx.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcflx.F90	(revision 5075)
@@ -156,4 +156,5 @@
             END DO
          END DO
+         taum(:,:) = taum(:,:) * tmask(:,:,1) ; wndm(:,:) = wndm(:,:) * tmask(:,:,1)
          CALL lbc_lnk( taum(:,:), 'T', 1. )   ;   CALL lbc_lnk( wndm(:,:), 'T', 1. )
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcfwb.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcfwb.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcfwb.F90	(revision 5075)
@@ -19,4 +19,5 @@
    USE phycst          ! physical constants
    USE sbcrnf          ! ocean runoffs
+   USE sbcisf          ! ice shelf melting contribution
    USE sbcssr          ! SS damping terms
    USE in_out_manager  ! I/O manager
@@ -57,4 +58,6 @@
       !!                =1 global mean of emp set to zero at each nn_fsbc time step
       !!                =2 annual global mean corrected from previous year
+      !!                =3 global mean of emp set to zero at each nn_fsbc time step
+      !!                   & spread out over erp area depending its sign
       !! Note: if sea ice is embedded it is taken into account when computing the budget 
       !!----------------------------------------------------------------------
@@ -81,9 +84,12 @@
             IF( kn_fwb == 1 )   WRITE(numout,*) '          instantaneously set to zero'
             IF( kn_fwb == 2 )   WRITE(numout,*) '          adjusted from previous year budget'
-         ENDIF
+            IF( kn_fwb == 3 )   WRITE(numout,*) '          fwf set to zero and spread out over erp area'
+         ENDIF
+         !
+         IF( kn_fwb == 3 .AND. nn_sssr /= 2 )   CALL ctl_stop( 'sbc_fwb: nn_fwb = 3 requires nn_sssr = 2, we stop ' )
          !
          area = glob_sum( e1e2t(:,:) )           ! interior global domain surface
          !
-#if ! defined key_lim2 &&  ! defined key_lim3 && ! defined key_cice 
+#if ! defined key_lim2 &&  ! defined key_lim3 && ! defined key_cice
          snwice_mass_b(:,:) = 0.e0               ! no sea-ice model is being used : no snow+ice mass
          snwice_mass  (:,:) = 0.e0
@@ -98,5 +104,5 @@
          !
          IF( MOD( kt-1, kn_fsbc ) == 0 ) THEN
-            z_fwf = glob_sum( e1e2t(:,:) * ( emp(:,:) - rnf(:,:) -  snwice_fmass(:,:) ) ) / area   ! sum over the global domain
+            z_fwf = glob_sum( e1e2t(:,:) * ( emp(:,:) - rnf(:,:) + rdivisf * fwfisf(:,:) -  snwice_fmass(:,:) ) ) / area   ! sum over the global domain
             zcoef = z_fwf * rcp
             emp(:,:) = emp(:,:) - z_fwf 
@@ -142,6 +148,58 @@
          ENDIF
          !
+      CASE ( 3 )                             !==  global fwf set to zero and spread out over erp area  ==!
+         !
+         IF( MOD( kt-1, kn_fsbc ) == 0 ) THEN
+            ztmsk_pos(:,:) = tmask_i(:,:)                      ! Select <0 and >0 area of erp
+            WHERE( erp < 0._wp )   ztmsk_pos = 0._wp
+            ztmsk_neg(:,:) = tmask_i(:,:) - ztmsk_pos(:,:)
+            !
+            zsurf_neg = glob_sum( e1e2t(:,:)*ztmsk_neg(:,:) )  ! Area filled by <0 and >0 erp 
+            zsurf_pos = glob_sum( e1e2t(:,:)*ztmsk_pos(:,:) )
+            !                                                  ! fwf global mean (excluding ocean to ice/snow exchanges) 
+            z_fwf     = glob_sum( e1e2t(:,:) * ( emp(:,:) - rnf(:,:) - snwice_fmass(:,:) ) ) / area
+            !            
+            IF( z_fwf < 0._wp ) THEN         ! spread out over >0 erp area to increase evaporation
+                zsurf_tospread      = zsurf_pos
+                ztmsk_tospread(:,:) = ztmsk_pos(:,:)
+            ELSE                             ! spread out over <0 erp area to increase precipitation
+                zsurf_tospread      = zsurf_neg
+                ztmsk_tospread(:,:) = ztmsk_neg(:,:)
+            ENDIF
+            !
+            zsum_fwf   = glob_sum( e1e2t(:,:) * z_fwf )         ! fwf global mean over <0 or >0 erp area
+!!gm :  zsum_fwf   = z_fwf * area   ???  it is right?  I think so....
+            z_fwf_nsrf =  zsum_fwf / ( zsurf_tospread + rsmall )
+            !                                                  ! weight to respect erp field 2D structure 
+            zsum_erp   = glob_sum( ztmsk_tospread(:,:) * erp(:,:) * e1e2t(:,:) )
+            z_wgt(:,:) = ztmsk_tospread(:,:) * erp(:,:) / ( zsum_erp + rsmall )
+            !                                                  ! final correction term to apply
+            zerp_cor(:,:) = -1. * z_fwf_nsrf * zsurf_tospread * z_wgt(:,:)
+            !
+!!gm   ===>>>>  lbc_lnk should be useless as all the computation is done over the whole domain !
+            CALL lbc_lnk( zerp_cor, 'T', 1. )
+            !
+            emp(:,:) = emp(:,:) + zerp_cor(:,:)
+            qns(:,:) = qns(:,:) - zerp_cor(:,:) * rcp * sst_m(:,:)  ! account for change to the heat budget due to fw correction
+            erp(:,:) = erp(:,:) + zerp_cor(:,:)
+            !
+            IF( nprint == 1 .AND. lwp ) THEN                   ! control print
+               IF( z_fwf < 0._wp ) THEN
+                  WRITE(numout,*)'   z_fwf < 0'
+                  WRITE(numout,*)'   SUM(erp+)     = ', SUM( ztmsk_tospread(:,:)*erp(:,:)*e1e2t(:,:) )*1.e-9,' Sv'
+               ELSE
+                  WRITE(numout,*)'   z_fwf >= 0'
+                  WRITE(numout,*)'   SUM(erp-)     = ', SUM( ztmsk_tospread(:,:)*erp(:,:)*e1e2t(:,:) )*1.e-9,' Sv'
+               ENDIF
+               WRITE(numout,*)'   SUM(empG)     = ', SUM( z_fwf*e1e2t(:,:) )*1.e-9,' Sv'
+               WRITE(numout,*)'   z_fwf         = ', z_fwf      ,' Kg/m2/s'
+               WRITE(numout,*)'   z_fwf_nsrf    = ', z_fwf_nsrf ,' Kg/m2/s'
+               WRITE(numout,*)'   MIN(zerp_cor) = ', MINVAL(zerp_cor) 
+               WRITE(numout,*)'   MAX(zerp_cor) = ', MAXVAL(zerp_cor) 
+            ENDIF
+         ENDIF
+         !
       CASE DEFAULT                           !==  you should never be there  ==!
-         CALL ctl_stop( 'sbc_fwb : wrong nn_fwb value for the FreshWater Budget correction, choose either 1 or 2' )
+         CALL ctl_stop( 'sbc_fwb : wrong nn_fwb value for the FreshWater Budget correction, choose either 1, 2 or 3' )
          !
       END SELECT
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_cice.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_cice.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_cice.F90	(revision 5075)
@@ -17,4 +17,5 @@
    USE phycst, only : rcp, rau0, r1_rau0, rhosn, rhoic
    USE in_out_manager  ! I/O manager
+   USE iom, ONLY : iom_put,iom_use              ! I/O manager library !!Joakim edit
    USE lib_mpp         ! distributed memory computing library
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
@@ -23,5 +24,4 @@
    USE daymod          ! calendar
    USE fldread         ! read input fields
-
    USE sbc_oce         ! Surface boundary condition: ocean fields
    USE sbc_ice         ! Surface boundary condition: ice   fields
@@ -38,4 +38,5 @@
    USE ice_calendar, only: dt
    USE ice_state, only: aice,aicen,uvel,vvel,vsno,vsnon,vice,vicen
+# if defined key_cice4
    USE ice_flux, only: strax,stray,strocnx,strocny,frain,fsnow,  &
                 sst,sss,uocn,vocn,ss_tltx,ss_tlty,fsalt_gbm,     &
@@ -44,7 +45,16 @@
                 uatm,vatm,wind,fsw,flw,Tair,potT,Qa,rhoa,zlvl,   &
                 swvdr,swvdf,swidr,swidf
+   USE ice_therm_vertical, only: calc_Tsfc
+#else
+   USE ice_flux, only: strax,stray,strocnx,strocny,frain,fsnow,  &
+                sst,sss,uocn,vocn,ss_tltx,ss_tlty,fsalt_ai,     &
+                fresh_ai,fhocn_ai,fswthru_ai,frzmlt,          &
+                flatn_f,fsurfn_f,fcondtopn_f,                    &
+                uatm,vatm,wind,fsw,flw,Tair,potT,Qa,rhoa,zlvl,   &
+                swvdr,swvdf,swidr,swidf
+   USE ice_therm_shared, only: calc_Tsfc
+#endif
    USE ice_forcing, only: frcvdr,frcvdf,frcidr,frcidf
    USE ice_atmo, only: calc_strair
-   USE ice_therm_vertical, only: calc_Tsfc
 
    USE CICE_InitMod
@@ -95,5 +105,5 @@
    END FUNCTION sbc_ice_cice_alloc
 
-   SUBROUTINE sbc_ice_cice( kt, nsbc )
+   SUBROUTINE sbc_ice_cice( kt, ksbc )
       !!---------------------------------------------------------------------
       !!                  ***  ROUTINE sbc_ice_cice  ***
@@ -113,5 +123,5 @@
       !!---------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt      ! ocean time step
-      INTEGER, INTENT(in) ::   nsbc    ! surface forcing type
+      INTEGER, INTENT(in) ::   ksbc    ! surface forcing type
       !!----------------------------------------------------------------------
       !
@@ -123,15 +133,15 @@
 
          ! Make sure any fluxes required for CICE are set
-         IF ( nsbc == 2 )  THEN
+         IF      ( ksbc == jp_flx ) THEN
             CALL cice_sbc_force(kt)
-         ELSE IF ( nsbc == 5 ) THEN
+         ELSE IF ( ksbc == jp_cpl ) THEN
             CALL sbc_cpl_ice_flx( 1.0-fr_i  )
          ENDIF
 
-         CALL cice_sbc_in ( kt, nsbc )
+         CALL cice_sbc_in  ( kt, ksbc )
          CALL CICE_Run
-         CALL cice_sbc_out ( kt, nsbc )
-
-         IF ( nsbc == 5 )  CALL cice_sbc_hadgam(kt+1)
+         CALL cice_sbc_out ( kt, ksbc )
+
+         IF ( ksbc == jp_cpl )  CALL cice_sbc_hadgam(kt+1)
 
       ENDIF                                          ! End sea-ice time step only
@@ -141,13 +151,13 @@
    END SUBROUTINE sbc_ice_cice
 
-   SUBROUTINE cice_sbc_init (nsbc)
+   SUBROUTINE cice_sbc_init (ksbc)
       !!---------------------------------------------------------------------
       !!                    ***  ROUTINE cice_sbc_init  ***
       !! ** Purpose: Initialise ice related fields for NEMO and coupling
       !!
-      INTEGER, INTENT( in  ) ::   nsbc                ! surface forcing type
+      INTEGER, INTENT( in  ) ::   ksbc                ! surface forcing type
       REAL(wp), DIMENSION(:,:), POINTER :: ztmp1, ztmp2
       REAL(wp) ::   zcoefu, zcoefv, zcoeff            ! local scalar
-      INTEGER  ::   ji, jj, jl                        ! dummy loop indices
+      INTEGER  ::   ji, jj, jl, jk                    ! dummy loop indices
       !!---------------------------------------------------------------------
 
@@ -161,13 +171,22 @@
       jj_off = INT ( (jpjglo - ny_global) / 2 )
 
+#if defined key_nemocice_decomp
+      ! Pass initial SST from NEMO to CICE so ice is initialised correctly if
+      ! there is no restart file.
+      ! Values from a CICE restart file would overwrite this
+      IF ( .NOT. ln_rstart ) THEN    
+         CALL nemo2cice( tsn(:,:,1,jp_tem) , sst , 'T' , 1.) 
+      ENDIF  
+#endif
+
 ! Initialize CICE
       CALL CICE_Initialize
 
 ! Do some CICE consistency checks
-      IF ( (nsbc == 2) .OR. (nsbc == 5) ) THEN
+      IF ( (ksbc == jp_flx) .OR. (ksbc == jp_cpl) ) THEN
          IF ( calc_strair .OR. calc_Tsfc ) THEN
             CALL ctl_stop( 'STOP', 'cice_sbc_init : Forcing option requires calc_strair=F and calc_Tsfc=F in ice_in' )
          ENDIF
-      ELSEIF (nsbc == 4) THEN
+      ELSEIF (ksbc == jp_core) THEN
          IF ( .NOT. (calc_strair .AND. calc_Tsfc) ) THEN
             CALL ctl_stop( 'STOP', 'cice_sbc_init : Forcing option requires calc_strair=T and calc_Tsfc=T in ice_in' )
@@ -190,5 +209,5 @@
 
       CALL cice2nemo(aice,fr_i, 'T', 1. )
-      IF ( (nsbc == 2).OR.(nsbc == 5) ) THEN
+      IF ( (ksbc == jp_flx) .OR. (ksbc == jp_cpl) ) THEN
          DO jl=1,ncat
             CALL cice2nemo(aicen(:,:,jl,:),a_i(:,:,jl), 'T', 1. )
@@ -218,9 +237,44 @@
          snwice_mass_b(:,:) = 0.0_wp         ! no mass exchanges
       ENDIF
-      IF( nn_ice_embd == 2 .AND.          &  ! full embedment (case 2) & no restart : 
-         &   .NOT.ln_rstart ) THEN           ! deplete the initial ssh belew sea-ice area
-         sshn(:,:) = sshn(:,:) - snwice_mass(:,:) * r1_rau0
-         sshb(:,:) = sshb(:,:) - snwice_mass(:,:) * r1_rau0
-         !
+      IF( .NOT. ln_rstart ) THEN
+         IF( nn_ice_embd == 2 ) THEN            ! full embedment (case 2) deplete the initial ssh below sea-ice area
+            sshn(:,:) = sshn(:,:) - snwice_mass(:,:) * r1_rau0
+            sshb(:,:) = sshb(:,:) - snwice_mass(:,:) * r1_rau0
+#if defined key_vvl            
+           ! key_vvl necessary? clem: yes for compilation purpose
+            DO jk = 1,jpkm1                     ! adjust initial vertical scale factors
+               fse3t_n(:,:,jk) = e3t_0(:,:,jk)*( 1._wp + sshn(:,:)*tmask(:,:,1)/(ht_0(:,:) + 1.0 - tmask(:,:,1)) )
+               fse3t_b(:,:,jk) = e3t_0(:,:,jk)*( 1._wp + sshb(:,:)*tmask(:,:,1)/(ht_0(:,:) + 1.0 - tmask(:,:,1)) )
+            ENDDO
+            fse3t_a(:,:,:) = fse3t_b(:,:,:)
+            ! Reconstruction of all vertical scale factors at now and before time
+            ! steps
+            ! =============================================================================
+            ! Horizontal scale factor interpolations
+            ! --------------------------------------
+            CALL dom_vvl_interpol( fse3t_b(:,:,:), fse3u_b(:,:,:), 'U' )
+            CALL dom_vvl_interpol( fse3t_b(:,:,:), fse3v_b(:,:,:), 'V' )
+            CALL dom_vvl_interpol( fse3t_n(:,:,:), fse3u_n(:,:,:), 'U' )
+            CALL dom_vvl_interpol( fse3t_n(:,:,:), fse3v_n(:,:,:), 'V' )
+            CALL dom_vvl_interpol( fse3u_n(:,:,:), fse3f_n(:,:,:), 'F' )
+            ! Vertical scale factor interpolations
+            ! ------------------------------------
+            CALL dom_vvl_interpol( fse3t_n(:,:,:), fse3w_n (:,:,:), 'W'  )
+            CALL dom_vvl_interpol( fse3u_n(:,:,:), fse3uw_n(:,:,:), 'UW' )
+            CALL dom_vvl_interpol( fse3v_n(:,:,:), fse3vw_n(:,:,:), 'VW' )
+            CALL dom_vvl_interpol( fse3u_b(:,:,:), fse3uw_b(:,:,:), 'UW' )
+            CALL dom_vvl_interpol( fse3v_b(:,:,:), fse3vw_b(:,:,:), 'VW' )
+            ! t- and w- points depth
+            ! ----------------------
+            fsdept_n(:,:,1) = 0.5_wp * fse3w_n(:,:,1)
+            fsdepw_n(:,:,1) = 0.0_wp
+            fsde3w_n(:,:,1) = fsdept_n(:,:,1) - sshn(:,:)
+            DO jk = 2, jpk
+               fsdept_n(:,:,jk) = fsdept_n(:,:,jk-1) + fse3w_n(:,:,jk)
+               fsdepw_n(:,:,jk) = fsdepw_n(:,:,jk-1) + fse3t_n(:,:,jk-1)
+               fsde3w_n(:,:,jk) = fsdept_n(:,:,jk  ) - sshn   (:,:)
+            END DO
+#endif
+         ENDIF
       ENDIF
  
@@ -232,5 +286,5 @@
 
    
-   SUBROUTINE cice_sbc_in (kt, nsbc)
+   SUBROUTINE cice_sbc_in (kt, ksbc)
       !!---------------------------------------------------------------------
       !!                    ***  ROUTINE cice_sbc_in  ***
@@ -238,5 +292,5 @@
       !!---------------------------------------------------------------------
       INTEGER, INTENT(in   ) ::   kt   ! ocean time step
-      INTEGER, INTENT(in   ) ::   nsbc ! surface forcing type
+      INTEGER, INTENT(in   ) ::   ksbc ! surface forcing type
 
       INTEGER  ::   ji, jj, jl                   ! dummy loop indices      
@@ -262,5 +316,5 @@
 ! forced and coupled case 
 
-      IF ( (nsbc == 2).OR.(nsbc == 5) ) THEN
+      IF ( (ksbc == jp_flx).OR.(ksbc == jp_cpl) ) THEN
 
          ztmpn(:,:,:)=0.0
@@ -287,5 +341,5 @@
 
 ! Surface downward latent heat flux (CI_5)
-         IF (nsbc == 2) THEN
+         IF (ksbc == jp_flx) THEN
             DO jl=1,ncat
                ztmpn(:,:,jl)=qla_ice(:,:,1)*a_i(:,:,jl)
@@ -316,5 +370,5 @@
 ! GBM conductive flux through ice (CI_6)
 !  Convert to GBM
-            IF (nsbc == 2) THEN
+            IF (ksbc == jp_flx) THEN
                ztmp(:,:) = botmelt(:,:,jl)*a_i(:,:,jl)
             ELSE
@@ -325,5 +379,5 @@
 ! GBM surface heat flux (CI_7)
 !  Convert to GBM
-            IF (nsbc == 2) THEN
+            IF (ksbc == jp_flx) THEN
                ztmp(:,:) = (topmelt(:,:,jl)+botmelt(:,:,jl))*a_i(:,:,jl) 
             ELSE
@@ -333,5 +387,5 @@
          ENDDO
 
-      ELSE IF (nsbc == 4) THEN
+      ELSE IF (ksbc == jp_core) THEN
 
 ! Pass CORE forcing fields to CICE (which will calculate heat fluxes etc itself)
@@ -375,9 +429,11 @@
 
 ! Snowfall
-! Ensure fsnow is positive (as in CICE routine prepare_forcing)  
+! Ensure fsnow is positive (as in CICE routine prepare_forcing)
+      IF( iom_use('snowpre') )   CALL iom_put('snowpre',MAX( (1.0-fr_i(:,:))*sprecip(:,:) ,0.0)) !!Joakim edit  
       ztmp(:,:)=MAX(fr_i(:,:)*sprecip(:,:),0.0)  
       CALL nemo2cice(ztmp,fsnow,'T', 1. ) 
 
 ! Rainfall
+      IF( iom_use('precip') )   CALL iom_put('precip', (1.0-fr_i(:,:))*(tprecip(:,:)-sprecip(:,:)) ) !!Joakim edit
       ztmp(:,:)=fr_i(:,:)*(tprecip(:,:)-sprecip(:,:))
       CALL nemo2cice(ztmp,frain,'T', 1. ) 
@@ -458,5 +514,5 @@
 
 
-   SUBROUTINE cice_sbc_out (kt,nsbc)
+   SUBROUTINE cice_sbc_out (kt,ksbc)
       !!---------------------------------------------------------------------
       !!                    ***  ROUTINE cice_sbc_out  ***
@@ -464,5 +520,5 @@
       !!---------------------------------------------------------------------
       INTEGER, INTENT( in  ) ::   kt   ! ocean time step
-      INTEGER, INTENT( in  ) ::   nsbc ! surface forcing type
+      INTEGER, INTENT( in  ) ::   ksbc ! surface forcing type
       
       INTEGER  ::   ji, jj, jl                 ! dummy loop indices
@@ -510,5 +566,5 @@
 ! Freshwater fluxes 
 
-      IF (nsbc == 2) THEN
+      IF (ksbc == jp_flx) THEN
 ! Note that emp from the forcing files is evap*(1-aice)-(tprecip-aice*sprecip)
 ! What we want here is evap*(1-aice)-tprecip*(1-aice) hence manipulation below
@@ -516,7 +572,7 @@
 ! Better to use evap and tprecip? (but for now don't read in evap in this case)
          emp(:,:)  = emp(:,:)+fr_i(:,:)*(tprecip(:,:)-sprecip(:,:))
-      ELSE IF (nsbc == 4) THEN
+      ELSE IF (ksbc == jp_core) THEN
          emp(:,:)  = (1.0-fr_i(:,:))*emp(:,:)        
-      ELSE IF (nsbc ==5) THEN
+      ELSE IF (ksbc == jp_cpl) THEN
 ! emp_tot is set in sbc_cpl_ice_flx (called from cice_sbc_in above) 
 ! This is currently as required with the coupling fields from the UM atmosphere
@@ -524,6 +580,11 @@
       ENDIF
 
+#if defined key_cice4
       CALL cice2nemo(fresh_gbm,ztmp1,'T', 1. )
       CALL cice2nemo(fsalt_gbm,ztmp2,'T', 1. )
+#else
+      CALL cice2nemo(fresh_ai,ztmp1,'T', 1. )
+      CALL cice2nemo(fsalt_ai,ztmp2,'T', 1. )
+#endif
 
 ! Check to avoid unphysical expression when ice is forming (ztmp1 negative)
@@ -535,5 +596,6 @@
       sfx(:,:)=ztmp2(:,:)*1000.0
       emp(:,:)=emp(:,:)-ztmp1(:,:)
- 
+      fmmflx(:,:) = ztmp1(:,:) !!Joakim edit
+      
       CALL lbc_lnk( emp , 'T', 1. )
       CALL lbc_lnk( sfx , 'T', 1. )
@@ -543,10 +605,10 @@
 ! Scale qsr and qns according to ice fraction (bulk formulae only)
 
-      IF (nsbc == 4) THEN
+      IF (ksbc == jp_core) THEN
          qsr(:,:)=qsr(:,:)*(1.0-fr_i(:,:))
          qns(:,:)=qns(:,:)*(1.0-fr_i(:,:))
       ENDIF
 ! Take into account snow melting except for fully coupled when already in qns_tot
-      IF (nsbc == 5) THEN
+      IF (ksbc == jp_cpl) THEN
          qsr(:,:)= qsr_tot(:,:)
          qns(:,:)= qns_tot(:,:)
@@ -557,5 +619,9 @@
 ! Now add in ice / snow related terms
 ! [fswthru will be zero unless running with calc_Tsfc=T in CICE]
+#if defined key_cice4
       CALL cice2nemo(fswthru_gbm,ztmp1,'T', 1. )
+#else
+      CALL cice2nemo(fswthru_ai,ztmp1,'T', 1. )
+#endif
       qsr(:,:)=qsr(:,:)+ztmp1(:,:)
       CALL lbc_lnk( qsr , 'T', 1. )
@@ -567,5 +633,9 @@
       ENDDO
 
+#if defined key_cice4
       CALL cice2nemo(fhocn_gbm,ztmp1,'T', 1. )
+#else
+      CALL cice2nemo(fhocn_ai,ztmp1,'T', 1. )
+#endif
       qns(:,:)=qns(:,:)+nfrzmlt(:,:)+ztmp1(:,:)
 
@@ -575,5 +645,5 @@
 
       CALL cice2nemo(aice,fr_i,'T', 1. )
-      IF ( (nsbc == 2).OR.(nsbc == 5) ) THEN
+      IF ( (ksbc == jp_flx).OR.(ksbc == jp_cpl) ) THEN
          DO jl=1,ncat
             CALL cice2nemo(aicen(:,:,jl,:),a_i(:,:,jl), 'T', 1. )
@@ -611,5 +681,4 @@
 
 
-#if defined key_oasis3 || defined key_oasis4
    SUBROUTINE cice_sbc_hadgam( kt )
       !!---------------------------------------------------------------------
@@ -653,10 +722,4 @@
    END SUBROUTINE cice_sbc_hadgam
 
-#else
-   SUBROUTINE cice_sbc_hadgam( kt )    ! Dummy routine
-      INTEGER, INTENT( in  ) ::   kt   ! ocean time step
-      WRITE(*,*) 'cice_sbc_hadgam: You should not have seen this print! error?'
-   END SUBROUTINE cice_sbc_hadgam
-#endif
 
    SUBROUTINE cice_sbc_final
@@ -713,4 +776,25 @@
       IF( kt == nit000 ) THEN                   !  First call kt=nit000  !
          !                                      ! ====================== !
+         ! namsbc_cice is not yet in the reference namelist
+         ! set file information (default values)
+         cn_dir = './'       ! directory in which the model is executed
+
+         ! (NB: frequency positive => hours, negative => months)
+         !            !    file          ! frequency !  variable    ! time intep !  clim   ! 'yearly' or ! weights  ! rotation   ! landmask
+         !            !    name          !  (hours)  !   name       !   (T/F)    !  (T/F)  !  'monthly'  ! filename ! pairs      ! file
+         sn_snow = FLD_N( 'snowfall_1m'  ,    -1.    ,  'snowfall'  ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    ) 
+         sn_rain = FLD_N( 'rainfall_1m'  ,    -1.    ,  'rainfall'  ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    ) 
+         sn_sblm = FLD_N( 'sublim_1m'    ,    -1.    ,  'sublim'    ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_top1 = FLD_N( 'topmeltn1_1m' ,    -1.    ,  'topmeltn1' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_top2 = FLD_N( 'topmeltn2_1m' ,    -1.    ,  'topmeltn2' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_top3 = FLD_N( 'topmeltn3_1m' ,    -1.    ,  'topmeltn3' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_top4 = FLD_N( 'topmeltn4_1m' ,    -1.    ,  'topmeltn4' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_top5 = FLD_N( 'topmeltn5_1m' ,    -1.    ,  'topmeltn5' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_bot1 = FLD_N( 'botmeltn1_1m' ,    -1.    ,  'botmeltn1' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_bot2 = FLD_N( 'botmeltn2_1m' ,    -1.    ,  'botmeltn2' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_bot3 = FLD_N( 'botmeltn3_1m' ,    -1.    ,  'botmeltn3' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_bot4 = FLD_N( 'botmeltn4_1m' ,    -1.    ,  'botmeltn4' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+         sn_bot5 = FLD_N( 'botmeltn5_1m' ,    -1.    ,  'botmeltn5' ,  .true.    , .true.  ,  ' yearly'  , ''       , ''         ,  ''    )
+
          REWIND( numnam_ref )              ! Namelist namsbc_cice in reference namelist : 
          READ  ( numnam_ref, namsbc_cice, IOSTAT = ios, ERR = 901)
@@ -1001,9 +1085,9 @@
 CONTAINS
 
-   SUBROUTINE sbc_ice_cice ( kt, nsbc )     ! Dummy routine
+   SUBROUTINE sbc_ice_cice ( kt, ksbc )     ! Dummy routine
       WRITE(*,*) 'sbc_ice_cice: You should not have seen this print! error?', kt
    END SUBROUTINE sbc_ice_cice
 
-   SUBROUTINE cice_sbc_init (nsbc)    ! Dummy routine
+   SUBROUTINE cice_sbc_init (ksbc)    ! Dummy routine
       WRITE(*,*) 'cice_sbc_init: You should not have seen this print! error?'
    END SUBROUTINE cice_sbc_init
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_if.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_if.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_if.F90	(revision 5075)
@@ -16,5 +16,9 @@
    USE eosbn2         ! equation of state
    USE sbc_oce        ! surface boundary condition: ocean fields
-   USE sbccpl
+#if defined key_lim3
+   USE ice    , ONLY :   a_i 
+#else
+   USE sbc_ice, ONLY :   a_i 
+#endif
    USE fldread        ! read input field
    USE iom            ! I/O manager library
@@ -99,13 +103,9 @@
                                  ! ( d rho / dt ) / ( d rho / ds )      ( s = 34, t = -1.8 )
          
-         fr_i(:,:) = tfreez( sss_m ) * tmask(:,:,1)      ! sea surface freezing temperature [Celcius]
+         fr_i(:,:) = eos_fzp( sss_m ) * tmask(:,:,1)      ! sea surface freezing temperature [Celcius]
 
-! OM : probleme. a_i pas defini dans les cas lim3 et cice
-#if defined key_coupled && defined key_lim2
-         a_i(:,:,1) = fr_i(:,:)         
-#endif
+         IF( lk_cpl )   a_i(:,:,1) = fr_i(:,:)         
 
          ! Flux and ice fraction computation
-!CDIR COLLAPSE
          DO jj = 1, jpj
             DO ji = 1, jpi
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim.F90	(revision 5075)
@@ -12,4 +12,5 @@
    !!            3.4  ! 2011-01  (A Porter)  dynamical allocation
    !!             -   ! 2012-10  (C. Rousset)  add lim_diahsb
+   !!            3.6  ! 2014-07  (M. Vancoppenolle, G. Madec, O. Marti) revise coupled interface
    !!----------------------------------------------------------------------
 #if defined key_lim3
@@ -68,4 +69,5 @@
 
    PUBLIC sbc_ice_lim  ! routine called by sbcmod.F90
+   PUBLIC lim_prt_state
    
    !! * Substitutions
@@ -78,33 +80,4 @@
    !!----------------------------------------------------------------------
 CONTAINS
-
-   FUNCTION fice_cell_ave ( ptab)
-      !!--------------------------------------------------------------------------
-      !! * Compute average over categories, for grid cell (ice covered and free ocean)
-      !!--------------------------------------------------------------------------
-      REAL (wp), DIMENSION (jpi,jpj) :: fice_cell_ave
-      REAL (wp), DIMENSION (jpi,jpj,jpl), INTENT (in) :: ptab
-      INTEGER :: jl ! Dummy loop index
-      
-      fice_cell_ave (:,:) = 0.0_wp
-      
-      DO jl = 1, jpl
-         fice_cell_ave (:,:) = fice_cell_ave (:,:) &
-            &                  + a_i (:,:,jl) * ptab (:,:,jl)
-      END DO
-      
-   END FUNCTION fice_cell_ave
-   
-   FUNCTION fice_ice_ave ( ptab)
-      !!--------------------------------------------------------------------------
-      !! * Compute average over categories, for ice covered part of grid cell
-      !!--------------------------------------------------------------------------
-      REAL (kind=wp), DIMENSION (jpi,jpj) :: fice_ice_ave
-      REAL (kind=wp), DIMENSION (jpi,jpj,jpl), INTENT(in) :: ptab
-
-      fice_ice_ave (:,:) = 0.0_wp
-      WHERE ( at_i (:,:) .GT. 0.0_wp ) fice_ice_ave (:,:) = fice_cell_ave ( ptab (:,:,:)) / at_i (:,:)
-
-   END FUNCTION fice_ice_ave
 
    !!======================================================================
@@ -131,32 +104,13 @@
       !!---------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt      ! ocean time step
-      INTEGER, INTENT(in) ::   kblk    ! type of bulk (=3 CLIO, =4 CORE)
+      INTEGER, INTENT(in) ::   kblk    ! type of bulk (=3 CLIO, =4 CORE, =5 COUPLED)
       !!
       INTEGER  ::   jl      ! dummy loop index
       REAL(wp) ::   zcoef   ! local scalar
-      REAL(wp), POINTER, DIMENSION(:,:,:)   ::   zalb_ice_os, zalb_ice_cs  ! albedo of the ice under overcast/clear sky
-      REAL(wp), POINTER, DIMENSION(:,:,:)   ::   zalb_ice      ! mean albedo of ice (for coupled)
-
-      REAL(wp), POINTER, DIMENSION(:,:) :: zalb_ice_all    ! Mean albedo over all categories
-      REAL(wp), POINTER, DIMENSION(:,:) :: ztem_ice_all    ! Mean temperature over all categories
-      
-      REAL(wp), POINTER, DIMENSION(:,:) :: z_qsr_ice_all   ! Mean solar heat flux over all categories
-      REAL(wp), POINTER, DIMENSION(:,:) :: z_qns_ice_all   ! Mean non solar heat flux over all categories
-      REAL(wp), POINTER, DIMENSION(:,:) :: z_qla_ice_all   ! Mean latent heat flux over all categories
-      REAL(wp), POINTER, DIMENSION(:,:) :: z_dqns_ice_all  ! Mean d(qns)/dT over all categories
-      REAL(wp), POINTER, DIMENSION(:,:) :: z_dqla_ice_all  ! Mean d(qla)/dT over all categories
+      REAL(wp), POINTER, DIMENSION(:,:,:)   ::   zalb_os, zalb_cs  ! ice albedo under overcast/clear sky
+      REAL(wp), POINTER, DIMENSION(:,:,:)   ::   zalb_ice          ! mean ice albedo (for coupled)
       !!----------------------------------------------------------------------
 
-      !- O.M. : why do we allocate all these arrays even when MOD( kt-1, nn_fsbc ) /= 0 ?????
-
       IF( nn_timing == 1 )  CALL timing_start('sbc_ice_lim')
-
-      CALL wrk_alloc( jpi,jpj,jpl, zalb_ice_os, zalb_ice_cs )
-
-#if defined key_coupled
-      IF ( ln_cpl .OR. ln_iceflx_ave .OR. ln_iceflx_linear ) CALL wrk_alloc( jpi,jpj,jpl, zalb_ice)
-      IF ( ln_iceflx_ave .OR. ln_iceflx_linear ) &
-         &   CALL wrk_alloc( jpi,jpj, ztem_ice_all, zalb_ice_all, z_qsr_ice_all, z_qns_ice_all, z_qla_ice_all, z_dqns_ice_all, z_dqla_ice_all)
-#endif
 
       IF( kt == nit000 ) THEN
@@ -168,5 +122,5 @@
          !
          IF( ln_nicep ) THEN      ! control print at a given point
-            jiindx = 177   ;   jjindx = 112
+            jiindx = 15    ;   jjindx =  44
             IF(lwp) WRITE(numout,*) ' The debugging point is : jiindx : ',jiindx, ' jjindx : ',jjindx
          ENDIF
@@ -176,30 +130,33 @@
       IF( MOD( kt-1, nn_fsbc ) == 0 ) THEN     !  Ice time-step only  !
          !                                     !----------------------!
-         !                                           !  Bulk Formulea !
+         !                                           !  Bulk Formulae !
          !                                           !----------------!
          !
-         u_oce(:,:) = ssu_m(:,:)                     ! mean surface ocean current at ice velocity point
-         v_oce(:,:) = ssv_m(:,:)                     ! (C-grid dynamics :  U- & V-points as the ocean)
-         !
-         t_bo(:,:) = tfreez( sss_m ) +  rt0          ! masked sea surface freezing temperature [Kelvin]
-         !                                           ! (set to rt0 over land)
-         CALL albedo_ice( t_su, ht_i, ht_s, zalb_ice_cs, zalb_ice_os )  ! ... ice albedo
-
+         u_oce(:,:) = ssu_m(:,:) * umask(:,:,1)                     ! mean surface ocean current at ice velocity point
+         v_oce(:,:) = ssv_m(:,:) * vmask(:,:,1)                    ! (C-grid dynamics :  U- & V-points as the ocean)
+         !
+         t_bo(:,:) = ( eos_fzp( sss_m ) +  rt0 ) * tmask(:,:,1) + rt0 * ( 1. - tmask(:,:,1) )  ! masked sea surface freezing temperature [Kelvin]
+         !                                                                                  ! (set to rt0 over land)
+         !                                           ! Ice albedo
+         CALL wrk_alloc( jpi,jpj,jpl, zalb_os, zalb_cs, zalb_ice )      
+
+         CALL albedo_ice( t_su, ht_i, ht_s, zalb_cs, zalb_os )  ! cloud-sky and overcast-sky ice albedos
+
+         SELECT CASE( kblk )
+         CASE( jp_core , jp_cpl )   ! CORE and COUPLED bulk formulations
+
+            ! albedo depends on cloud fraction because of non-linear spectral effects
+            zalb_ice(:,:,:) = ( 1. - cldf_ice ) * zalb_cs(:,:,:) + cldf_ice * zalb_os(:,:,:)
+            ! In CLIO the cloud fraction is read in the climatology and the all-sky albedo 
+            ! (zalb_ice) is computed within the bulk routine
+            
+         END SELECT
+         
+         !                                           ! Mask sea ice surface temperature
          DO jl = 1, jpl
             t_su(:,:,jl) = t_su(:,:,jl) +  rt0 * ( 1. - tmask(:,:,1) )
          END DO
-
-         IF ( ln_cpl ) zalb_ice (:,:,:) = 0.5 * ( zalb_ice_cs (:,:,:) +  zalb_ice_os (:,:,:) )
-         
-#if defined key_coupled
-         IF ( ln_iceflx_ave .OR. ln_iceflx_linear ) THEN
-            !
-            ! Compute mean albedo and temperature
-            zalb_ice_all (:,:) = fice_ice_ave ( zalb_ice (:,:,:) ) 
-            ztem_ice_all (:,:) = fice_ice_ave ( tn_ice   (:,:,:) ) 
-            !
-         ENDIF
-#endif
-                                               ! Bulk formulea - provides the following fields:
+     
+         ! Bulk formulae  - provides the following fields:
          ! utau_ice, vtau_ice : surface ice stress                     (U- & V-points)   [N/m2]
          ! qsr_ice , qns_ice  : solar & non solar heat flux over ice   (T-point)         [W/m2]
@@ -210,6 +167,6 @@
          !
          SELECT CASE( kblk )
-         CASE( 3 )                                       ! CLIO bulk formulation
-            CALL blk_ice_clio( t_su , zalb_ice_cs, zalb_ice_os,                           &
+         CASE( jp_clio )                                       ! CLIO bulk formulation
+            CALL blk_ice_clio( t_su , zalb_cs    , zalb_os    , zalb_ice  ,               &
                &                      utau_ice   , vtau_ice   , qns_ice   , qsr_ice   ,   &
                &                      qla_ice    , dqns_ice   , dqla_ice  ,               &
@@ -217,57 +174,34 @@
                &                      fr1_i0     , fr2_i0     , cp_ice_msh, jpl  )
             !         
-         CASE( 4 )                                       ! CORE bulk formulation
-            CALL blk_ice_core( t_su , u_ice     , v_ice     , zalb_ice_cs,               &
+            IF( nn_limflx /= 2 )   CALL ice_lim_flx( t_su, zalb_ice, qns_ice, qsr_ice ,   &
+               &                                           dqns_ice, qla_ice, dqla_ice, nn_limflx )
+
+         CASE( jp_core )                                       ! CORE bulk formulation
+            CALL blk_ice_core( t_su , u_ice     , v_ice     , zalb_ice   ,               &
                &                      utau_ice  , vtau_ice  , qns_ice    , qsr_ice   ,   &
                &                      qla_ice   , dqns_ice  , dqla_ice   ,               &
                &                      tprecip   , sprecip   ,                            &
                &                      fr1_i0    , fr2_i0    , cp_ice_msh, jpl  )
+               !
+            IF( nn_limflx /= 2 )   CALL ice_lim_flx( t_su, zalb_ice, qns_ice, qsr_ice ,   &
+               &                                           dqns_ice, qla_ice, dqla_ice, nn_limflx )
             !
-         CASE ( 5 )
-            zalb_ice (:,:,:) = 0.5 * ( zalb_ice_cs (:,:,:) +  zalb_ice_os (:,:,:) )
+         CASE ( jp_cpl )
             
             CALL sbc_cpl_ice_tau( utau_ice , vtau_ice )
 
-            CALL sbc_cpl_ice_flx( p_frld=ato_i, palbi=zalb_ice, psst=sst_m, pist=tn_ice    )
-
-            ! Latent heat flux is forced to 0 in coupled :
-            !  it is included in qns (non-solar heat flux)
-            qla_ice  (:,:,:) = 0.0e0_wp
-            dqla_ice (:,:,:) = 0.0e0_wp
+            ! MV -> seb 
+!           CALL sbc_cpl_ice_flx( p_frld=ato_i, palbi=zalb_ice, psst=sst_m, pist=t_su    )
+
+!           IF( nn_limflx == 2 )   CALL ice_lim_flx( t_su, zalb_ice, qns_ice, qsr_ice ,   &
+!              &                                           dqns_ice, qla_ice, dqla_ice, nn_limflx )
+!           ! Latent heat flux is forced to 0 in coupled :
+!           !  it is included in qns (non-solar heat flux)
+!           qla_ice  (:,:,:) = 0._wp
+!           dqla_ice (:,:,:) = 0._wp
+            ! END MV -> seb
             !
          END SELECT
-
-         ! Average over all categories
-#if defined key_coupled
-         IF ( ln_iceflx_ave .OR. ln_iceflx_linear ) THEN
-
-            z_qns_ice_all  (:,:) = fice_ice_ave ( qns_ice  (:,:,:) )
-            z_qsr_ice_all  (:,:) = fice_ice_ave ( qsr_ice  (:,:,:) )
-            z_dqns_ice_all (:,:) = fice_ice_ave ( dqns_ice (:,:,:) )
-            z_qla_ice_all  (:,:) = fice_ice_ave ( qla_ice  (:,:,:) )
-            z_dqla_ice_all (:,:) = fice_ice_ave ( dqla_ice (:,:,:) )
-
-            DO jl = 1, jpl
-               dqns_ice (:,:,jl) = z_dqns_ice_all (:,:)
-               dqla_ice (:,:,jl) = z_dqla_ice_all (:,:)
-            END DO
-            !
-            IF ( ln_iceflx_ave ) THEN
-               DO jl = 1, jpl
-                  qns_ice  (:,:,jl) = z_qns_ice_all  (:,:)
-                  qsr_ice  (:,:,jl) = z_qsr_ice_all  (:,:)
-                  qla_ice  (:,:,jl) = z_qla_ice_all  (:,:)
-               END DO
-            END IF
-            !
-            IF ( ln_iceflx_linear ) THEN
-               DO jl = 1, jpl
-                  qns_ice  (:,:,jl) = z_qns_ice_all(:,:) + z_dqns_ice_all(:,:) * (tn_ice(:,:,jl) - ztem_ice_all(:,:))
-                  qla_ice  (:,:,jl) = z_qla_ice_all(:,:) + z_dqla_ice_all(:,:) * (tn_ice(:,:,jl) - ztem_ice_all(:,:))
-                  qsr_ice  (:,:,jl) = (1.0e0_wp-zalb_ice(:,:,jl)) / (1.0e0_wp-zalb_ice_all(:,:)) * z_qsr_ice_all(:,:)
-               END DO
-            END IF
-         END IF
-#endif
+         
          !                                           !----------------------!
          !                                           ! LIM-3  time-stepping !
@@ -277,54 +211,37 @@
          !
          !                                           ! Store previous ice values
-!!gm : remark   old_...   should becomes ...b  as tn versus tb  
-         old_a_i  (:,:,:)   = a_i  (:,:,:)     ! ice area
-         old_e_i  (:,:,:,:) = e_i  (:,:,:,:)   ! ice thermal energy
-         old_v_i  (:,:,:)   = v_i  (:,:,:)     ! ice volume
-         old_v_s  (:,:,:)   = v_s  (:,:,:)     ! snow volume 
-         old_e_s  (:,:,:,:) = e_s  (:,:,:,:)   ! snow thermal energy
-         old_smv_i(:,:,:)   = smv_i(:,:,:)     ! salt content
-         old_oa_i (:,:,:)   = oa_i (:,:,:)     ! areal age content
-         !
-         old_u_ice(:,:) = u_ice(:,:)
-         old_v_ice(:,:) = v_ice(:,:)
-         !                                           ! intialisation to zero    !!gm is it truly necessary ???
-         d_a_i_thd  (:,:,:)   = 0._wp   ;   d_a_i_trp  (:,:,:)   = 0._wp
-         d_v_i_thd  (:,:,:)   = 0._wp   ;   d_v_i_trp  (:,:,:)   = 0._wp
-         d_e_i_thd  (:,:,:,:) = 0._wp   ;   d_e_i_trp  (:,:,:,:) = 0._wp
-         d_v_s_thd  (:,:,:)   = 0._wp   ;   d_v_s_trp  (:,:,:)   = 0._wp
-         d_e_s_thd  (:,:,:,:) = 0._wp   ;   d_e_s_trp  (:,:,:,:) = 0._wp
-         d_smv_i_thd(:,:,:)   = 0._wp   ;   d_smv_i_trp(:,:,:)   = 0._wp
-         d_oa_i_thd (:,:,:)   = 0._wp   ;   d_oa_i_trp (:,:,:)   = 0._wp
-         !
-         d_u_ice_dyn(:,:) = 0._wp
-         d_v_ice_dyn(:,:) = 0._wp
-         !
-         sfx    (:,:) = 0._wp   ;   sfx_thd  (:,:) = 0._wp
-         sfx_bri(:,:) = 0._wp   ;   sfx_mec  (:,:) = 0._wp   ;   sfx_res  (:,:) = 0._wp
-         fhbri  (:,:) = 0._wp   ;   fheat_mec(:,:) = 0._wp   ;   fheat_res(:,:) = 0._wp
-         fhmec  (:,:) = 0._wp   ;   
-         fmmec  (:,:) = 0._wp
-         fmmflx (:,:) = 0._wp     
-         focea2D(:,:) = 0._wp
-         fsup2D (:,:) = 0._wp
-
-         ! used in limthd.F90
-         rdvosif(:,:) = 0._wp   ! variation of ice volume at surface
-         rdvobif(:,:) = 0._wp   ! variation of ice volume at bottom
-         fdvolif(:,:) = 0._wp   ! total variation of ice volume
-         rdvonif(:,:) = 0._wp   ! lateral variation of ice volume
-         fstric (:,:) = 0._wp   ! part of solar radiation transmitted through the ice
-         ffltbif(:,:) = 0._wp   ! linked with fstric
-         qfvbq  (:,:) = 0._wp   ! linked with fstric
-         rdm_snw(:,:) = 0._wp   ! variation of snow mass per unit area
-         rdm_ice(:,:) = 0._wp   ! variation of ice mass per unit area
-         hicifp (:,:) = 0._wp   ! daily thermodynamic ice production. 
-         !
-         diag_sni_gr(:,:) = 0._wp   ;   diag_lat_gr(:,:) = 0._wp
-         diag_bot_gr(:,:) = 0._wp   ;   diag_dyn_gr(:,:) = 0._wp
-         diag_bot_me(:,:) = 0._wp   ;   diag_sur_me(:,:) = 0._wp
-         diag_res_pr(:,:) = 0._wp   ;   diag_trp_vi(:,:) = 0._wp
-         ! dynamical invariants
-         delta_i(:,:) = 0._wp       ;   divu_i(:,:) = 0._wp       ;   shear_i(:,:) = 0._wp
+         a_i_b  (:,:,:)   = a_i  (:,:,:)     ! ice area
+         e_i_b  (:,:,:,:) = e_i  (:,:,:,:)   ! ice thermal energy
+         v_i_b  (:,:,:)   = v_i  (:,:,:)     ! ice volume
+         v_s_b  (:,:,:)   = v_s  (:,:,:)     ! snow volume 
+         e_s_b  (:,:,:,:) = e_s  (:,:,:,:)   ! snow thermal energy
+         smv_i_b(:,:,:)   = smv_i(:,:,:)     ! salt content
+         oa_i_b (:,:,:)   = oa_i (:,:,:)     ! areal age content
+         u_ice_b(:,:)     = u_ice(:,:)
+         v_ice_b(:,:)     = v_ice(:,:)
+
+         ! salt, heat and mass fluxes
+         sfx    (:,:) = 0._wp   ;
+         sfx_bri(:,:) = 0._wp   ; 
+         sfx_sni(:,:) = 0._wp   ;   sfx_opw(:,:) = 0._wp
+         sfx_bog(:,:) = 0._wp   ;   sfx_dyn(:,:) = 0._wp
+         sfx_bom(:,:) = 0._wp   ;   sfx_sum(:,:) = 0._wp
+         sfx_res(:,:) = 0._wp
+
+         wfx_snw(:,:) = 0._wp   ;   wfx_ice(:,:) = 0._wp
+         wfx_sni(:,:) = 0._wp   ;   wfx_opw(:,:) = 0._wp
+         wfx_bog(:,:) = 0._wp   ;   wfx_dyn(:,:) = 0._wp
+         wfx_bom(:,:) = 0._wp   ;   wfx_sum(:,:) = 0._wp
+         wfx_res(:,:) = 0._wp   ;   wfx_sub(:,:) = 0._wp
+         wfx_spr(:,:) = 0._wp   ;   
+
+         hfx_in (:,:) = 0._wp   ;   hfx_out(:,:) = 0._wp
+         hfx_thd(:,:) = 0._wp   ;   
+         hfx_snw(:,:) = 0._wp   ;   hfx_opw(:,:) = 0._wp
+         hfx_bog(:,:) = 0._wp   ;   hfx_dyn(:,:) = 0._wp
+         hfx_bom(:,:) = 0._wp   ;   hfx_sum(:,:) = 0._wp
+         hfx_res(:,:) = 0._wp   ;   hfx_sub(:,:) = 0._wp
+         hfx_spr(:,:) = 0._wp   ;   hfx_dif(:,:) = 0._wp 
+         hfx_err(:,:) = 0._wp   ;   hfx_err_rem(:,:) = 0._wp
 
                           CALL lim_rst_opn( kt )     ! Open Ice restart file
@@ -352,13 +269,13 @@
          ENDIF
 !                         !- Change old values for new values
-                          old_u_ice(:,:)   = u_ice (:,:)
-                          old_v_ice(:,:)   = v_ice (:,:)
-                          old_a_i(:,:,:)   = a_i (:,:,:)
-                          old_v_s(:,:,:)   = v_s (:,:,:)
-                          old_v_i(:,:,:)   = v_i (:,:,:)
-                          old_e_s(:,:,:,:) = e_s (:,:,:,:)
-                          old_e_i(:,:,:,:) = e_i (:,:,:,:)
-                          old_oa_i(:,:,:)  = oa_i(:,:,:)
-                          old_smv_i(:,:,:) = smv_i (:,:,:)
+                          u_ice_b(:,:)     = u_ice(:,:)
+                          v_ice_b(:,:)     = v_ice(:,:)
+                          a_i_b  (:,:,:)   = a_i  (:,:,:)
+                          v_s_b  (:,:,:)   = v_s  (:,:,:)
+                          v_i_b  (:,:,:)   = v_i  (:,:,:)
+                          e_s_b  (:,:,:,:) = e_s  (:,:,:,:)
+                          e_i_b  (:,:,:,:) = e_i  (:,:,:,:)
+                          oa_i_b (:,:,:)   = oa_i (:,:,:)
+                          smv_i_b(:,:,:)   = smv_i(:,:,:)
  
          ! ----------------------------------------------
@@ -370,4 +287,17 @@
                           pfrld(:,:)   = 1._wp - at_i(:,:)
                           phicif(:,:)  = vt_i(:,:)
+
+                          ! MV -> seb
+                          SELECT CASE( kblk )
+                             CASE ( jp_cpl )
+                             CALL sbc_cpl_ice_flx( p_frld=pfrld, palbi=zalb_ice, psst=sst_m, pist=t_su    )
+                             IF( nn_limflx == 2 )   CALL ice_lim_flx( t_su, zalb_ice, qns_ice, qsr_ice ,   &
+                          &                                           dqns_ice, qla_ice, dqla_ice, nn_limflx )
+                           ! Latent heat flux is forced to 0 in coupled :
+                           !  it is included in qns (non-solar heat flux)
+                             qla_ice  (:,:,:) = 0._wp
+                             dqla_ice (:,:,:) = 0._wp
+                          END SELECT
+                          ! END MV -> seb
                           !
                           CALL lim_var_bv                 ! bulk brine volume (diag)
@@ -375,5 +305,4 @@
                           zcoef = rdt_ice /rday           !  Ice natural aging
                           oa_i(:,:,:) = oa_i(:,:,:) + a_i(:,:,:) * zcoef
-                          CALL lim_var_glo2eqv            ! this CALL is maybe not necessary (Martin)
          IF( ln_nicep )   CALL lim_prt_state( kt, jiindx, jjindx, 1, ' - ice thermodyn. - ' )   ! control print
                           CALL lim_itd_th( kt )           !  Remap ice categories, lateral accretion  !
@@ -391,7 +320,7 @@
          !                                           ! Diagnostics and outputs 
          IF (ln_limdiaout) CALL lim_diahsb
-!clem # if ! defined key_iomput
+
                           CALL lim_wri( 1  )              ! Ice outputs 
-!clem # endif
+
          IF( kt == nit000 .AND. ln_rstart )   &
             &             CALL iom_close( numrir )        ! clem: close input ice restart file
@@ -401,4 +330,6 @@
          !
          IF( ln_nicep )   CALL lim_ctl( kt )              ! alerts in case of model crash
+         !
+         CALL wrk_dealloc( jpi,jpj,jpl, zalb_os, zalb_cs, zalb_ice )
          !
       ENDIF                                    ! End sea-ice time step only
@@ -411,20 +342,92 @@
       !                                                   ! otherwise the atm.-ocean stresses are used everywhere
       IF( ln_limdyn )     CALL lim_sbc_tau( kt, ub(:,:,1), vb(:,:,1) )  ! using before instantaneous surf. currents
-      
 !!gm   remark, the ocean-ice stress is not saved in ice diag call above .....  find a solution!!!
-      !
-      CALL wrk_dealloc( jpi,jpj,jpl, zalb_ice_os, zalb_ice_cs )
-
-#if defined key_coupled
-      IF ( ln_cpl .OR. ln_iceflx_ave .OR. ln_iceflx_linear ) CALL wrk_dealloc( jpi,jpj,jpl, zalb_ice)
-      IF ( ln_iceflx_ave .OR. ln_iceflx_linear ) &
-         &    CALL wrk_dealloc( jpi,jpj, ztem_ice_all, zalb_ice_all, z_qsr_ice_all, z_qns_ice_all, z_qla_ice_all, z_dqns_ice_all, z_dqla_ice_all)
-#endif
+
       !
       IF( nn_timing == 1 )  CALL timing_stop('sbc_ice_lim')
       !
    END SUBROUTINE sbc_ice_lim
-
-
+   
+   
+      SUBROUTINE ice_lim_flx( ptn_ice, palb_ice, pqns_ice, pqsr_ice,   &
+         &                          pdqn_ice, pqla_ice, pdql_ice, k_limflx )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE sbc_ice_lim  ***
+      !!                   
+      !! ** Purpose :   update the ice surface boundary condition by averaging and / or
+      !!                redistributing fluxes on ice categories                   
+      !!
+      !! ** Method  :   average then redistribute 
+      !!
+      !! ** Action  :   
+      !!---------------------------------------------------------------------
+      INTEGER                   , INTENT(in   ) ::   k_limflx   ! =-1 do nothing; =0 average ; 
+                                                                ! =1 average and redistribute ; =2 redistribute
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   ptn_ice    ! ice surface temperature 
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   palb_ice   ! ice albedo
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pqns_ice   ! non solar flux
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pqsr_ice   ! net solar flux
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pdqn_ice   ! non solar flux sensitivity
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pqla_ice   ! latent heat flux
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   pdql_ice   ! latent heat flux sensitivity
+      !
+      INTEGER  ::   jl      ! dummy loop index
+      !
+      REAL(wp), POINTER, DIMENSION(:,:) :: zalb_m    ! Mean albedo over all categories
+      REAL(wp), POINTER, DIMENSION(:,:) :: ztem_m    ! Mean temperature over all categories
+      !
+      REAL(wp), POINTER, DIMENSION(:,:) :: z_qsr_m   ! Mean solar heat flux over all categories
+      REAL(wp), POINTER, DIMENSION(:,:) :: z_qns_m   ! Mean non solar heat flux over all categories
+      REAL(wp), POINTER, DIMENSION(:,:) :: z_qla_m   ! Mean latent heat flux over all categories
+      REAL(wp), POINTER, DIMENSION(:,:) :: z_dqn_m   ! Mean d(qns)/dT over all categories
+      REAL(wp), POINTER, DIMENSION(:,:) :: z_dql_m   ! Mean d(qla)/dT over all categories
+      !!----------------------------------------------------------------------
+
+      IF( nn_timing == 1 )  CALL timing_start('ice_lim_flx')
+      !
+      !
+      SELECT CASE( k_limflx )                              !==  averaged on all ice categories  ==!
+      CASE( 0 , 1 )
+         CALL wrk_alloc( jpi,jpj, z_qsr_m, z_qns_m, z_qla_m, z_dqn_m, z_dql_m)
+         !
+         z_qns_m(:,:) = fice_ice_ave ( pqns_ice (:,:,:) )
+         z_qsr_m(:,:) = fice_ice_ave ( pqsr_ice (:,:,:) )
+         z_dqn_m(:,:) = fice_ice_ave ( pdqn_ice (:,:,:) )
+         z_qla_m(:,:) = fice_ice_ave ( pqla_ice (:,:,:) )
+         z_dql_m(:,:) = fice_ice_ave ( pdql_ice (:,:,:) )
+         DO jl = 1, jpl
+            pdqn_ice(:,:,jl) = z_dqn_m(:,:)
+            pdql_ice(:,:,jl) = z_dql_m(:,:)
+         END DO
+         !
+         DO jl = 1, jpl
+            pqns_ice(:,:,jl) = z_qns_m(:,:)
+            pqsr_ice(:,:,jl) = z_qsr_m(:,:)
+            pqla_ice(:,:,jl) = z_qla_m(:,:)
+         END DO
+         !
+         CALL wrk_dealloc( jpi,jpj, z_qsr_m, z_qns_m, z_qla_m, z_dqn_m, z_dql_m)
+      END SELECT
+
+      SELECT CASE( k_limflx )                              !==  redistribution on all ice categories  ==!
+      CASE( 1 , 2 )
+         CALL wrk_alloc( jpi,jpj, zalb_m, ztem_m )
+         !
+         zalb_m(:,:) = fice_ice_ave ( palb_ice (:,:,:) ) 
+         ztem_m(:,:) = fice_ice_ave ( ptn_ice  (:,:,:) ) 
+         DO jl = 1, jpl
+            pqns_ice(:,:,jl) = pqns_ice(:,:,jl) + pdqn_ice(:,:,jl) * (ptn_ice(:,:,jl) - ztem_m(:,:))
+            pqla_ice(:,:,jl) = pqla_ice(:,:,jl) + pdql_ice(:,:,jl) * (ptn_ice(:,:,jl) - ztem_m(:,:))
+            pqsr_ice(:,:,jl) = pqsr_ice(:,:,jl) * ( 1._wp - palb_ice(:,:,jl) ) / ( 1._wp - zalb_m(:,:) ) 
+         END DO
+         !
+         CALL wrk_dealloc( jpi,jpj, zalb_m, ztem_m )
+      END SELECT
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('ice_lim_flx')
+      !
+   END SUBROUTINE ice_lim_flx
+   
+   
    SUBROUTINE lim_ctl( kt )
       !!-----------------------------------------------------------------------
@@ -456,6 +459,6 @@
                   !WRITE(numout,*) ' at_i     ', at_i(ji,jj)
                   !WRITE(numout,*) ' Point - category', ji, jj, jl
-                  !WRITE(numout,*) ' a_i *** a_i_old ', a_i      (ji,jj,jl), old_a_i  (ji,jj,jl)
-                  !WRITE(numout,*) ' v_i *** v_i_old ', v_i      (ji,jj,jl), old_v_i  (ji,jj,jl)
+                  !WRITE(numout,*) ' a_i *** a_i_b   ', a_i      (ji,jj,jl), a_i_b  (ji,jj,jl)
+                  !WRITE(numout,*) ' v_i *** v_i_b   ', v_i      (ji,jj,jl), v_i_b  (ji,jj,jl)
                   !WRITE(numout,*) ' d_a_i_thd/trp   ', d_a_i_thd(ji,jj,jl), d_a_i_trp(ji,jj,jl)
                   !WRITE(numout,*) ' d_v_i_thd/trp   ', d_v_i_thd(ji,jj,jl), d_v_i_trp(ji,jj,jl)
@@ -534,5 +537,4 @@
 !                 WRITE(numout,*) ' sst                  : ', sst_m(ji,jj)
 !                 WRITE(numout,*) ' sss                  : ', sss_m(ji,jj)
-!                 WRITE(numout,*) ' s_i_newice           : ', s_i_newice(ji,jj,1:jpl)
 !                 WRITE(numout,*) 
                   inb_alp(ialert_id) = inb_alp(ialert_id) + 1
@@ -568,7 +570,7 @@
                !DO jl = 1, jpl
                   !WRITE(numout,*) ' Category no: ', jl
-                  !WRITE(numout,*) ' a_i        : ', a_i      (ji,jj,jl) , ' old_a_i    : ', old_a_i  (ji,jj,jl)   
+                  !WRITE(numout,*) ' a_i        : ', a_i      (ji,jj,jl) , ' a_i_b      : ', a_i_b  (ji,jj,jl)   
                   !WRITE(numout,*) ' d_a_i_trp  : ', d_a_i_trp(ji,jj,jl) , ' d_a_i_thd  : ', d_a_i_thd(ji,jj,jl) 
-                  !WRITE(numout,*) ' v_i        : ', v_i      (ji,jj,jl) , ' old_v_i    : ', old_v_i  (ji,jj,jl)   
+                  !WRITE(numout,*) ' v_i        : ', v_i      (ji,jj,jl) , ' v_i_b      : ', v_i_b  (ji,jj,jl)   
                   !WRITE(numout,*) ' d_v_i_trp  : ', d_v_i_trp(ji,jj,jl) , ' d_v_i_thd  : ', d_v_i_thd(ji,jj,jl) 
                   !WRITE(numout,*) ' '
@@ -591,17 +593,4 @@
                !WRITE(numout,*) ' sst       : ', sst_m(ji,jj)
                !WRITE(numout,*) ' sss       : ', sss_m(ji,jj)
-               !WRITE(numout,*) ' qcmif     : ', qcmif(ji,jj)
-               !WRITE(numout,*) ' qldif     : ', qldif(ji,jj)
-               !WRITE(numout,*) ' qcmif     : ', qcmif(ji,jj) / rdt_ice
-               !WRITE(numout,*) ' qldif     : ', qldif(ji,jj) / rdt_ice
-               !WRITE(numout,*) ' qfvbq     : ', qfvbq(ji,jj)
-               !WRITE(numout,*) ' qdtcn     : ', qdtcn(ji,jj)
-               !WRITE(numout,*) ' qfvbq / dt: ', qfvbq(ji,jj) / rdt_ice
-               !WRITE(numout,*) ' qdtcn / dt: ', qdtcn(ji,jj) / rdt_ice
-               !WRITE(numout,*) ' fdtcn     : ', fdtcn(ji,jj) 
-               !WRITE(numout,*) ' fhmec     : ', fhmec(ji,jj) 
-               !WRITE(numout,*) ' fheat_mec : ', fheat_mec(ji,jj) 
-               !WRITE(numout,*) ' fheat_res : ', fheat_res(ji,jj) 
-               !WRITE(numout,*) ' fhbri     : ', fhbri(ji,jj) 
                !
                !CALL lim_prt_state( kt, ji, jj, 2, '   ')
@@ -672,5 +661,5 @@
       !!                n : number of the option
       !!-------------------------------------------------------------------
-      INTEGER         , INTENT(in) ::   kt      ! ocean time step
+      INTEGER         , INTENT(in) ::   kt            ! ocean time step
       INTEGER         , INTENT(in) ::   ki, kj, kn    ! ocean gridpoint indices
       CHARACTER(len=*), INTENT(in) ::   cd1           !
@@ -759,5 +748,5 @@
                WRITE(numout,*) ' strength      : ', strength(ji,jj)
                WRITE(numout,*) ' d_u_ice_dyn   : ', d_u_ice_dyn(ji,jj), ' d_v_ice_dyn   : ', d_v_ice_dyn(ji,jj)
-               WRITE(numout,*) ' old_u_ice     : ', old_u_ice(ji,jj)  , ' old_v_ice     : ', old_v_ice(ji,jj)  
+               WRITE(numout,*) ' u_ice_b       : ', u_ice_b(ji,jj)    , ' v_ice_b       : ', v_ice_b(ji,jj)  
                WRITE(numout,*)
                
@@ -769,19 +758,19 @@
                   WRITE(numout,*) ' t_su       : ', t_su(ji,jj,jl)             , ' t_s        : ', t_s(ji,jj,1,jl)
                   WRITE(numout,*) ' sm_i       : ', sm_i(ji,jj,jl)             , ' o_i        : ', o_i(ji,jj,jl)
-                  WRITE(numout,*) ' a_i        : ', a_i(ji,jj,jl)              , ' old_a_i    : ', old_a_i(ji,jj,jl)   
+                  WRITE(numout,*) ' a_i        : ', a_i(ji,jj,jl)              , ' a_i_b      : ', a_i_b(ji,jj,jl)   
                   WRITE(numout,*) ' d_a_i_trp  : ', d_a_i_trp(ji,jj,jl)        , ' d_a_i_thd  : ', d_a_i_thd(ji,jj,jl) 
-                  WRITE(numout,*) ' v_i        : ', v_i(ji,jj,jl)              , ' old_v_i    : ', old_v_i(ji,jj,jl)   
+                  WRITE(numout,*) ' v_i        : ', v_i(ji,jj,jl)              , ' v_i_b      : ', v_i_b(ji,jj,jl)   
                   WRITE(numout,*) ' d_v_i_trp  : ', d_v_i_trp(ji,jj,jl)        , ' d_v_i_thd  : ', d_v_i_thd(ji,jj,jl) 
-                  WRITE(numout,*) ' v_s        : ', v_s(ji,jj,jl)              , ' old_v_s    : ', old_v_s(ji,jj,jl)  
+                  WRITE(numout,*) ' v_s        : ', v_s(ji,jj,jl)              , ' v_s_b      : ', v_s_b(ji,jj,jl)  
                   WRITE(numout,*) ' d_v_s_trp  : ', d_v_s_trp(ji,jj,jl)        , ' d_v_s_thd  : ', d_v_s_thd(ji,jj,jl)
-                  WRITE(numout,*) ' e_i1       : ', e_i(ji,jj,1,jl)/1.0e9      , ' old_ei1    : ', old_e_i(ji,jj,1,jl)/1.0e9 
+                  WRITE(numout,*) ' e_i1       : ', e_i(ji,jj,1,jl)/1.0e9      , ' ei1        : ', e_i_b(ji,jj,1,jl)/1.0e9 
                   WRITE(numout,*) ' de_i1_trp  : ', d_e_i_trp(ji,jj,1,jl)/1.0e9, ' de_i1_thd  : ', d_e_i_thd(ji,jj,1,jl)/1.0e9
-                  WRITE(numout,*) ' e_i2       : ', e_i(ji,jj,2,jl)/1.0e9      , ' old_ei2    : ', old_e_i(ji,jj,2,jl)/1.0e9  
+                  WRITE(numout,*) ' e_i2       : ', e_i(ji,jj,2,jl)/1.0e9      , ' ei2_b      : ', e_i_b(ji,jj,2,jl)/1.0e9  
                   WRITE(numout,*) ' de_i2_trp  : ', d_e_i_trp(ji,jj,2,jl)/1.0e9, ' de_i2_thd  : ', d_e_i_thd(ji,jj,2,jl)/1.0e9
-                  WRITE(numout,*) ' e_snow     : ', e_s(ji,jj,1,jl)            , ' old_e_snow : ', old_e_s(ji,jj,1,jl) 
+                  WRITE(numout,*) ' e_snow     : ', e_s(ji,jj,1,jl)            , ' e_snow_b   : ', e_s_b(ji,jj,1,jl) 
                   WRITE(numout,*) ' d_e_s_trp  : ', d_e_s_trp(ji,jj,1,jl)      , ' d_e_s_thd  : ', d_e_s_thd(ji,jj,1,jl)
-                  WRITE(numout,*) ' smv_i      : ', smv_i(ji,jj,jl)            , ' old_smv_i  : ', old_smv_i(ji,jj,jl)   
+                  WRITE(numout,*) ' smv_i      : ', smv_i(ji,jj,jl)            , ' smv_i_b    : ', smv_i_b(ji,jj,jl)   
                   WRITE(numout,*) ' d_smv_i_trp: ', d_smv_i_trp(ji,jj,jl)      , ' d_smv_i_thd: ', d_smv_i_thd(ji,jj,jl) 
-                  WRITE(numout,*) ' oa_i       : ', oa_i(ji,jj,jl)             , ' old_oa_i   : ', old_oa_i(ji,jj,jl)
+                  WRITE(numout,*) ' oa_i       : ', oa_i(ji,jj,jl)             , ' oa_i_b     : ', oa_i_b(ji,jj,jl)
                   WRITE(numout,*) ' d_oa_i_trp : ', d_oa_i_trp(ji,jj,jl)       , ' d_oa_i_thd : ', d_oa_i_thd(ji,jj,jl)
                END DO !jl
@@ -790,14 +779,8 @@
                WRITE(numout,*) ' - Heat / FW fluxes '
                WRITE(numout,*) '   ~~~~~~~~~~~~~~~~ '
-               WRITE(numout,*) ' emp        : ', emp      (ji,jj)
-               WRITE(numout,*) ' sfx        : ', sfx      (ji,jj)
-               WRITE(numout,*) ' sfx_thd    : ', sfx_thd(ji,jj)
-               WRITE(numout,*) ' sfx_bri    : ', sfx_bri  (ji,jj)
-               WRITE(numout,*) ' sfx_mec    : ', sfx_mec  (ji,jj)
-               WRITE(numout,*) ' sfx_res    : ', sfx_res(ji,jj)
-               WRITE(numout,*) ' fmmec      : ', fmmec    (ji,jj)
-               WRITE(numout,*) ' fhmec      : ', fhmec    (ji,jj)
-               WRITE(numout,*) ' fhbri      : ', fhbri    (ji,jj)
-               WRITE(numout,*) ' fheat_mec  : ', fheat_mec(ji,jj)
+               WRITE(numout,*) ' - Heat fluxes in and out the ice ***'
+               WRITE(numout,*) ' qsr_ini       : ', pfrld(ji,jj) * qsr(ji,jj) + SUM( a_i_b(ji,jj,:) * qsr_ice(ji,jj,:) )
+               WRITE(numout,*) ' qns_ini       : ', pfrld(ji,jj) * qns(ji,jj) + SUM( a_i_b(ji,jj,:) * qns_ice(ji,jj,:) )
+               WRITE(numout,*)
                WRITE(numout,*) 
                WRITE(numout,*) ' sst        : ', sst_m(ji,jj)  
@@ -829,27 +812,65 @@
                WRITE(numout,*) ' qsr       : ', qsr(ji,jj)
                WRITE(numout,*) ' qns       : ', qns(ji,jj)
-               WRITE(numout,*) ' fdtcn     : ', fdtcn(ji,jj)
-               WRITE(numout,*) ' qcmif     : ', qcmif(ji,jj) * r1_rdtice
-               WRITE(numout,*) ' qldif     : ', qldif(ji,jj) * r1_rdtice
+               WRITE(numout,*)
+               WRITE(numout,*) ' hfx_mass     : ', hfx_thd(ji,jj) + hfx_dyn(ji,jj) + hfx_snw(ji,jj) + hfx_res(ji,jj)
+               WRITE(numout,*) ' hfx_in       : ', hfx_in(ji,jj)
+               WRITE(numout,*) ' hfx_out      : ', hfx_out(ji,jj)
+               WRITE(numout,*) ' dhc          : ', diag_heat_dhc(ji,jj)              
+               WRITE(numout,*)
+               WRITE(numout,*) ' hfx_dyn      : ', hfx_dyn(ji,jj)
+               WRITE(numout,*) ' hfx_thd      : ', hfx_thd(ji,jj)
+               WRITE(numout,*) ' hfx_res      : ', hfx_res(ji,jj)
+               WRITE(numout,*) ' fhtur        : ', fhtur(ji,jj) 
+               WRITE(numout,*) ' qlead        : ', qlead(ji,jj) * r1_rdtice
                WRITE(numout,*)
                WRITE(numout,*) ' - Salt fluxes at bottom interface ***'
                WRITE(numout,*) ' emp       : ', emp    (ji,jj)
-               WRITE(numout,*) ' sfx_bri   : ', sfx_bri(ji,jj)
                WRITE(numout,*) ' sfx       : ', sfx    (ji,jj)
                WRITE(numout,*) ' sfx_res   : ', sfx_res(ji,jj)
-               WRITE(numout,*) ' sfx_mec   : ', sfx_mec(ji,jj)
-               WRITE(numout,*) ' - Heat fluxes at bottom interface ***'
-               WRITE(numout,*) ' fheat_res : ', fheat_res(ji,jj)
+               WRITE(numout,*) ' sfx_bri   : ', sfx_bri(ji,jj)
+               WRITE(numout,*) ' sfx_dyn   : ', sfx_dyn(ji,jj)
                WRITE(numout,*)
                WRITE(numout,*) ' - Momentum fluxes '
                WRITE(numout,*) ' utau      : ', utau(ji,jj) 
                WRITE(numout,*) ' vtau      : ', vtau(ji,jj)
-            ENDIF
+            ENDIF 
             WRITE(numout,*) ' '
             !
          END DO
       END DO
-
+      !
    END SUBROUTINE lim_prt_state
+   
+     
+   FUNCTION fice_cell_ave ( ptab )
+      !!--------------------------------------------------------------------------
+      !! * Compute average over categories, for grid cell (ice covered and free ocean)
+      !!--------------------------------------------------------------------------
+      REAL (wp), DIMENSION (jpi,jpj) :: fice_cell_ave
+      REAL (wp), DIMENSION (jpi,jpj,jpl), INTENT (in) :: ptab
+      INTEGER :: jl ! Dummy loop index
+      
+      fice_cell_ave (:,:) = 0.0_wp
+      
+      DO jl = 1, jpl
+         fice_cell_ave (:,:) = fice_cell_ave (:,:) &
+            &                  + a_i (:,:,jl) * ptab (:,:,jl)
+      END DO
+      
+   END FUNCTION fice_cell_ave
+   
+   
+   FUNCTION fice_ice_ave ( ptab )
+      !!--------------------------------------------------------------------------
+      !! * Compute average over categories, for ice covered part of grid cell
+      !!--------------------------------------------------------------------------
+      REAL (kind=wp), DIMENSION (jpi,jpj) :: fice_ice_ave
+      REAL (kind=wp), DIMENSION (jpi,jpj,jpl), INTENT(in) :: ptab
+
+      fice_ice_ave (:,:) = 0.0_wp
+      WHERE ( at_i (:,:) .GT. 0.0_wp ) fice_ice_ave (:,:) = fice_cell_ave ( ptab (:,:,:)) / at_i (:,:)
+
+   END FUNCTION fice_ice_ave
+
 
 #else
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim_2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim_2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcice_lim_2.F90	(revision 5075)
@@ -53,4 +53,8 @@
    USE agrif_lim2_update
 # endif
+
+#if defined key_bdy 
+   USE bdyice_lim       ! unstructured open boundary data  (bdy_ice_lim routine)
+#endif
 
    IMPLICIT NONE
@@ -93,10 +97,11 @@
       !!
       INTEGER  ::   ji, jj   ! dummy loop indices
-      REAL(wp), DIMENSION(:,:,:), POINTER :: zalb_ice_os   ! albedo of the ice under overcast sky
-      REAL(wp), DIMENSION(:,:,:), POINTER :: zalb_ice_cs   ! albedo of ice under clear sky
-      REAL(wp), DIMENSION(:,:,:), POINTER :: zsist         ! surface ice temperature (K)
+      REAL(wp), DIMENSION(:,:,:), POINTER :: zalb_os   ! ice albedo under overcast sky
+      REAL(wp), DIMENSION(:,:,:), POINTER :: zalb_cs   ! ice albedo under clear sky
+      REAL(wp), DIMENSION(:,:,:), POINTER :: zalb_ice  ! mean ice albedo
+      REAL(wp), DIMENSION(:,:,:), POINTER :: zsist     ! ice surface temperature (K)
       !!----------------------------------------------------------------------
 
-      CALL wrk_alloc( jpi,jpj,1, zalb_ice_os, zalb_ice_cs, zsist )
+      CALL wrk_alloc( jpi,jpj,1, zalb_os, zalb_cs, zalb_ice, zsist )
 
       IF( kt == nit000 ) THEN
@@ -126,6 +131,8 @@
             DO jj = 2, jpj
                DO ji = 2, jpi   ! NO vector opt. possible
-                  u_oce(ji,jj) = 0.5_wp * ( ssu_m(ji-1,jj  ) + ssu_m(ji-1,jj-1) ) * tmu(ji,jj)
-                  v_oce(ji,jj) = 0.5_wp * ( ssv_m(ji  ,jj-1) + ssv_m(ji-1,jj-1) ) * tmu(ji,jj)
+                  u_oce(ji,jj) = 0.5_wp * ( ssu_m(ji-1,jj  ) * umask(ji-1,jj  ,1) &
+                     &           + ssu_m(ji-1,jj-1) * umask(ji-1,jj-1,1) ) * tmu(ji,jj)
+                  v_oce(ji,jj) = 0.5_wp * ( ssv_m(ji  ,jj-1) * vmask(ji  ,jj-1,1) &
+                     &           + ssv_m(ji-1,jj-1) * vmask(ji-1,jj-1,1) ) * tmu(ji,jj)
                END DO
             END DO
@@ -134,18 +141,29 @@
             !
          CASE( 'C' )                  !== C-grid ice dynamics :   U & V-points (same as ocean)
-            u_oce(:,:) = ssu_m(:,:)                     ! mean surface ocean current at ice velocity point
-            v_oce(:,:) = ssv_m(:,:)
+            u_oce(:,:) = ssu_m(:,:) * umask(:,:,1)                     ! mean surface ocean current at ice velocity point
+            v_oce(:,:) = ssv_m(:,:) * vmask(:,:,1)
             !
          END SELECT
 
          ! ... masked sea surface freezing temperature [Kelvin] (set to rt0 over land)
-         tfu(:,:) = tfreez( sss_m ) +  rt0 
+         tfu(:,:) = eos_fzp( sss_m ) +  rt0 
 
          zsist (:,:,1) = sist (:,:) + rt0 * ( 1. - tmask(:,:,1) )
 
-         ! ... ice albedo (clear sky and overcast sky)
+         ! Ice albedo
+
          CALL albedo_ice( zsist, reshape( hicif, (/jpi,jpj,1/) ), &
                                  reshape( hsnif, (/jpi,jpj,1/) ), &
-                          zalb_ice_cs, zalb_ice_os )
+                          zalb_cs, zalb_os )
+
+         SELECT CASE( ksbc )
+         CASE( jp_core , jp_cpl )   ! CORE and COUPLED bulk formulations
+
+            ! albedo depends on cloud fraction because of non-linear spectral effects
+            zalb_ice(:,:,:) = ( 1. - cldf_ice ) * zalb_cs(:,:,:) + cldf_ice * zalb_os(:,:,:)
+            ! In CLIO the cloud fraction is read in the climatology and the all-sky albedo 
+            ! (zalb_ice) is computed within the bulk routine
+
+         END SELECT
 
          ! ... Sea-ice surface boundary conditions output from bulk formulae :
@@ -163,6 +181,6 @@
          !
          SELECT CASE( ksbc )
-         CASE( 3 )           ! CLIO bulk formulation
-            CALL blk_ice_clio( zsist, zalb_ice_cs, zalb_ice_os,                         &
+         CASE( jp_clio )           ! CLIO bulk formulation
+            CALL blk_ice_clio( zsist, zalb_cs    , zalb_os    , zalb_ice   ,            &
                &                      utau_ice   , vtau_ice   , qns_ice    , qsr_ice,   &
                &                      qla_ice    , dqns_ice   , dqla_ice   ,            &
@@ -170,13 +188,13 @@
                &                      fr1_i0     , fr2_i0     , cp_ice_msh , jpl  )
 
-         CASE( 4 )           ! CORE bulk formulation
-            CALL blk_ice_core( zsist, u_ice      , v_ice      , zalb_ice_cs,            &
+         CASE( jp_core )           ! CORE bulk formulation
+            CALL blk_ice_core( zsist, u_ice      , v_ice      , zalb_ice   ,            &
                &                      utau_ice   , vtau_ice   , qns_ice    , qsr_ice,   &
                &                      qla_ice    , dqns_ice   , dqla_ice   ,            &
                &                      tprecip    , sprecip    ,                         &
                &                      fr1_i0     , fr2_i0     , cp_ice_msh , jpl  )
-            IF( ltrcdm2dc_ice )   CALL blk_ice_meanqsr( zalb_ice_cs, qsr_ice_mean, jpl )
-
-         CASE( 5 )           ! Coupled formulation : atmosphere-ice stress only (fluxes provided after ice dynamics)
+            IF( ltrcdm2dc_ice )   CALL blk_ice_meanqsr( zalb_ice, qsr_ice_mean, jpl )
+
+         CASE( jp_cpl )            ! Coupled formulation : atmosphere-ice stress only (fluxes provided after ice dynamics)
             CALL sbc_cpl_ice_tau( utau_ice , vtau_ice )
          END SELECT
@@ -205,15 +223,16 @@
                            CALL lim_trp_2      ( kt )      ! Ice transport   ( Advection/diffusion )
            IF( ln_limdmp ) CALL lim_dmp_2      ( kt )      ! Ice damping 
+#if defined key_bdy
+                           CALL bdy_ice_lim( kt ) ! bdy ice thermo
+#endif
          END IF
-#if defined key_coupled
          !                                             ! Ice surface fluxes in coupled mode 
-         IF( ksbc == 5 )   THEN
+         IF( ksbc == jp_cpl )   THEN
             a_i(:,:,1)=fr_i
             CALL sbc_cpl_ice_flx( frld,                                              &
             !                                optional arguments, used only in 'mixed oce-ice' case
-            &                                             palbi = zalb_ice_cs, psst = sst_m, pist = zsist )
+            &                                             palbi = zalb_ice, psst = sst_m, pist = zsist )
             sprecip(:,:) = - emp_ice(:,:)   ! Ugly patch, WARNING, in coupled mode, sublimation included in snow (parsub = 0.)
          ENDIF
-#endif
                            CALL lim_thd_2      ( kt )      ! Ice thermodynamics 
                            CALL lim_sbc_flx_2  ( kt )      ! update surface ocean mass, heat & salt fluxes 
@@ -245,5 +264,5 @@
       IF( ln_limdyn    )   CALL lim_sbc_tau_2( kt, ub(:,:,1), vb(:,:,1) )  ! using before instantaneous surf. currents
       !
-      CALL wrk_dealloc( jpi,jpj,1, zalb_ice_os, zalb_ice_cs, zsist )
+      CALL wrk_dealloc( jpi,jpj,1, zalb_os, zalb_cs, zalb_ice, zsist )
       !
    END SUBROUTINE sbc_ice_lim_2
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcisf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcisf.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcisf.F90	(revision 5075)
@@ -0,0 +1,904 @@
+MODULE sbcisf
+   !!======================================================================
+   !!                       ***  MODULE  sbcisf  ***
+   !! Surface module :  update surface ocean boundary condition under ice
+   !!                   shelf
+   !!======================================================================
+   !! History :  3.2   !  2011-02  (C.Harris  ) Original code isf cav
+   !!            X.X   !  2006-02  (C. Wang   ) Original code bg03
+   !!            3.4   !  2013-03  (P. Mathiot) Merging
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   sbc_isf        : update sbc under ice shelf
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers
+   USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
+   USE eosbn2          ! equation of state
+   USE sbc_oce         ! surface boundary condition: ocean fields
+   USE lbclnk          !
+   USE iom             ! I/O manager library
+   USE in_out_manager  ! I/O manager
+   USE wrk_nemo        ! Memory allocation
+   USE timing          ! Timing
+   USE lib_fortran     ! glob_sum
+   USE zdfbfr
+   USE fldread         ! read input field at current time step
+
+
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   sbc_isf, sbc_isf_div, sbc_isf_alloc  ! routine called in sbcmod and divcur
+
+   ! public in order to be able to output then 
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   risf_tsc_b, risf_tsc   
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fwfisf_b, fwfisf  !: evaporation damping   [kg/m2/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   qisf            !: net heat flux from ice shelf
+   REAL(wp), PUBLIC ::   rn_hisf_tbl                 !: thickness of top boundary layer [m]
+   LOGICAL , PUBLIC ::   ln_divisf                   !: flag to correct divergence 
+   INTEGER , PUBLIC ::   nn_isfblk                   !: 
+   INTEGER , PUBLIC ::   nn_gammablk                 !:
+   LOGICAL , PUBLIC ::   ln_conserve                 !:
+   REAL(wp), PUBLIC ::   rn_gammat0                  !: temperature exchange coeficient
+   REAL(wp), PUBLIC ::   rn_gammas0                  !: salinity    exchange coeficient 
+   REAL(wp), PUBLIC ::   rdivisf                     !: flag to test if fwf apply on divergence
+
+   REAL(wp)   , PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  rzisf_tbl              !:depth of calving front (shallowest point) nn_isf ==2/3
+   REAL(wp)   , PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  rhisf_tbl, rhisf_tbl_0 !:thickness of tbl
+   REAL(wp)   , PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  r1_hisf_tbl            !:1/thickness of tbl
+   REAL(wp)   , PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  ralpha                 !:proportion of bottom cell influenced by tbl 
+   REAL(wp)   , PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  risfLeff               !:effective length (Leff) BG03 nn_isf==2
+   REAL(wp)   , PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  ttbl, stbl, utbl, vtbl !:top boundary layer variable at T point
+#if defined key_agrif
+   ! AGRIF can not handle these arrays as integers. The reason is a mystery but problems avoided by declaring them as reals
+   REAL(wp),    PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  misfkt, misfkb         !:Level of ice shelf base
+                                                                                          !: (first wet level and last level include in the tbl)
+#else
+   INTEGER,    PUBLIC, ALLOCATABLE, SAVE, DIMENSION (:,:)     ::  misfkt, misfkb         !:Level of ice shelf base
+#endif
+
+
+   REAL(wp), PUBLIC, SAVE ::   rcpi   = 2000.0_wp     ! phycst ?
+   REAL(wp), PUBLIC, SAVE ::   kappa  = 1.54e-6_wp    ! phycst ?
+   REAL(wp), PUBLIC, SAVE ::   rhoisf = 920.0_wp      ! phycst ?
+   REAL(wp), PUBLIC, SAVE ::   tsurf  = -20.0_wp      ! phycst ?
+   REAL(wp), PUBLIC, SAVE ::   lfusisf= 0.334e6_wp    ! phycst ?
+
+!: Variable used in fldread to read the forcing file (nn_isf == 4 .OR. nn_isf == 3)
+   CHARACTER(len=100), PUBLIC ::   cn_dirisf  = './'    !: Root directory for location of ssr files
+   TYPE(FLD_N)       , PUBLIC ::   sn_qisf, sn_fwfisf     !: information about the runoff file to be read
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_qisf, sf_fwfisf
+   TYPE(FLD_N)       , PUBLIC ::   sn_rnfisf              !: information about the runoff file to be read
+   TYPE(FLD), ALLOCATABLE, DIMENSION(:) ::   sf_rnfisf           
+   TYPE(FLD_N)       , PUBLIC ::   sn_depmax_isf, sn_depmin_isf, sn_Leff_isf     !: information about the runoff file to be read
+   
+   !! * Substitutions
+#  include "domzgr_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.0 , LOCEAN-IPSL (2008)
+   !! $Id: sbcice_if.F90 1730 2009-11-16 14:34:19Z smasson $
+   !! Software governed by the CeCILL licence (modipsl/doc/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+ 
+  SUBROUTINE sbc_isf(kt)
+    INTEGER, INTENT(in)          ::   kt         ! ocean time step
+    INTEGER                      ::   ji, jj, jk, ijkmin, inum, ierror
+    INTEGER                      ::   ikt, ikb   ! top and bottom level of the isf boundary layer
+    REAL(wp)                     ::   rmin
+    REAL(wp)                     ::   zhk
+    CHARACTER(len=256)           ::   cfisf, cvarzisf, cvarhisf   ! name for isf file
+    CHARACTER(LEN=256)           :: cnameis                     ! name of iceshelf file
+    CHARACTER (LEN=32)           :: cvarLeff                    ! variable name for efficient Length scale
+    INTEGER           ::   ios           ! Local integer output status for namelist read
+      !
+      !!---------------------------------------------------------------------
+      NAMELIST/namsbc_isf/ nn_isfblk, rn_hisf_tbl, ln_divisf, ln_conserve, rn_gammat0, rn_gammas0, nn_gammablk, &
+                         & sn_fwfisf, sn_qisf, sn_rnfisf, sn_depmax_isf, sn_depmin_isf, sn_Leff_isf
+      !
+      !
+      !                                         ! ====================== !
+      IF( kt == nit000 ) THEN                   !  First call kt=nit000  !
+         !                                      ! ====================== !
+         REWIND( numnam_ref )              ! Namelist namsbc_rnf in reference namelist : Runoffs 
+         READ  ( numnam_ref, namsbc_isf, IOSTAT = ios, ERR = 901)
+901      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namsbc_isf in reference namelist', lwp )
+
+         REWIND( numnam_cfg )              ! Namelist namsbc_rnf in configuration namelist : Runoffs
+         READ  ( numnam_cfg, namsbc_isf, IOSTAT = ios, ERR = 902 )
+902      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namsbc_isf in configuration namelist', lwp )
+         IF(lwm) WRITE ( numond, namsbc_isf )
+
+
+         IF ( lwp ) WRITE(numout,*)
+         IF ( lwp ) WRITE(numout,*) 'sbc_isf: heat flux of the ice shelf'
+         IF ( lwp ) WRITE(numout,*) '~~~~~~~~~'
+         IF ( lwp ) WRITE(numout,*) 'sbcisf :' 
+         IF ( lwp ) WRITE(numout,*) '~~~~~~~~'
+         IF ( lwp ) WRITE(numout,*) '        nn_isf      = ', nn_isf
+         IF ( lwp ) WRITE(numout,*) '        nn_isfblk   = ', nn_isfblk
+         IF ( lwp ) WRITE(numout,*) '        rn_hisf_tbl = ', rn_hisf_tbl
+         IF ( lwp ) WRITE(numout,*) '        ln_divisf   = ', ln_divisf 
+         IF ( lwp ) WRITE(numout,*) '        nn_gammablk = ', nn_gammablk 
+         IF ( lwp ) WRITE(numout,*) '        rn_tfri2    = ', rn_tfri2 
+         IF (ln_divisf) THEN       ! keep it in the namelist ??? used true anyway as for runoff ? (PM)
+            rdivisf = 1._wp
+         ELSE
+            rdivisf = 0._wp
+         END IF
+         !
+         ! Allocate public variable
+         IF ( sbc_isf_alloc()  /= 0 )         CALL ctl_stop( 'STOP', 'sbc_isf : unable to allocate arrays' )
+         !
+         ! initialisation
+         qisf(:,:)        = 0._wp  ; fwfisf(:,:) = 0._wp
+         risf_tsc(:,:,:)  = 0._wp
+         !
+         ! define isf tbl tickness, top and bottom indice
+         IF      (nn_isf == 1) THEN
+            rhisf_tbl(:,:) = rn_hisf_tbl
+            misfkt(:,:)    = mikt(:,:)         ! same indice for bg03 et cav => used in isfdiv
+         ELSE IF ((nn_isf == 3) .OR. (nn_isf == 2)) THEN
+            ALLOCATE( sf_rnfisf(1), STAT=ierror )
+            ALLOCATE( sf_rnfisf(1)%fnow(jpi,jpj,1), sf_rnfisf(1)%fdta(jpi,jpj,1,2) )
+            CALL fld_fill( sf_rnfisf, (/ sn_rnfisf /), cn_dirisf, 'sbc_isf_init', 'read fresh water flux isf data', 'namsbc_isf' )
+
+            !: read effective lenght (BG03)
+            IF (nn_isf == 2) THEN
+               ! Read Data and save some integral values
+               CALL iom_open( sn_Leff_isf%clname, inum )
+               cvarLeff  = 'soLeff'               !: variable name for Efficient Length scale
+               CALL iom_get( inum, jpdom_data, cvarLeff, risfLeff , 1)
+               CALL iom_close(inum)
+               !
+               risfLeff = risfLeff*1000           !: convertion in m
+            END IF
+
+           ! read depth of the top and bottom of the isf top boundary layer (in this case, isf front depth and grounding line depth)
+            CALL iom_open( sn_depmax_isf%clname, inum )
+            cvarhisf = TRIM(sn_depmax_isf%clvar)
+            CALL iom_get( inum, jpdom_data, cvarhisf, rhisf_tbl, 1) !: depth of deepest point of the ice shelf base
+            CALL iom_close(inum)
+            !
+            CALL iom_open( sn_depmin_isf%clname, inum )
+            cvarzisf = TRIM(sn_depmin_isf%clvar)
+            CALL iom_get( inum, jpdom_data, cvarzisf, rzisf_tbl, 1) !: depth of shallowest point of the ice shelves base
+            CALL iom_close(inum)
+            !
+            rhisf_tbl(:,:) = rhisf_tbl(:,:) - rzisf_tbl(:,:)        !: tickness isf boundary layer
+
+           !! compute first level of the top boundary layer
+           DO ji = 1, jpi
+              DO jj = 1, jpj
+                  jk = 2
+                  DO WHILE ( jk .LE. mbkt(ji,jj) .AND. fsdepw(ji,jj,jk) < rzisf_tbl(ji,jj) ) ;  jk = jk + 1 ;  END DO
+                  misfkt(ji,jj) = jk-1
+               END DO
+            END DO
+
+         ELSE IF ( nn_isf == 4 ) THEN
+            ! as in nn_isf == 1
+            rhisf_tbl(:,:) = rn_hisf_tbl
+            misfkt(:,:)    = mikt(:,:)         ! same indice for bg03 et cav => used in isfdiv
+            
+            ! load variable used in fldread (use for temporal interpolation of isf fwf forcing)
+            ALLOCATE( sf_fwfisf(1), sf_qisf(1), STAT=ierror )
+            ALLOCATE( sf_fwfisf(1)%fnow(jpi,jpj,1), sf_fwfisf(1)%fdta(jpi,jpj,1,2) )
+            ALLOCATE( sf_qisf(1)%fnow(jpi,jpj,1), sf_qisf(1)%fdta(jpi,jpj,1,2) )
+            CALL fld_fill( sf_fwfisf, (/ sn_fwfisf /), cn_dirisf, 'sbc_isf_init', 'read fresh water flux isf data', 'namsbc_isf' )
+            !CALL fld_fill( sf_qisf  , (/ sn_qisf   /), cn_dirisf, 'sbc_isf_init', 'read heat flux isf data'       , 'namsbc_isf' )
+         END IF
+         
+         rhisf_tbl_0(:,:) = rhisf_tbl(:,:)
+
+         ! compute bottom level of isf tbl and thickness of tbl below the ice shelf
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               ikt = misfkt(ji,jj)
+               ikb = misfkt(ji,jj)
+               ! thickness of boundary layer at least the top level thickness
+               rhisf_tbl(ji,jj) = MAX(rhisf_tbl_0(ji,jj), fse3t_n(ji,jj,ikt))
+
+               ! determine the deepest level influenced by the boundary layer
+               ! test on tmask useless ?????
+               DO jk = ikt, mbkt(ji,jj)
+                  IF ( (SUM(fse3t_n(ji,jj,ikt:jk-1)) .LT. rhisf_tbl(ji,jj)) .AND. (tmask(ji,jj,jk) == 1) ) ikb = jk
+               END DO
+               rhisf_tbl(ji,jj) = MIN(rhisf_tbl(ji,jj), SUM(fse3t_n(ji,jj,ikt:ikb)))  ! limit the tbl to water thickness.
+               misfkb(ji,jj) = ikb                                                  ! last wet level of the tbl
+               r1_hisf_tbl(ji,jj) = 1._wp / rhisf_tbl(ji,jj)
+
+               zhk           = SUM( fse3t(ji, jj, ikt:ikb - 1)) * r1_hisf_tbl(ji,jj)  ! proportion of tbl cover by cell from ikt to ikb - 1
+               ralpha(ji,jj) = rhisf_tbl(ji,jj) * (1._wp - zhk ) / fse3t(ji,jj,ikb)  ! proportion of bottom cell influenced by boundary layer
+            END DO
+         END DO
+         
+      END IF
+
+      !                                            ! ---------------------------------------- !
+      IF( kt /= nit000 ) THEN                      !          Swap of forcing fields          !
+         !                                         ! ---------------------------------------- !
+         fwfisf_b  (:,:  ) = fwfisf  (:,:  )               ! Swap the ocean forcing fields except at nit000
+         risf_tsc_b(:,:,:) = risf_tsc(:,:,:)               ! where before fields are set at the end of the routine
+         !
+      ENDIF
+
+      IF( MOD( kt-1, nn_fsbc) == 0 ) THEN
+
+
+         ! compute salf and heat flux
+         IF (nn_isf == 1) THEN
+            ! realistic ice shelf formulation
+            ! compute T/S/U/V for the top boundary layer
+            CALL sbc_isf_tbl(tsn(:,:,:,jp_tem),ttbl(:,:),'T')
+            CALL sbc_isf_tbl(tsn(:,:,:,jp_sal),stbl(:,:),'T')
+            CALL sbc_isf_tbl(un(:,:,:),utbl(:,:),'U')
+            CALL sbc_isf_tbl(vn(:,:,:),vtbl(:,:),'V')
+            ! iom print
+            CALL iom_put('ttbl',ttbl(:,:))
+            CALL iom_put('stbl',stbl(:,:))
+            CALL iom_put('utbl',utbl(:,:))
+            CALL iom_put('vtbl',vtbl(:,:))
+            ! compute fwf and heat flux
+            CALL sbc_isf_cav (kt)
+
+         ELSE IF (nn_isf == 2) THEN
+            ! Beckmann and Goosse parametrisation 
+            stbl(:,:)   = soce
+            CALL sbc_isf_bg03(kt)
+
+         ELSE IF (nn_isf == 3) THEN
+            ! specified runoff in depth (Mathiot et al., XXXX in preparation)
+            CALL fld_read ( kt, nn_fsbc, sf_rnfisf   )
+            fwfisf(:,:) = - sf_rnfisf(1)%fnow(:,:,1)         ! fresh water flux from the isf (fwfisf <0 mean melting) 
+            qisf(:,:)   = fwfisf(:,:) * lfusisf              ! heat        flux
+            stbl(:,:)   = soce
+
+         ELSE IF (nn_isf == 4) THEN
+            ! specified fwf and heat flux forcing beneath the ice shelf
+            CALL fld_read ( kt, nn_fsbc, sf_fwfisf   )
+            !CALL fld_read ( kt, nn_fsbc, sf_qisf   )
+            fwfisf(:,:) = sf_fwfisf(1)%fnow(:,:,1)            ! fwf
+            qisf(:,:)   = fwfisf(:,:) * lfusisf              ! heat        flux
+            !qisf(:,:)   = sf_qisf(1)%fnow(:,:,1)              ! heat flux
+            stbl(:,:)   = soce
+
+         END IF
+         ! compute tsc due to isf
+         ! WARNING water add at temp = 0C, correction term is added in trasbc, maybe better here but need a 3D variable).
+         risf_tsc(:,:,jp_tem) = qisf(:,:) * r1_rau0_rcp !
+         
+         ! salt effect already take into account in vertical advection
+         risf_tsc(:,:,jp_sal) = (1.0_wp-rdivisf) * fwfisf(:,:) * stbl(:,:) * r1_rau0
+          
+         ! lbclnk
+         CALL lbc_lnk(risf_tsc(:,:,jp_tem),'T',1.)
+         CALL lbc_lnk(risf_tsc(:,:,jp_sal),'T',1.)
+         CALL lbc_lnk(fwfisf(:,:)   ,'T',1.)
+         CALL lbc_lnk(qisf(:,:)     ,'T',1.)
+
+         IF( kt == nit000 ) THEN                          !   set the forcing field at nit000 - 1    !
+            IF( ln_rstart .AND.    &                     ! Restart: read in restart file
+                 & iom_varid( numror, 'fwf_isf_b', ldstop = .FALSE. ) > 0 ) THEN
+               IF(lwp) WRITE(numout,*) '          nit000-1 isf tracer content forcing fields read in the restart file'
+               CALL iom_get( numror, jpdom_autoglo, 'fwf_isf_b', fwfisf_b(:,:) )   ! before salt content isf_tsc trend
+               CALL iom_get( numror, jpdom_autoglo, 'isf_sc_b', risf_tsc_b(:,:,jp_sal) )   ! before salt content isf_tsc trend
+               CALL iom_get( numror, jpdom_autoglo, 'isf_hc_b', risf_tsc_b(:,:,jp_tem) )   ! before salt content isf_tsc trend
+            ELSE
+               fwfisf_b(:,:)    = fwfisf(:,:)
+               risf_tsc_b(:,:,:)= risf_tsc(:,:,:)
+            END IF
+         ENDIF
+         ! 
+         ! output
+         CALL iom_put('qisf'  , qisf)
+         IF( iom_use('fwfisf') )   CALL iom_put('fwfisf', fwfisf * stbl(:,:) / soce )
+      END IF
+  
+  END SUBROUTINE sbc_isf
+
+  INTEGER FUNCTION sbc_isf_alloc()
+      !!----------------------------------------------------------------------
+      !!               ***  FUNCTION sbc_isf_rnf_alloc  ***
+      !!----------------------------------------------------------------------
+      sbc_isf_alloc = 0       ! set to zero if no array to be allocated
+      IF( .NOT. ALLOCATED( qisf ) ) THEN
+         ALLOCATE(  risf_tsc(jpi,jpj,jpts), risf_tsc_b(jpi,jpj,jpts)              , &
+               &    qisf(jpi,jpj)     , fwfisf(jpi,jpj)     , fwfisf_b(jpi,jpj)   , &
+               &    rhisf_tbl(jpi,jpj), r1_hisf_tbl(jpi,jpj), rzisf_tbl(jpi,jpj)  , &
+               &    ttbl(jpi,jpj)     , stbl(jpi,jpj)       , utbl(jpi,jpj)       , &
+               &    vtbl(jpi, jpj)    , risfLeff(jpi,jpj)   , rhisf_tbl_0(jpi,jpj), &
+               &    ralpha(jpi,jpj)   , misfkt(jpi,jpj)     , misfkb(jpi,jpj)     , &
+               &    STAT= sbc_isf_alloc )
+         !
+         IF( lk_mpp                  )   CALL mpp_sum ( sbc_isf_alloc )
+         IF( sbc_isf_alloc /= 0 )   CALL ctl_warn('sbc_isf_alloc: failed to allocate arrays.')
+         !
+      ENDIF
+  END FUNCTION
+
+  SUBROUTINE sbc_isf_bg03(kt)
+   !!==========================================================================
+   !!                 *** SUBROUTINE sbcisf_bg03  ***
+   !! add net heat and fresh water flux from ice shelf melting
+   !! into the adjacent ocean using the parameterisation by
+   !! Beckmann and Goosse (2003), "A parameterization of ice shelf-ocean
+   !!     interaction for climate models", Ocean Modelling 5(2003) 157-170.
+   !!  (hereafter BG)
+   !!==========================================================================
+   !!----------------------------------------------------------------------
+   !!   sbc_isf_bg03      : routine called from sbcmod
+   !!----------------------------------------------------------------------
+   !!
+   !! ** Purpose   :   Add heat and fresh water fluxes due to ice shelf melting
+   !! ** Reference :   Beckmann et Goosse, 2003, Ocean Modelling
+   !!
+   !! History :
+   !!      !  06-02  (C. Wang) Original code
+   !!----------------------------------------------------------------------
+
+    INTEGER, INTENT ( in ) :: kt
+
+    INTEGER :: ji, jj, jk, jish  !temporary integer
+    INTEGER :: ijkmin
+    INTEGER :: ii, ij, ik 
+    INTEGER :: inum
+
+    REAL(wp) :: zt_sum      ! sum of the temperature between 200m and 600m
+    REAL(wp) :: zt_ave      ! averaged temperature between 200m and 600m
+    REAL(wp) :: zt_frz      ! freezing point temperature at depth z
+    REAL(wp) :: zpress      ! pressure to compute the freezing point in depth
+    
+    !!----------------------------------------------------------------------
+    IF ( nn_timing == 1 ) CALL timing_start('sbc_isf_bg03')
+     !
+
+    ! This test is false only in the very first time step of a run (JMM ???- Initialy build to skip 1rst year of run )
+    DO ji = 1, jpi
+       DO jj = 1, jpj
+          ik = misfkt(ji,jj)
+          !! Initialize arrays to 0 (each step)
+          zt_sum = 0.e0_wp
+          IF ( ik .GT. 1 ) THEN
+    ! 3. -----------the average temperature between 200m and 600m ---------------------
+             DO jk = misfkt(ji,jj),misfkb(ji,jj)
+             ! freezing point temperature  at ice shelf base BG eq. 2 (JMM sign pb ??? +7.64e-4 !!!)
+             ! after verif with UNESCO, wrong sign in BG eq. 2
+             ! Calculate freezing temperature
+                zpress = grav*rau0*fsdept(ji,jj,ik)*1.e-04 
+                zt_frz = eos_fzp(tsb(ji,jj,ik,jp_sal), zpress) 
+                zt_sum = zt_sum + (tsn(ji,jj,ik,jp_tem)-zt_frz) * fse3t(ji,jj,ik) * tmask(ji,jj,ik)  ! sum temp
+             ENDDO
+             zt_ave = zt_sum/rhisf_tbl(ji,jj) ! calcul mean value
+    
+    ! 4. ------------Net heat flux and fresh water flux due to the ice shelf
+          ! For those corresponding to zonal boundary    
+             qisf(ji,jj) = - rau0 * rcp * rn_gammat0 * risfLeff(ji,jj) * e1t(ji,jj) * zt_ave  &
+                         & / (e1t(ji,jj) * e2t(ji,jj)) * tmask(ji,jj,ik) 
+             
+             fwfisf(ji,jj) = qisf(ji,jj) / lfusisf          !fresh water flux kg/(m2s)                  
+             fwfisf(ji,jj) = fwfisf(ji,jj) * ( soce / stbl(ji,jj) )
+             !add to salinity trend
+          ELSE
+             qisf(ji,jj) = 0._wp ; fwfisf(ji,jj) = 0._wp
+          END IF
+       ENDDO
+    ENDDO
+    !
+    IF( nn_timing == 1 )  CALL timing_stop('sbc_isf_bg03')
+  END SUBROUTINE sbc_isf_bg03
+
+   SUBROUTINE sbc_isf_cav( kt )
+      !!---------------------------------------------------------------------
+      !!                     ***  ROUTINE sbc_isf_cav  ***
+      !!
+      !! ** Purpose :   handle surface boundary condition under ice shelf
+      !!
+      !! ** Method  : -
+      !!
+      !! ** Action  :   utau, vtau : remain unchanged
+      !!                taum, wndm : remain unchanged
+      !!                qns        : update heat flux below ice shelf
+      !!                emp, emps  : update freshwater flux below ice shelf
+      !!---------------------------------------------------------------------
+      INTEGER, INTENT(in)          ::   kt         ! ocean time step
+      !
+      LOGICAL :: ln_isomip = .true.
+      REAL(wp), DIMENSION(:,:), POINTER       ::   zfrz,zpress,zti
+      REAL(wp), DIMENSION(:,:), POINTER       ::   zgammat2d, zgammas2d 
+      !REAL(wp), DIMENSION(:,:), POINTER ::   zqisf, zfwfisf
+      REAL(wp) ::   zlamb1, zlamb2, zlamb3
+      REAL(wp) ::   zeps1,zeps2,zeps3,zeps4,zeps6,zeps7
+      REAL(wp) ::   zaqe,zbqe,zcqe,zaqer,zdis,zsfrz,zcfac
+      REAL(wp) ::   zfwflx, zhtflx, zhtflx_b
+      REAL(wp) ::   zgammat, zgammas
+      REAL(wp) ::   zeps   =  -1.e-20_wp        !==   Local constant initialization   ==!
+      INTEGER  ::   ji, jj     ! dummy loop indices
+      INTEGER  ::   ii0, ii1, ij0, ij1   ! temporary integers
+      INTEGER  ::   ierror     ! return error code
+      LOGICAL  ::   lit=.TRUE.
+      INTEGER  ::   nit
+      !!---------------------------------------------------------------------
+      !
+      ! coeficient for linearisation of tfreez
+      zlamb1=-0.0575
+      zlamb2=0.0901
+      zlamb3=-7.61e-04
+      IF( nn_timing == 1 )  CALL timing_start('sbc_isf_cav')
+      !
+      CALL wrk_alloc( jpi,jpj, zfrz,zpress,zti, zgammat2d, zgammas2d )
+
+      zcfac=0.0_wp 
+      IF (ln_conserve)  zcfac=1.0_wp
+      zpress(:,:)=0.0_wp
+      zgammat2d(:,:)=0.0_wp
+      zgammas2d(:,:)=0.0_wp
+      !
+      !
+!CDIR COLLAPSE
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            ! Crude approximation for pressure (but commonly used)
+            ! 1e-04 to convert from Pa to dBar
+            zpress(ji,jj)=grav*rau0*fsdepw(ji,jj,mikt(ji,jj))*1.e-04
+            !
+         END DO
+      END DO
+
+! Calculate in-situ temperature (ref to surface)
+      zti(:,:)=tinsitu( ttbl, stbl, zpress )
+! Calculate freezing temperature
+      zfrz(:,:)=eos_fzp( sss_m(:,:), zpress )
+
+      
+      zhtflx=0._wp ; zfwflx=0._wp
+      IF (nn_isfblk == 1) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               IF (mikt(ji,jj) > 1 ) THEN
+                  nit = 1; lit = .TRUE.; zgammat=rn_gammat0; zgammas=rn_gammas0; zhtflx_b=0._wp
+                  DO WHILE ( lit )
+! compute gamma
+                     CALL sbc_isf_gammats(zgammat, zgammas, zhtflx, zfwflx, ji, jj, lit)
+! zhtflx is upward heat flux (out of ocean)
+                     zhtflx = zgammat*rcp*rau0*(zti(ji,jj)-zfrz(ji,jj))
+! zwflx is upward water flux
+                     zfwflx = - zhtflx/lfusisf
+! test convergence and compute gammat
+                     IF ( (zhtflx - zhtflx_b) .LE. 0.01 ) lit = .FALSE.
+
+                     nit = nit + 1
+                     IF (nit .GE. 100) THEN
+                        !WRITE(numout,*) "sbcisf : too many iteration ... ", zhtflx, zhtflx_b,zgammat, rn_gammat0, rn_tfri2, nn_gammablk, ji,jj
+                        !WRITE(numout,*) "sbcisf : too many iteration ... ", (zhtflx - zhtflx_b)/zhtflx
+                        CALL ctl_stop( 'STOP', 'sbc_isf_hol99 : too many iteration ...' )
+                     END IF
+! save gammat and compute zhtflx_b
+                     zgammat2d(ji,jj)=zgammat
+                     zhtflx_b = zhtflx
+                  END DO
+
+                  qisf(ji,jj) = - zhtflx
+! For genuine ISOMIP protocol this should probably be something like
+                  fwfisf(ji,jj) = zfwflx  * ( soce / MAX(stbl(ji,jj),zeps))
+               ELSE
+                  fwfisf(ji,jj) = 0._wp
+                  qisf(ji,jj)   = 0._wp
+               END IF
+            !
+            END DO
+         END DO
+
+      ELSE IF (nn_isfblk == 2 ) THEN
+
+! More complicated 3 equation thermodynamics as in MITgcm
+!CDIR COLLAPSE
+         DO jj = 2, jpj
+            DO ji = 2, jpi
+               IF (mikt(ji,jj) > 1 ) THEN
+                  nit=1; lit=.TRUE.; zgammat=rn_gammat0; zgammas=rn_gammas0; zhtflx_b=0._wp; zhtflx=0._wp
+                  DO WHILE ( lit )
+                     CALL sbc_isf_gammats(zgammat, zgammas, zhtflx, zfwflx, ji, jj, lit)
+
+                     zeps1=rcp*rau0*zgammat
+                     zeps2=lfusisf*rau0*zgammas
+                     zeps3=rhoisf*rcpi*kappa/risfdep(ji,jj)
+                     zeps4=zlamb2+zlamb3*risfdep(ji,jj)
+                     zeps6=zeps4-zti(ji,jj)
+                     zeps7=zeps4-tsurf
+                     zaqe=zlamb1 * (zeps1 + zeps3)
+                     zaqer=0.5/zaqe
+                     zbqe=zeps1*zeps6+zeps3*zeps7-zeps2
+                     zcqe=zeps2*stbl(ji,jj)
+                     zdis=zbqe*zbqe-4.0*zaqe*zcqe               
+! Presumably zdis can never be negative because gammas is very small compared to gammat
+                     zsfrz=(-zbqe-SQRT(zdis))*zaqer
+                     IF (zsfrz .lt. 0.0) zsfrz=(-zbqe+SQRT(zdis))*zaqer
+                     zfrz(ji,jj)=zeps4+zlamb1*zsfrz
+  
+! zfwflx is upward water flux
+                     zfwflx= rau0 * zgammas * ( (zsfrz-stbl(ji,jj)) / zsfrz )
+! zhtflx is upward heat flux (out of ocean)
+! If non conservative we have zcfac=0.0 so zhtflx is as ISOMIP but with different zfrz value
+                     zhtflx = ( zgammat*rau0 - zcfac*zfwflx ) * rcp * (zti(ji,jj) - zfrz(ji,jj) ) 
+! zwflx is upward water flux
+! If non conservative we have zcfac=0.0 so what follows is then zfwflx*sss_m/zsfrz
+                     zfwflx = ( zgammas*rau0 - zcfac*zfwflx ) * (zsfrz - stbl(ji,jj)) / stbl(ji,jj)
+! test convergence and compute gammat
+                     IF (( zhtflx - zhtflx_b) .LE. 0.01 ) lit = .FALSE.
+
+                     nit = nit + 1
+                     IF (nit .GE. 51) THEN
+                        WRITE(numout,*) "sbcisf : too many iteration ... ", &
+                            &  zhtflx, zhtflx_b, zgammat, zgammas, nn_gammablk, ji, jj, mikt(ji,jj), narea
+                        CALL ctl_stop( 'STOP', 'sbc_isf_hol99 : too many iteration ...' )
+                     END IF
+! save gammat and compute zhtflx_b
+                     zgammat2d(ji,jj)=zgammat
+                     zgammas2d(ji,jj)=zgammas
+                     zhtflx_b = zhtflx
+
+                  END DO
+! If non conservative we have zcfac=0.0 so zhtflx is as ISOMIP but with different zfrz value
+                  qisf(ji,jj) = - zhtflx 
+! If non conservative we have zcfac=0.0 so what follows is then zfwflx*sss_m/zsfrz
+                  fwfisf(ji,jj) = zfwflx 
+               ELSE
+                  fwfisf(ji,jj) = 0._wp
+                  qisf(ji,jj)   = 0._wp
+               ENDIF
+               !
+            END DO
+         END DO
+      ENDIF
+      ! lbclnk
+      CALL lbc_lnk(zgammas2d(:,:),'T',1.)
+      CALL lbc_lnk(zgammat2d(:,:),'T',1.)
+      ! output
+      CALL iom_put('isfgammat', zgammat2d)
+      CALL iom_put('isfgammas', zgammas2d)
+         !
+      !CALL wrk_dealloc( jpi,jpj, zfrz,zpress,zti, zqisf, zfwfisf  )
+      CALL wrk_dealloc( jpi,jpj, zfrz,zpress,zti, zgammat2d, zgammas2d )
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('sbc_isf_cav')
+
+   END SUBROUTINE sbc_isf_cav
+
+   SUBROUTINE sbc_isf_gammats(gt, gs, zqhisf, zqwisf, ji, jj, lit )
+      !!----------------------------------------------------------------------
+      !! ** Purpose    : compute the coefficient echange for heat flux
+      !!
+      !! ** Method     : gamma assume constant or depends of u* and stability
+      !!
+      !! ** References : Holland and Jenkins, 1999, JPO, p1787-1800, eq 14
+      !!                Jenkins et al., 2010, JPO, p2298-2312
+      !!---------------------------------------------------------------------
+      REAL(wp), INTENT(inout) :: gt, gs, zqhisf, zqwisf
+      INTEGER , INTENT(in)    :: ji,jj
+      LOGICAL , INTENT(inout) :: lit
+
+      INTEGER  :: ikt                 ! loop index
+      REAL(wp) :: zut, zvt, zustar           ! U, V at T point and friction velocity
+      REAL(wp) :: zdku, zdkv                 ! U, V shear 
+      REAL(wp) :: zPr, zSc, zRc              ! Prandtl, Scmidth and Richardson number 
+      REAL(wp) :: zmob, zmols                ! Monin Obukov length, coriolis factor at T point
+      REAL(wp) :: zbuofdep, zhnu             ! Bouyancy length scale, sublayer tickness
+      REAL(wp) :: zhmax                      ! limitation of mol
+      REAL(wp) :: zetastar                   ! stability parameter
+      REAL(wp) :: zgmolet, zgmoles, zgturb   ! contribution of modelecular sublayer and turbulence 
+      REAL(wp) :: zcoef                      ! temporary coef
+      REAL(wp) :: zdep
+      REAL(wp), PARAMETER :: zxsiN = 0.052   ! dimensionless constant
+      REAL(wp), PARAMETER :: epsln = 1.0e-20 ! a small positive number
+      REAL(wp), PARAMETER :: znu   = 1.95e-6 ! kinamatic viscosity of sea water (m2.s-1)
+      REAL(wp) ::   rcs      = 1.0e-3_wp        ! conversion: mm/s ==> m/s
+      REAL(wp), DIMENSION(2) :: zts, zab
+      !!---------------------------------------------------------------------
+      !
+      IF( nn_gammablk == 0 ) THEN
+      !! gamma is constant (specified in namelist)
+         gt = rn_gammat0
+         gs = rn_gammas0
+         lit = .FALSE.
+      ELSE IF ( nn_gammablk == 1 ) THEN
+      !! gamma is assume to be proportional to u* 
+      !! WARNING in case of Losh 2008 tbl parametrization, 
+      !! you have to used the mean value of u in the boundary layer) 
+      !! not yet coded
+      !! Jenkins et al., 2010, JPO, p2298-2312
+         ikt = mikt(ji,jj)
+      !! Compute U and V at T points
+   !      zut = 0.5 * ( utbl(ji-1,jj  ) + utbl(ji,jj) )
+   !      zvt = 0.5 * ( vtbl(ji  ,jj-1) + vtbl(ji,jj) )
+          zut = utbl(ji,jj)
+          zvt = vtbl(ji,jj)
+
+      !! compute ustar
+         zustar = SQRT( rn_tfri2 * (zut * zut + zvt * zvt) )
+      !! Compute mean value over the TBL
+
+      !! Compute gammats
+         gt = zustar * rn_gammat0
+         gs = zustar * rn_gammas0
+         lit = .FALSE.
+      ELSE IF ( nn_gammablk == 2 ) THEN
+      !! gamma depends of stability of boundary layer
+      !! WARNING in case of Losh 2008 tbl parametrization, 
+      !! you have to used the mean value of u in the boundary layer) 
+      !! not yet coded
+      !! Holland and Jenkins, 1999, JPO, p1787-1800, eq 14
+      !! as MOL depends of flux and flux depends of MOL, best will be iteration (TO DO)
+               ikt = mikt(ji,jj)
+
+      !! Compute U and V at T points
+               zut = 0.5 * ( utbl(ji-1,jj  ) + utbl(ji,jj) )
+               zvt = 0.5 * ( vtbl(ji  ,jj-1) + vtbl(ji,jj) )
+
+      !! compute ustar
+               zustar = SQRT( rn_tfri2 * (zut * zut + zvt * zvt) )
+               IF (zustar == 0._wp) THEN           ! only for kt = 1 I think
+                 gt = rn_gammat0
+                 gs = rn_gammas0
+               ELSE
+      !! compute Rc number (as done in zdfric.F90)
+               zcoef = 0.5 / fse3w(ji,jj,ikt)
+               !                                            ! shear of horizontal velocity
+               zdku = zcoef * (  un(ji-1,jj  ,ikt  ) + un(ji,jj,ikt  )   &
+                  &             -un(ji-1,jj  ,ikt+1) - un(ji,jj,ikt+1)  )
+               zdkv = zcoef * (  vn(ji  ,jj-1,ikt  ) + vn(ji,jj,ikt  )   &
+                  &             -vn(ji  ,jj-1,ikt+1) - vn(ji,jj,ikt+1)  )
+               !                                            ! richardson number (minimum value set to zero)
+               zRc = rn2(ji,jj,ikt+1) / ( zdku*zdku + zdkv*zdkv + 1.e-20 )
+
+      !! compute Pr and Sc number (can be improved)
+               zPr =   13.8
+               zSc = 2432.0
+
+      !! compute gamma mole
+               zgmolet = 12.5 * zPr ** (2.0/3.0) - 6.0
+               zgmoles = 12.5 * zSc ** (2.0/3.0) -6.0
+
+      !! compute bouyancy 
+               zts(jp_tem) = ttbl(ji,jj)
+               zts(jp_sal) = stbl(ji,jj)
+               zdep        = fsdepw(ji,jj,ikt)
+               !
+               CALL eos_rab( zts, zdep, zab )
+                  !
+      !! compute length scale 
+               zbuofdep = grav * ( zab(jp_tem) * zqhisf - zab(jp_sal) * zqwisf )  !!!!!!!!!!!!!!!!!!!!!!!!!!!!
+
+      !! compute Monin Obukov Length
+               ! Maximum boundary layer depth
+               zhmax = fsdept(ji,jj,mbkt(ji,jj)) - fsdepw(ji,jj,mikt(ji,jj)) -0.001
+               ! Compute Monin obukhov length scale at the surface and Ekman depth:
+               zmob   = zustar ** 3 / (vkarmn * (zbuofdep + epsln))
+               zmols  = SIGN(1._wp, zmob) * MIN(ABS(zmob), zhmax) * tmask(ji,jj,ikt)
+
+      !! compute eta* (stability parameter)
+               zetastar = 1 / ( SQRT(1 + MAX(zxsiN * zustar / ( ABS(ff(ji,jj)) * zmols * zRc ), 0.0)))
+
+      !! compute the sublayer thickness
+               zhnu = 5 * znu / zustar
+      !! compute gamma turb
+               zgturb = 1/vkarmn * LOG(zustar * zxsiN * zetastar * zetastar / ( ABS(ff(ji,jj)) * zhnu )) &
+               &      + 1 / ( 2 * zxsiN * zetastar ) - 1/vkarmn
+
+      !! compute gammats
+               gt = zustar / (zgturb + zgmolet)
+               gs = zustar / (zgturb + zgmoles)
+               END IF
+      END IF
+
+   END SUBROUTINE
+
+   SUBROUTINE sbc_isf_tbl( varin, varout, cptin )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE sbc_isf_tbl  ***
+      !!
+      !! ** Purpose : compute mean T/S/U/V in the boundary layer 
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) :: varin
+      REAL(wp), DIMENSION(:,:)  , INTENT(out):: varout
+      
+      CHARACTER(len=1), INTENT(in) :: cptin ! point of variable in/out
+
+      REAL(wp) :: ze3, zhk
+      REAL(wp), DIMENSION(:,:), POINTER :: zikt
+
+      INTEGER :: ji,jj,jk
+      INTEGER :: ikt,ikb
+      INTEGER, DIMENSION(:,:), POINTER :: mkt, mkb
+
+      CALL wrk_alloc( jpi,jpj, mkt, mkb  )
+      CALL wrk_alloc( jpi,jpj, zikt )
+
+      ! get first and last level of tbl
+      mkt(:,:) = misfkt(:,:)
+      mkb(:,:) = misfkb(:,:)
+
+      varout(:,:)=0._wp
+      DO jj = 2,jpj
+         DO ji = 2,jpi
+            IF (ssmask(ji,jj) == 1) THEN
+               ikt = mkt(ji,jj)
+               ikb = mkb(ji,jj)
+
+               ! level fully include in the ice shelf boundary layer
+               DO jk = ikt, ikb - 1
+                  ze3 = fse3t_n(ji,jj,jk)
+                  IF (cptin == 'T' ) varout(ji,jj) = varout(ji,jj) + varin(ji,jj,jk) * r1_hisf_tbl(ji,jj) * ze3
+                  IF (cptin == 'U' ) varout(ji,jj) = varout(ji,jj) + 0.5_wp * (varin(ji,jj,jk) + varin(ji-1,jj,jk)) &
+                     &                                                       * r1_hisf_tbl(ji,jj) * ze3
+                  IF (cptin == 'V' ) varout(ji,jj) = varout(ji,jj) + 0.5_wp * (varin(ji,jj,jk) + varin(ji,jj-1,jk)) &
+                     &                                                       * r1_hisf_tbl(ji,jj) * ze3
+               END DO
+
+               ! level partially include in ice shelf boundary layer 
+               zhk = SUM( fse3t_n(ji, jj, ikt:ikb - 1)) * r1_hisf_tbl(ji,jj)
+               IF (cptin == 'T') &
+                   &  varout(ji,jj) = varout(ji,jj) + varin(ji,jj,ikb) * (1._wp - zhk)
+               IF (cptin == 'U') &
+                   &  varout(ji,jj) = varout(ji,jj) + 0.5_wp * (varin(ji,jj,ikb) + varin(ji-1,jj,ikb)) * (1._wp - zhk)
+               IF (cptin == 'V') &
+                   &  varout(ji,jj) = varout(ji,jj) + 0.5_wp * (varin(ji,jj,ikb) + varin(ji,jj-1,ikb)) * (1._wp - zhk)
+            END IF
+         END DO
+      END DO
+
+      CALL wrk_dealloc( jpi,jpj, mkt, mkb )      
+      CALL wrk_dealloc( jpi,jpj, zikt ) 
+
+      IF (cptin == 'T') CALL lbc_lnk(varout,'T',1.)
+      IF (cptin == 'U' .OR. cptin == 'V') CALL lbc_lnk(varout,'T',-1.)
+
+   END SUBROUTINE sbc_isf_tbl
+      
+
+   SUBROUTINE sbc_isf_div( phdivn )
+      !!----------------------------------------------------------------------
+      !!                  ***  SUBROUTINE sbc_isf_div  ***
+      !!       
+      !! ** Purpose :   update the horizontal divergence with the runoff inflow
+      !!
+      !! ** Method  :   
+      !!                CAUTION : risf_tsc(:,:,jp_sal) is negative (outflow) increase the 
+      !!                          divergence and expressed in m/s
+      !!
+      !! ** Action  :   phdivn   decreased by the runoff inflow
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   phdivn   ! horizontal divergence
+      !!
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   ikt, ikb 
+      INTEGER  ::   nk_isf
+      REAL(wp)     ::   zhk, z1_hisf_tbl, zhisf_tbl
+      REAL(wp)     ::   zfact     ! local scalar
+      !!----------------------------------------------------------------------
+      !
+      zfact   = 0.5_wp
+      !
+      IF (lk_vvl) THEN     ! need to re compute level distribution of isf fresh water
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               ikt = misfkt(ji,jj)
+               ikb = misfkt(ji,jj)
+               ! thickness of boundary layer at least the top level thickness
+               rhisf_tbl(ji,jj) = MAX(rhisf_tbl_0(ji,jj), fse3t(ji,jj,ikt))
+
+               ! determine the deepest level influenced by the boundary layer
+               ! test on tmask useless ?????
+               DO jk = ikt, mbkt(ji,jj)
+!                  IF ( (SUM(fse3t(ji,jj,ikt:jk-1)) .LT. rhisf_tbl(ji,jj)) .AND. (tmask(ji,jj,jk) == 1) ) ikb = jk
+               END DO
+               rhisf_tbl(ji,jj) = MIN(rhisf_tbl(ji,jj), SUM(fse3t(ji,jj,ikt:ikb)))  ! limit the tbl to water thickness.
+               misfkb(ji,jj) = ikb                                                  ! last wet level of the tbl
+               r1_hisf_tbl(ji,jj) = 1._wp / rhisf_tbl(ji,jj)
+
+               zhk           = SUM( fse3t(ji, jj, ikt:ikb - 1)) * r1_hisf_tbl(ji,jj)  ! proportion of tbl cover by cell from ikt to ikb - 1
+               ralpha(ji,jj) = rhisf_tbl(ji,jj) * (1._wp - zhk ) / fse3t(ji,jj,ikb)  ! proportion of bottom cell influenced by boundary layer
+            END DO
+         END DO
+      END IF ! vvl case
+      !
+      DO jj = 1,jpj
+         DO ji = 1,jpi
+               ikt = misfkt(ji,jj)
+               ikb = misfkb(ji,jj)
+               ! level fully include in the ice shelf boundary layer
+               DO jk = ikt, ikb - 1
+                  phdivn(ji,jj,jk) = phdivn(ji,jj,jk) + ( fwfisf(ji,jj) + fwfisf_b(ji,jj) ) &
+                    &               * r1_hisf_tbl(ji,jj) * r1_rau0 * zfact
+               END DO
+               ! level partially include in ice shelf boundary layer 
+               phdivn(ji,jj,ikb) = phdivn(ji,jj,ikb) + ( fwfisf(ji,jj) &
+                  &             + fwfisf_b(ji,jj) ) * r1_hisf_tbl(ji,jj) * r1_rau0 * zfact * ralpha(ji,jj) 
+            !==   ice shelf melting mass distributed over several levels   ==!
+         END DO
+      END DO
+      !
+   END SUBROUTINE sbc_isf_div
+                        
+   FUNCTION tinsitu( ptem, psal, ppress ) RESULT( pti )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE eos_init  ***
+      !!
+      !! ** Purpose :   Compute the in-situ temperature [Celcius]
+      !!
+      !! ** Method  :   
+      !!
+      !! Reference  :   Bryden,h.,1973,deep-sea res.,20,401-408
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   ptem   ! potential temperature [Celcius]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   psal   ! salinity             [psu]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   ppress ! pressure             [dBar]
+      REAL(wp), DIMENSION(:,:), POINTER           ::   pti    ! in-situ temperature [Celcius]
+!      REAL(wp) :: fsatg
+!      REAL(wp) :: pfps, pfpt, pfphp 
+      REAL(wp) :: zt, zs, zp, zh, zq, zxk
+      INTEGER  :: ji, jj            ! dummy loop indices
+      !
+      CALL wrk_alloc( jpi,jpj, pti  )
+      ! 
+      DO jj=1,jpj
+         DO ji=1,jpi
+            zh = ppress(ji,jj)
+! Theta1
+            zt = ptem(ji,jj)
+            zs = psal(ji,jj)
+            zp = 0.0
+            zxk= zh * fsatg( zs, zt, zp )
+            zt = zt + 0.5 * zxk
+            zq = zxk
+! Theta2
+            zp = zp + 0.5 * zh
+            zxk= zh*fsatg( zs, zt, zp )
+            zt = zt + 0.29289322 * ( zxk - zq )
+            zq = 0.58578644 * zxk + 0.121320344 * zq
+! Theta3
+            zxk= zh * fsatg( zs, zt, zp )
+            zt = zt + 1.707106781 * ( zxk - zq )
+            zq = 3.414213562 * zxk - 4.121320344 * zq
+! Theta4
+            zp = zp + 0.5 * zh
+            zxk= zh * fsatg( zs, zt, zp )
+            pti(ji,jj) = zt + ( zxk - 2.0 * zq ) / 6.0
+         END DO
+      END DO
+      !
+      CALL wrk_dealloc( jpi,jpj, pti  )
+      !
+   END FUNCTION tinsitu
+   !
+   FUNCTION fsatg( pfps, pfpt, pfphp )
+      !!----------------------------------------------------------------------
+      !!                 ***  FUNCTION fsatg  ***
+      !!
+      !! ** Purpose    :   Compute the Adiabatic laspse rate [Celcius].[decibar]^-1
+      !!
+      !! ** Reference  :   Bryden,h.,1973,deep-sea res.,20,401-408
+      !! 
+      !! ** units      :   pressure        pfphp    decibars
+      !!                   temperature     pfpt     deg celsius (ipts-68)
+      !!                   salinity        pfps     (ipss-78)
+      !!                   adiabatic       fsatg    deg. c/decibar
+      !!----------------------------------------------------------------------
+      REAL(wp) :: pfps, pfpt, pfphp 
+      REAL(wp) :: fsatg
+      !
+      fsatg = (((-2.1687e-16*pfpt+1.8676e-14)*pfpt-4.6206e-13)*pfphp         &
+        &    +((2.7759e-12*pfpt-1.1351e-10)*(pfps-35.)+((-5.4481e-14*pfpt    &
+        &    +8.733e-12)*pfpt-6.7795e-10)*pfpt+1.8741e-8))*pfphp             &
+        &    +(-4.2393e-8*pfpt+1.8932e-6)*(pfps-35.)                         &
+        &    +((6.6228e-10*pfpt-6.836e-8)*pfpt+8.5258e-6)*pfpt+3.5803e-5
+      !
+    END FUNCTION fsatg
+    !!======================================================================
+END MODULE sbcisf
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcmod.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcmod.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcmod.F90	(revision 5075)
@@ -37,7 +37,7 @@
    USE sbcice_cice      ! surface boundary condition: CICE    sea-ice model
    USE sbccpl           ! surface boundary condition: coupled florulation
-   USE cpl_oasis3, ONLY:lk_cpl      ! are we in coupled mode?
    USE sbcssr           ! surface boundary condition: sea surface restoring
    USE sbcrnf           ! surface boundary condition: runoffs
+   USE sbcisf           ! surface boundary condition: ice shelf
    USE sbcfwb           ! surface boundary condition: freshwater budget
    USE closea           ! closed sea
@@ -82,7 +82,7 @@
       INTEGER ::   icpt   ! local integer
       !!
-      NAMELIST/namsbc/ nn_fsbc   , ln_ana    , ln_flx,  ln_blk_clio, ln_blk_core, ln_cpl,   &
+      NAMELIST/namsbc/ nn_fsbc   , ln_ana    , ln_flx,  ln_blk_clio, ln_blk_core,           &
          &             ln_blk_mfs, ln_apr_dyn, nn_ice,  nn_ice_embd, ln_dm2dc   , ln_rnf,   &
-         &             ln_ssr    , nn_fwb    , ln_cdgw , ln_wave , ln_sdw, nn_lsm, cn_iceflx
+         &             ln_ssr    ,  nn_isf , nn_fwb    , ln_cdgw , ln_wave , ln_sdw, nn_lsm, nn_limflx
       INTEGER  ::   ios
       !!----------------------------------------------------------------------
@@ -123,6 +123,6 @@
          WRITE(numout,*) '              CORE bulk  formulation                     ln_blk_core = ', ln_blk_core
          WRITE(numout,*) '              MFS  bulk  formulation                     ln_blk_mfs  = ', ln_blk_mfs
-         WRITE(numout,*) '              coupled    formulation (T if key_sbc_cpl)  ln_cpl      = ', ln_cpl
-         WRITE(numout,*) '              Flux handling over ice categories          cn_iceflx   = ', TRIM (cn_iceflx)
+         WRITE(numout,*) '              coupled    formulation (T if key_oasis3)   lk_cpl      = ', lk_cpl
+         WRITE(numout,*) '              Multicategory heat flux formulation (LIM3) nn_limflx   = ', nn_limflx
          WRITE(numout,*) '           Misc. options of sbc : '
          WRITE(numout,*) '              Patm gradient added in ocean & ice Eqs.    ln_apr_dyn  = ', ln_apr_dyn
@@ -131,4 +131,5 @@
          WRITE(numout,*) '              daily mean to diurnal cycle qsr            ln_dm2dc    = ', ln_dm2dc 
          WRITE(numout,*) '              runoff / runoff mouths                     ln_rnf      = ', ln_rnf
+         WRITE(numout,*) '              iceshelf formulation                       nn_isf      = ', nn_isf
          WRITE(numout,*) '              Sea Surface Restoring on SST and/or SSS    ln_ssr      = ', ln_ssr
          WRITE(numout,*) '              FreshWater Budget control  (=0/1/2)        nn_fwb      = ', nn_fwb
@@ -137,20 +138,15 @@
       ENDIF
 
-      !   Flux handling over ice categories
-#if defined key_coupled 
-      SELECT CASE ( TRIM (cn_iceflx))
-      CASE ('ave')
-         ln_iceflx_ave    = .TRUE.
-         ln_iceflx_linear = .FALSE.
-      CASE ('linear')
-         ln_iceflx_ave    = .FALSE.
-         ln_iceflx_linear = .TRUE.
-      CASE default
-         ln_iceflx_ave    = .FALSE.
-         ln_iceflx_linear = .FALSE.
+      ! LIM3 Multi-category heat flux formulation
+      SELECT CASE ( nn_limflx)
+      CASE ( -1 )
+         IF(lwp) WRITE(numout,*) '              Use of per-category fluxes (nn_limflx = -1) '
+      CASE ( 0  )
+         IF(lwp) WRITE(numout,*) '              Average per-category fluxes (nn_limflx = 0) ' 
+      CASE ( 1  )
+         IF(lwp) WRITE(numout,*) '              Average then redistribute per-category fluxes (nn_limflx = 1) '
+      CASE ( 2  )
+         IF(lwp) WRITE(numout,*) '              Redistribute a single flux over categories (nn_limflx = 2) '
       END SELECT
-      IF(lwp) WRITE(numout,*) '              Fluxes averaged over all ice categories         ln_iceflx_ave    = ', ln_iceflx_ave
-      IF(lwp) WRITE(numout,*) '              Fluxes distributed linearly over ice categories ln_iceflx_linear = ', ln_iceflx_linear
-#endif
       !
 #if defined key_top && ! defined key_offline
@@ -180,4 +176,8 @@
          rnfmsk_z(:)   = 0.0_wp
       ENDIF
+      IF( nn_isf .EQ. 0 ) THEN                      ! no specific treatment in vicinity of ice shelf 
+         IF( sbc_isf_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'sbc_init : unable to allocate sbc_isf arrays' )
+         fwfisf  (:,:) = 0.0_wp
+      END IF
       IF( nn_ice == 0  )   fr_i(:,:) = 0.e0        ! no ice in the domain, ice fraction is always zero
 
@@ -186,4 +186,6 @@
  
       fmmflx(:,:) = 0.0_wp                        ! freezing-melting array initialisation
+      
+      taum(:,:) = 0.0_wp                           ! Initialise taum for use in gls in case of reduced restart
 
       !                                            ! restartability   
@@ -206,10 +208,11 @@
       IF( ( nn_ice == 3 .OR. nn_ice == 4 ) .AND. nn_ice_embd == 0 )   &
          &   CALL ctl_stop( 'LIM3 and CICE sea-ice models require nn_ice_embd = 1 or 2' )
-#if defined key_coupled
-      IF( ln_iceflx_ave .AND. ln_iceflx_linear ) &
-         &   CALL ctl_stop( ' ln_iceflx_ave and ln_iceflx_linear options are not compatible' )
-      IF( ( nn_ice ==3 .AND. lk_cpl) .AND. .NOT. ( ln_iceflx_ave .OR. ln_iceflx_linear ) ) &
-         &   CALL ctl_stop( ' With lim3 coupled, either ln_iceflx_ave or ln_iceflx_linear must be set to .TRUE.' )
-#endif      
+      IF( ( nn_ice /= 3 ) .AND. ( nn_limflx >= 0 ) )   &
+         &   WRITE(numout,*) 'The nn_limflx>=0 option has no effect if sea ice model is not LIM3'
+      IF( ( nn_ice == 3 ) .AND. ( lk_cpl ) .AND. ( ( nn_limflx == -1 ) .OR. ( nn_limflx == 1 ) ) )   &
+         &   CALL ctl_stop( 'The chosen nn_limflx for LIM3 in coupled mode must be 0 or 2' )
+      IF( ( nn_ice == 3 ) .AND. ( .NOT. lk_cpl ) .AND. ( nn_limflx == 2 ) )   &
+         &   CALL ctl_stop( 'The chosen nn_limflx for LIM3 in forced mode cannot be 2' )
+
       IF( ln_dm2dc )   nday_qsr = -1   ! initialisation flag
 
@@ -236,12 +239,12 @@
       !                          ! Choice of the Surface Boudary Condition (set nsbc)
       icpt = 0
-      IF( ln_ana          ) THEN   ;   nsbc =  1   ; icpt = icpt + 1   ;   ENDIF       ! analytical      formulation
-      IF( ln_flx          ) THEN   ;   nsbc =  2   ; icpt = icpt + 1   ;   ENDIF       ! flux            formulation
-      IF( ln_blk_clio     ) THEN   ;   nsbc =  3   ; icpt = icpt + 1   ;   ENDIF       ! CLIO bulk       formulation
-      IF( ln_blk_core     ) THEN   ;   nsbc =  4   ; icpt = icpt + 1   ;   ENDIF       ! CORE bulk       formulation
-      IF( ln_blk_mfs      ) THEN   ;   nsbc =  6   ; icpt = icpt + 1   ;   ENDIF       ! MFS  bulk       formulation
-      IF( ln_cpl          ) THEN   ;   nsbc =  5   ; icpt = icpt + 1   ;   ENDIF       ! Coupled         formulation
-      IF( cp_cfg == 'gyre') THEN   ;   nsbc =  0                       ;   ENDIF       ! GYRE analytical formulation
-      IF( lk_esopa        )            nsbc = -1                                       ! esopa test, ALL formulations
+      IF( ln_ana          ) THEN   ;   nsbc = jp_ana    ; icpt = icpt + 1   ;   ENDIF       ! analytical      formulation
+      IF( ln_flx          ) THEN   ;   nsbc = jp_flx    ; icpt = icpt + 1   ;   ENDIF       ! flux            formulation
+      IF( ln_blk_clio     ) THEN   ;   nsbc = jp_clio   ; icpt = icpt + 1   ;   ENDIF       ! CLIO bulk       formulation
+      IF( ln_blk_core     ) THEN   ;   nsbc = jp_core   ; icpt = icpt + 1   ;   ENDIF       ! CORE bulk       formulation
+      IF( ln_blk_mfs      ) THEN   ;   nsbc = jp_mfs    ; icpt = icpt + 1   ;   ENDIF       ! MFS  bulk       formulation
+      IF( lk_cpl          ) THEN   ;   nsbc = jp_cpl    ; icpt = icpt + 1   ;   ENDIF       ! Coupled         formulation
+      IF( cp_cfg == 'gyre') THEN   ;   nsbc = jp_gyre                       ;   ENDIF       ! GYRE analytical formulation
+      IF( lk_esopa        )            nsbc = jp_esopa                                      ! esopa test, ALL formulations
       !
       IF( icpt /= 1 .AND. .NOT.lk_esopa ) THEN
@@ -254,20 +257,22 @@
       IF(lwp) THEN
          WRITE(numout,*)
-         IF( nsbc == -1 )   WRITE(numout,*) '              ESOPA test All surface boundary conditions'
-         IF( nsbc ==  0 )   WRITE(numout,*) '              GYRE analytical formulation'
-         IF( nsbc ==  1 )   WRITE(numout,*) '              analytical formulation'
-         IF( nsbc ==  2 )   WRITE(numout,*) '              flux formulation'
-         IF( nsbc ==  3 )   WRITE(numout,*) '              CLIO bulk formulation'
-         IF( nsbc ==  4 )   WRITE(numout,*) '              CORE bulk formulation'
-         IF( nsbc ==  5 )   WRITE(numout,*) '              coupled formulation'
-         IF( nsbc ==  6 )   WRITE(numout,*) '              MFS Bulk formulation'
-      ENDIF
-      !
-                          CALL sbc_ssm_init               ! Sea-surface mean fields initialisation
-      !
-      IF( ln_ssr      )   CALL sbc_ssr_init               ! Sea-Surface Restoring initialisation
-      !
-      IF( nn_ice == 4 )   CALL cice_sbc_init( nsbc )      ! CICE initialisation
-      !
+         IF( nsbc == jp_esopa )   WRITE(numout,*) '              ESOPA test All surface boundary conditions'
+         IF( nsbc == jp_gyre  )   WRITE(numout,*) '              GYRE analytical formulation'
+         IF( nsbc == jp_ana   )   WRITE(numout,*) '              analytical formulation'
+         IF( nsbc == jp_flx   )   WRITE(numout,*) '              flux formulation'
+         IF( nsbc == jp_clio  )   WRITE(numout,*) '              CLIO bulk formulation'
+         IF( nsbc == jp_core  )   WRITE(numout,*) '              CORE bulk formulation'
+         IF( nsbc == jp_cpl   )   WRITE(numout,*) '              coupled formulation'
+         IF( nsbc == jp_mfs   )   WRITE(numout,*) '              MFS Bulk formulation'
+      ENDIF
+      !
+                               CALL sbc_ssm_init               ! Sea-surface mean fields initialisation
+      !
+      IF( ln_ssr           )   CALL sbc_ssr_init               ! Sea-Surface Restoring initialisation
+      !
+      IF( nn_ice == 4      )   CALL cice_sbc_init( nsbc )      ! CICE initialisation
+      !
+      IF( nsbc   == jp_cpl )   CALL sbc_cpl_init (nn_ice)      ! OASIS initialisation. must be done before first time step
+
    END SUBROUTINE sbc_init
 
@@ -320,18 +325,18 @@
       SELECT CASE( nsbc )                                ! Compute ocean surface boundary condition
       !                                                  ! (i.e. utau,vtau, qns, qsr, emp, sfx)
-      CASE(  0 )   ;   CALL sbc_gyre    ( kt )                    ! analytical formulation : GYRE configuration
-      CASE(  1 )   ;   CALL sbc_ana     ( kt )                    ! analytical formulation : uniform sbc
-      CASE(  2 )   ;   CALL sbc_flx     ( kt )                    ! flux formulation
-      CASE(  3 )   ;   CALL sbc_blk_clio( kt )                    ! bulk formulation : CLIO for the ocean
-      CASE(  4 )   ;   CALL sbc_blk_core( kt )                    ! bulk formulation : CORE for the ocean
-      CASE(  5 )   ;   CALL sbc_cpl_rcv ( kt, nn_fsbc, nn_ice )   ! coupled formulation
-      CASE(  6 )   ;   CALL sbc_blk_mfs ( kt )                    ! bulk formulation : MFS for the ocean
-      CASE( -1 )                                
-                       CALL sbc_ana     ( kt )                    ! ESOPA, test ALL the formulations
-                       CALL sbc_gyre    ( kt )                    !
-                       CALL sbc_flx     ( kt )                    !
-                       CALL sbc_blk_clio( kt )                    !
-                       CALL sbc_blk_core( kt )                    !
-                       CALL sbc_cpl_rcv ( kt, nn_fsbc, nn_ice )   !
+      CASE( jp_gyre  )   ;   CALL sbc_gyre    ( kt )                    ! analytical formulation : GYRE configuration
+      CASE( jp_ana   )   ;   CALL sbc_ana     ( kt )                    ! analytical formulation : uniform sbc
+      CASE( jp_flx   )   ;   CALL sbc_flx     ( kt )                    ! flux formulation
+      CASE( jp_clio  )   ;   CALL sbc_blk_clio( kt )                    ! bulk formulation : CLIO for the ocean
+      CASE( jp_core  )   ;   CALL sbc_blk_core( kt )                    ! bulk formulation : CORE for the ocean
+      CASE( jp_cpl   )   ;   CALL sbc_cpl_rcv ( kt, nn_fsbc, nn_ice )   ! coupled formulation
+      CASE( jp_mfs   )   ;   CALL sbc_blk_mfs ( kt )                    ! bulk formulation : MFS for the ocean
+      CASE( jp_esopa )                                
+                             CALL sbc_ana     ( kt )                    ! ESOPA, test ALL the formulations
+                             CALL sbc_gyre    ( kt )                    !
+                             CALL sbc_flx     ( kt )                    !
+                             CALL sbc_blk_clio( kt )                    !
+                             CALL sbc_blk_core( kt )                    !
+                             CALL sbc_cpl_rcv ( kt, nn_fsbc, nn_ice )   !
       END SELECT
 
@@ -342,9 +347,10 @@
       CASE(  2 )   ;         CALL sbc_ice_lim_2( kt, nsbc )          ! LIM-2 ice model
       CASE(  3 )   ;         CALL sbc_ice_lim  ( kt, nsbc )          ! LIM-3 ice model
-      !is it useful?
       CASE(  4 )   ;         CALL sbc_ice_cice ( kt, nsbc )          ! CICE ice model
       END SELECT                                              
 
       IF( ln_icebergs    )   CALL icb_stp( kt )                   ! compute icebergs
+
+      IF( nn_isf   /= 0  )   CALL sbc_isf( kt )                    ! compute iceshelves
 
       IF( ln_rnf         )   CALL sbc_rnf( kt )                   ! add runoffs to fresh water fluxes
@@ -414,15 +420,15 @@
          CALL iom_put( "qsr"   ,       qsr  )                   ! solar heat flux
          IF( nn_ice > 0 )   CALL iom_put( "ice_cover", fr_i )   ! ice fraction 
+         CALL iom_put( "taum"  , taum       )                   ! wind stress module 
+         CALL iom_put( "wspd"  , wndm       )                   ! wind speed  module over free ocean or leads in presence of sea-ice
       ENDIF
       !
       CALL iom_put( "utau", utau )   ! i-wind stress   (stress can be updated at 
       CALL iom_put( "vtau", vtau )   ! j-wind stress    each time step in sea-ice)
-      CALL iom_put( "taum", taum )   ! wind stress module 
-      CALL iom_put( "wspd", wndm )   ! wind speed  module 
       !
       IF(ln_ctl) THEN         ! print mean trends (used for debugging)
-         CALL prt_ctl(tab2d_1=fr_i             , clinfo1=' fr_i     - : ', mask1=tmask, ovlap=1 )
-         CALL prt_ctl(tab2d_1=(emp-rnf)        , clinfo1=' emp-rnf  - : ', mask1=tmask, ovlap=1 )
-         CALL prt_ctl(tab2d_1=(sfx-rnf)        , clinfo1=' sfx-rnf  - : ', mask1=tmask, ovlap=1 )
+         CALL prt_ctl(tab2d_1=fr_i              , clinfo1=' fr_i     - : ', mask1=tmask, ovlap=1 )
+         CALL prt_ctl(tab2d_1=(emp-rnf + fwfisf), clinfo1=' emp-rnf  - : ', mask1=tmask, ovlap=1 )
+         CALL prt_ctl(tab2d_1=(sfx-rnf + fwfisf), clinfo1=' sfx-rnf  - : ', mask1=tmask, ovlap=1 )
          CALL prt_ctl(tab2d_1=qns              , clinfo1=' qns      - : ', mask1=tmask, ovlap=1 )
          CALL prt_ctl(tab2d_1=qsr              , clinfo1=' qsr      - : ', mask1=tmask, ovlap=1 )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcrnf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcrnf.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcrnf.F90	(revision 5075)
@@ -19,4 +19,5 @@
    USE phycst          ! physical constants
    USE sbc_oce         ! surface boundary condition variables
+   USE sbcisf          ! PM we could remove it I think
    USE closea          ! closed seas
    USE fldread         ! read input field at current time step
@@ -24,4 +25,6 @@
    USE iom             ! I/O module
    USE lib_mpp         ! MPP library
+   USE eosbn2
+   USE wrk_nemo        ! Memory allocation
 
    IMPLICIT NONE
@@ -98,4 +101,8 @@
       INTEGER  ::   z_err = 0 ! dummy integer for error handling
       !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:), POINTER       ::   ztfrz   ! freezing point used for temperature correction
+      !
+      CALL wrk_alloc( jpi,jpj, ztfrz)
+
       !
       IF( kt == nit000 )   CALL sbc_rnf_init                           ! Read namelist and allocate structures
@@ -134,4 +141,8 @@
                WHERE( sf_t_rnf(1)%fnow(:,:,1) == -999._wp )             ! if missing data value use SST as runoffs temperature
                    rnf_tsc(:,:,jp_tem) = sst_m(:,:) * rnf(:,:) * r1_rau0
+               END WHERE
+               WHERE( sf_t_rnf(1)%fnow(:,:,1) == -222._wp )             ! where fwf comes from melting of ice shelves or iceberg
+                   ztfrz(:,:) = -1.9 !tfreez( sss_m(:,:) ) !PM to be discuss (trouble if sensitivity study)
+                   rnf_tsc(:,:,jp_tem) = ztfrz(:,:) * rnf(:,:) * r1_rau0 - rnf(:,:) * lfusisf * r1_rau0_rcp
                END WHERE
             ELSE                                                        ! use SST as runoffs temperature
@@ -175,4 +186,5 @@
          CALL iom_rstput( kt, nitrst, numrow, 'rnf_sc_b', rnf_tsc(:,:,jp_sal) )
       ENDIF
+      CALL wrk_dealloc( jpi,jpj, ztfrz)
       !
    END SUBROUTINE sbc_rnf
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcssm.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcssm.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcssm.F90	(revision 5075)
@@ -14,10 +14,11 @@
    USE oce             ! ocean dynamics and tracers
    USE dom_oce         ! ocean space and time domain
-   USE sbc_oce         ! Surface boundary condition: ocean fields
    USE sbc_oce         ! surface boundary condition: ocean fields
    USE sbcapr          ! surface boundary condition: atmospheric pressure
-   USE prtctl          ! Print control                    (prt_ctl routine)
-   USE iom
+   USE eosbn2          ! equation of state and related derivatives
+   !
    USE in_out_manager  ! I/O manager
+   USE prtctl          ! Print control
+   USE iom             ! IOM library
 
    IMPLICIT NONE
@@ -54,13 +55,36 @@
       INTEGER, INTENT(in) ::   kt   ! ocean time step
       !
+      INTEGER  ::   ji, jj               ! loop index
       REAL(wp) ::   zcoef, zf_sbc       ! local scalar
+      REAL(wp), DIMENSION(jpi,jpj,jpts) :: zts
+      REAL(wp), DIMENSION(jpi,jpj)      :: zub, zvb,zdep
       !!---------------------------------------------------------------------
+      
+      !                                        !* first wet T-, U-, V- ocean level (ISF) variables (T, S, depth, velocity)
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            zub(ji,jj)        = ub (ji,jj,miku(ji,jj))
+            zvb(ji,jj)        = vb (ji,jj,mikv(ji,jj))
+            zts(ji,jj,jp_tem) = tsn(ji,jj,mikt(ji,jj),jp_tem)
+            zts(ji,jj,jp_sal) = tsn(ji,jj,mikt(ji,jj),jp_sal)
+         END DO
+      END DO
+      !
+      IF( lk_vvl ) THEN
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zdep(ji,jj) = fse3t_n(ji,jj,mikt(ji,jj))
+            END DO
+         END DO
+      ENDIF
       !                                                   ! ---------------------------------------- !
       IF( nn_fsbc == 1 ) THEN                             !   Instantaneous surface fields        !
          !                                                ! ---------------------------------------- !
-         ssu_m(:,:) = ub(:,:,1)
-         ssv_m(:,:) = vb(:,:,1)
-         sst_m(:,:) = tsn(:,:,1,jp_tem)
-         sss_m(:,:) = tsn(:,:,1,jp_sal)
+         ssu_m(:,:) = zub(:,:)
+         ssv_m(:,:) = zvb(:,:)
+         IF( ln_useCT )  THEN    ;   sst_m(:,:) = eos_pt_from_ct( zts(:,:,jp_tem), zts(:,:,jp_sal) )
+         ELSE                    ;   sst_m(:,:) = zts(:,:,jp_tem)
+         ENDIF
+         sss_m(:,:) = zts(:,:,jp_sal)
          !                          ! removed inverse barometer ssh when Patm forcing is used (for sea-ice dynamics)
          IF( ln_apr_dyn ) THEN   ;   ssh_m(:,:) = sshn(:,:) - 0.5 * ( ssh_ib(:,:) + ssh_ibb(:,:) )
@@ -68,5 +92,5 @@
          ENDIF
          !
-         IF( lk_vvl )   fse3t_m(:,:) = fse3t_n(:,:,1)
+         IF( lk_vvl )   fse3t_m(:,:) = zdep(:,:)
          !
       ELSE
@@ -77,13 +101,16 @@
             IF(lwp) WRITE(numout,*) '~~~~~~~   mean fields initialised to instantaneous values'
             zcoef = REAL( nn_fsbc - 1, wp )
-            ssu_m(:,:) = zcoef * ub(:,:,1)
-            ssv_m(:,:) = zcoef * vb(:,:,1)
-            sst_m(:,:) = zcoef * tsn(:,:,1,jp_tem)
-            sss_m(:,:) = zcoef * tsn(:,:,1,jp_sal)
-            !                          ! removed inverse barometer ssh when Patm forcing is used 
+            ssu_m(:,:) = zcoef * zub(:,:)
+            ssv_m(:,:) = zcoef * zvb(:,:)
+            IF( ln_useCT )  THEN    ;   sst_m(:,:) = zcoef * eos_pt_from_ct( zts(:,:,jp_tem), zts(:,:,jp_sal) )
+            ELSE                    ;   sst_m(:,:) = zcoef * zts(:,:,jp_tem)
+            ENDIF
+            sss_m(:,:) = zcoef * zts(:,:,jp_sal)
+            !                          ! removed inverse barometer ssh when Patm forcing is used (for sea-ice dynamics)
             IF( ln_apr_dyn ) THEN   ;   ssh_m(:,:) = zcoef * ( sshn(:,:) - 0.5 * ( ssh_ib(:,:) + ssh_ibb(:,:) ) )
-            ELSE                    ;   ssh_m(:,:) = zcoef *   sshn(:,:)
+            ELSE                    ;   ssh_m(:,:) = zcoef * sshn(:,:)
             ENDIF
-            IF( lk_vvl )   fse3t_m(:,:) = zcoef * fse3t_n(:,:,1)
+            !
+            IF( lk_vvl )   fse3t_m(:,:) = zcoef * zdep(:,:)
             !                                             ! ---------------------------------------- !
          ELSEIF( MOD( kt - 2 , nn_fsbc ) == 0 ) THEN      !   Initialisation: New mean computation   !
@@ -99,13 +126,16 @@
          !                                                !        Cumulate at each time step        !
          !                                                ! ---------------------------------------- !
-         ssu_m(:,:) = ssu_m(:,:) + ub(:,:,1)
-         ssv_m(:,:) = ssv_m(:,:) + vb(:,:,1)
-         sst_m(:,:) = sst_m(:,:) + tsn(:,:,1,jp_tem)
-         sss_m(:,:) = sss_m(:,:) + tsn(:,:,1,jp_sal)
+         ssu_m(:,:) = ssu_m(:,:) + zub(:,:)
+         ssv_m(:,:) = ssv_m(:,:) + zvb(:,:)
+         IF( ln_useCT )  THEN    ;   sst_m(:,:) = sst_m(:,:) + eos_pt_from_ct( zts(:,:,jp_tem), zts(:,:,jp_sal) )
+         ELSE                    ;   sst_m(:,:) = sst_m(:,:) + zts(:,:,jp_tem)
+         ENDIF
+         sss_m(:,:) = sss_m(:,:) + zts(:,:,jp_sal)
          !                          ! removed inverse barometer ssh when Patm forcing is used (for sea-ice dynamics)
-         IF( ln_apr_dyn ) THEN   ;   ssh_m(:,:) = ssh_m(:,:) + sshn(:,:) - 0.5 *  ( ssh_ib(:,:) + ssh_ibb(:,:) )
+         IF( ln_apr_dyn ) THEN   ;   ssh_m(:,:) = ssh_m(:,:) + sshn(:,:) - 0.5 * ( ssh_ib(:,:) + ssh_ibb(:,:) )
          ELSE                    ;   ssh_m(:,:) = ssh_m(:,:) + sshn(:,:)
          ENDIF
-         IF( lk_vvl )   fse3t_m(:,:) = fse3t_m(:,:) + fse3t_n(:,:,1)
+         !
+         IF( lk_vvl )   fse3t_m(:,:) = fse3t_m(:,:) + zdep(:,:)
 
          !                                                ! ---------------------------------------- !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcssr.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcssr.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/SBC/sbcssr.F90	(revision 5075)
@@ -10,4 +10,5 @@
    !!----------------------------------------------------------------------
    !!   sbc_ssr       : add to sbc a restoring term toward SST/SSS climatology
+   !!   sbc_ssr_init  : initialisation of surface restoring
    !!----------------------------------------------------------------------
    USE oce            ! ocean dynamics and tracers
@@ -16,4 +17,5 @@
    USE phycst         ! physical constants
    USE sbcrnf         ! surface boundary condition : runoffs
+   !
    USE fldread        ! read input fields
    USE iom            ! I/O manager
@@ -93,5 +95,4 @@
             !
             IF( nn_sstr == 1 ) THEN                                   !* Temperature restoring term
-!CDIR COLLAPSE
                DO jj = 1, jpj
                   DO ji = 1, jpi
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/eosbn2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/eosbn2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/eosbn2.F90	(revision 5075)
@@ -15,7 +15,11 @@
    !!             -   ! 2002-11  (G. Madec, A. Bozec)  partial step, eos_insitu_2d
    !!             -   ! 2003-08  (G. Madec)  F90, free form
-   !!            3.0  ! 2006-08  (G. Madec)  add tfreez function
+   !!            3.0  ! 2006-08  (G. Madec)  add tfreez function (now eos_fzp function)
    !!            3.3  ! 2010-05  (C. Ethe, G. Madec)  merge TRC-TRA
-   !!             -   ! 2010-10  (G. Nurser, G. Madec)  add eos_alpbet used in ldfslp
+   !!             -   ! 2010-10  (G. Nurser, G. Madec)  add alpha/beta used in ldfslp
+   !!            3.7  ! 2012-03  (F. Roquet, G. Madec)  add primitive of alpha and beta used in PE computation
+   !!             -   ! 2012-05  (F. Roquet)  add Vallis and original JM95 equation of state
+   !!             -   ! 2013-04  (F. Roquet, G. Madec)  add eos_rab, change bn2 computation and reorganize the module
+   !!             -   ! 2014-09  (F. Roquet)  add TEOS-10, S-EOS, and modify EOS-80
    !!----------------------------------------------------------------------
 
@@ -23,19 +27,23 @@
    !!   eos            : generic interface of the equation of state
    !!   eos_insitu     : Compute the in situ density
-   !!   eos_insitu_pot : Compute the insitu and surface referenced potential
-   !!                    volumic mass
+   !!   eos_insitu_pot : Compute the insitu and surface referenced potential volumic mass
    !!   eos_insitu_2d  : Compute the in situ density for 2d fields
-   !!   eos_bn2        : Compute the Brunt-Vaisala frequency
-   !!   eos_alpbet     : calculates the in situ thermal/haline expansion ratio
-   !!   tfreez         : Compute the surface freezing temperature
+   !!   bn2            : Compute the Brunt-Vaisala frequency
+   !!   eos_rab        : generic interface of in situ thermal/haline expansion ratio 
+   !!   eos_rab_3d     : compute in situ thermal/haline expansion ratio
+   !!   eos_rab_2d     : compute in situ thermal/haline expansion ratio for 2d fields
+   !!   eos_fzp_2d     : freezing temperature for 2d fields
+   !!   eos_fzp_0d     : freezing temperature for scalar
    !!   eos_init       : set eos parameters (namelist)
    !!----------------------------------------------------------------------
    USE dom_oce         ! ocean space and time domain
    USE phycst          ! physical constants
-   USE zdfddm          ! vertical physics: double diffusion
+   !
    USE in_out_manager  ! I/O manager
    USE lib_mpp         ! MPP library
+   USE lib_fortran     ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
    USE prtctl          ! Print control
    USE wrk_nemo        ! Memory Allocation
+   USE lbclnk         ! ocean lateral boundary conditions
    USE timing          ! Timing
 
@@ -47,20 +55,116 @@
       MODULE PROCEDURE eos_insitu, eos_insitu_pot, eos_insitu_2d
    END INTERFACE
-   INTERFACE bn2
-      MODULE PROCEDURE eos_bn2
+   !
+   INTERFACE eos_rab
+      MODULE PROCEDURE rab_3d, rab_2d, rab_0d
    END INTERFACE
-
-   PUBLIC   eos        ! called by step, istate, tranpc and zpsgrd modules
-   PUBLIC   eos_init   ! called by istate module
-   PUBLIC   bn2        ! called by step module
-   PUBLIC   eos_alpbet ! called by ldfslp module
-   PUBLIC   tfreez     ! called by sbcice_... modules
-
-   !                                  !!* Namelist (nameos) *
-   INTEGER , PUBLIC ::   nn_eos       !: = 0/1/2 type of eq. of state and Brunt-Vaisala frequ.
-   REAL(wp), PUBLIC ::   rn_alpha     !: thermal expension coeff. (linear equation of state)
-   REAL(wp), PUBLIC ::   rn_beta      !: saline  expension coeff. (linear equation of state)
-
-   REAL(wp), PUBLIC ::   ralpbet              !: alpha / beta ratio
+   !
+   INTERFACE eos_fzp 
+      MODULE PROCEDURE eos_fzp_2d, eos_fzp_0d
+   END INTERFACE
+   !
+   PUBLIC   eos            ! called by step, istate, tranpc and zpsgrd modules
+   PUBLIC   bn2            ! called by step module
+   PUBLIC   eos_rab        ! called by ldfslp, zdfddm, trabbl
+   PUBLIC   eos_pt_from_ct ! called by sbcssm
+   PUBLIC   eos_fzp        ! called by traadv_cen2 and sbcice_... modules
+   PUBLIC   eos_pen        ! used for pe diagnostics in trdpen module
+   PUBLIC   eos_init       ! called by istate module
+
+   !                                          !!* Namelist (nameos) *
+   INTEGER , PUBLIC ::   nn_eos   = 0         !: = 0/1/2 type of eq. of state and Brunt-Vaisala frequ.
+   LOGICAL , PUBLIC ::   ln_useCT  = .FALSE.  ! determine if eos_pt_from_ct is used to compute sst_m
+
+   !                                   !!!  simplified eos coefficients
+   ! default value: Vallis 2006
+   REAL(wp) ::   rn_a0      = 1.6550e-1_wp     ! thermal expansion coeff. 
+   REAL(wp) ::   rn_b0      = 7.6554e-1_wp     ! saline  expansion coeff. 
+   REAL(wp) ::   rn_lambda1 = 5.9520e-2_wp     ! cabbeling coeff. in T^2        
+   REAL(wp) ::   rn_lambda2 = 5.4914e-4_wp     ! cabbeling coeff. in S^2        
+   REAL(wp) ::   rn_mu1     = 1.4970e-4_wp     ! thermobaric coeff. in T  
+   REAL(wp) ::   rn_mu2     = 1.1090e-5_wp     ! thermobaric coeff. in S  
+   REAL(wp) ::   rn_nu      = 2.4341e-3_wp     ! cabbeling coeff. in theta*salt  
+   
+   ! TEOS10/EOS80 parameters
+   REAL(wp) ::   r1_S0, r1_T0, r1_Z0, rdeltaS
+   
+   ! EOS parameters
+   REAL(wp) ::   EOS000 , EOS100 , EOS200 , EOS300 , EOS400 , EOS500 , EOS600
+   REAL(wp) ::   EOS010 , EOS110 , EOS210 , EOS310 , EOS410 , EOS510
+   REAL(wp) ::   EOS020 , EOS120 , EOS220 , EOS320 , EOS420
+   REAL(wp) ::   EOS030 , EOS130 , EOS230 , EOS330
+   REAL(wp) ::   EOS040 , EOS140 , EOS240
+   REAL(wp) ::   EOS050 , EOS150
+   REAL(wp) ::   EOS060
+   REAL(wp) ::   EOS001 , EOS101 , EOS201 , EOS301 , EOS401
+   REAL(wp) ::   EOS011 , EOS111 , EOS211 , EOS311
+   REAL(wp) ::   EOS021 , EOS121 , EOS221
+   REAL(wp) ::   EOS031 , EOS131
+   REAL(wp) ::   EOS041
+   REAL(wp) ::   EOS002 , EOS102 , EOS202
+   REAL(wp) ::   EOS012 , EOS112
+   REAL(wp) ::   EOS022
+   REAL(wp) ::   EOS003 , EOS103
+   REAL(wp) ::   EOS013 
+   
+   ! ALPHA parameters
+   REAL(wp) ::   ALP000 , ALP100 , ALP200 , ALP300 , ALP400 , ALP500
+   REAL(wp) ::   ALP010 , ALP110 , ALP210 , ALP310 , ALP410
+   REAL(wp) ::   ALP020 , ALP120 , ALP220 , ALP320
+   REAL(wp) ::   ALP030 , ALP130 , ALP230
+   REAL(wp) ::   ALP040 , ALP140
+   REAL(wp) ::   ALP050
+   REAL(wp) ::   ALP001 , ALP101 , ALP201 , ALP301
+   REAL(wp) ::   ALP011 , ALP111 , ALP211
+   REAL(wp) ::   ALP021 , ALP121
+   REAL(wp) ::   ALP031
+   REAL(wp) ::   ALP002 , ALP102
+   REAL(wp) ::   ALP012
+   REAL(wp) ::   ALP003
+   
+   ! BETA parameters
+   REAL(wp) ::   BET000 , BET100 , BET200 , BET300 , BET400 , BET500
+   REAL(wp) ::   BET010 , BET110 , BET210 , BET310 , BET410
+   REAL(wp) ::   BET020 , BET120 , BET220 , BET320
+   REAL(wp) ::   BET030 , BET130 , BET230
+   REAL(wp) ::   BET040 , BET140
+   REAL(wp) ::   BET050
+   REAL(wp) ::   BET001 , BET101 , BET201 , BET301
+   REAL(wp) ::   BET011 , BET111 , BET211
+   REAL(wp) ::   BET021 , BET121
+   REAL(wp) ::   BET031
+   REAL(wp) ::   BET002 , BET102
+   REAL(wp) ::   BET012
+   REAL(wp) ::   BET003
+
+   ! PEN parameters
+   REAL(wp) ::   PEN000 , PEN100 , PEN200 , PEN300 , PEN400
+   REAL(wp) ::   PEN010 , PEN110 , PEN210 , PEN310
+   REAL(wp) ::   PEN020 , PEN120 , PEN220
+   REAL(wp) ::   PEN030 , PEN130
+   REAL(wp) ::   PEN040
+   REAL(wp) ::   PEN001 , PEN101 , PEN201
+   REAL(wp) ::   PEN011 , PEN111
+   REAL(wp) ::   PEN021
+   REAL(wp) ::   PEN002 , PEN102
+   REAL(wp) ::   PEN012
+   
+   ! ALPHA_PEN parameters
+   REAL(wp) ::   APE000 , APE100 , APE200 , APE300
+   REAL(wp) ::   APE010 , APE110 , APE210
+   REAL(wp) ::   APE020 , APE120
+   REAL(wp) ::   APE030
+   REAL(wp) ::   APE001 , APE101
+   REAL(wp) ::   APE011
+   REAL(wp) ::   APE002
+
+   ! BETA_PEN parameters
+   REAL(wp) ::   BPE000 , BPE100 , BPE200 , BPE300
+   REAL(wp) ::   BPE010 , BPE110 , BPE210
+   REAL(wp) ::   BPE020 , BPE120
+   REAL(wp) ::   BPE030
+   REAL(wp) ::   BPE001 , BPE101
+   REAL(wp) ::   BPE011
+   REAL(wp) ::   BPE002
 
    !! * Substitutions
@@ -68,5 +172,5 @@
 #  include "vectopt_loop_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! NEMO/OPA 3.7 , NEMO Consortium (2014)
    !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -82,117 +186,108 @@
       !!       defined through the namelist parameter nn_eos.
       !!
-      !! ** Method  :   3 cases:
-      !!      nn_eos = 0 : Jackett and McDougall (1994) equation of state.
-      !!         the in situ density is computed directly as a function of
-      !!         potential temperature relative to the surface (the opa t
-      !!         variable), salt and pressure (assuming no pressure variation
-      !!         along geopotential surfaces, i.e. the pressure p in decibars
-      !!         is approximated by the depth in meters.
-      !!              prd(t,s,p) = ( rho(t,s,p) - rau0 ) / rau0
-      !!         with pressure                      p        decibars
-      !!              potential temperature         t        deg celsius
-      !!              salinity                      s        psu
-      !!              reference volumic mass        rau0     kg/m**3
-      !!              in situ volumic mass          rho      kg/m**3
-      !!              in situ density anomalie      prd      no units
-      !!         Check value: rho = 1060.93298 kg/m**3 for p=10000 dbar,
-      !!          t = 40 deg celcius, s=40 psu
-      !!      nn_eos = 1 : linear equation of state function of temperature only
-      !!              prd(t) = 0.0285 - rn_alpha * t
-      !!      nn_eos = 2 : linear equation of state function of temperature and
-      !!               salinity
-      !!              prd(t,s) = rn_beta * s - rn_alpha * tn - 1.
-      !!      Note that no boundary condition problem occurs in this routine
-      !!      as pts are defined over the whole domain.
+      !! ** Method  :   prd(t,s,z) = ( rho(t,s,z) - rau0 ) / rau0
+      !!         with   prd    in situ density anomaly      no units
+      !!                t      TEOS10: CT or EOS80: PT      Celsius
+      !!                s      TEOS10: SA or EOS80: SP      TEOS10: g/kg or EOS80: psu
+      !!                z      depth                        meters
+      !!                rho    in situ density              kg/m^3
+      !!                rau0   reference density            kg/m^3
+      !!
+      !!     nn_eos = -1 : polynomial TEOS-10 equation of state is used for rho(t,s,z).
+      !!         Check value: rho = 1028.21993233072 kg/m^3 for z=3000 dbar, ct=3 Celcius, sa=35.5 g/kg
+      !!
+      !!     nn_eos =  0 : polynomial EOS-80 equation of state is used for rho(t,s,z).
+      !!         Check value: rho = 1028.35011066567 kg/m^3 for z=3000 dbar, pt=3 Celcius, sp=35.5 psu
+      !!
+      !!     nn_eos =  1 : simplified equation of state
+      !!              prd(t,s,z) = ( -a0*(1+lambda/2*(T-T0)+mu*z+nu*(S-S0))*(T-T0) + b0*(S-S0) ) / rau0
+      !!              linear case function of T only: rn_alpha<>0, other coefficients = 0
+      !!              linear eos function of T and S: rn_alpha and rn_beta<>0, other coefficients=0
+      !!              Vallis like equation: use default values of coefficients
       !!
       !! ** Action  :   compute prd , the in situ density (no units)
       !!
-      !! References :   Jackett and McDougall, J. Atmos. Ocean. Tech., 1994
-      !!----------------------------------------------------------------------
-      !!
-      REAL(wp), DIMENSION(:,:,:,:), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celcius]
-      !                                                      ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(:,:,:)  , INTENT(  out) ::   prd   ! in situ density            [-]
-      REAL(wp), DIMENSION(:,:,:)  , INTENT(in   ) ::   pdep  ! depth                      [m]
-      !!
-      INTEGER  ::   ji, jj, jk           ! dummy loop indices
-      REAL(wp) ::   zt , zs , zh , zsr   ! local scalars
-      REAL(wp) ::   zr1, zr2, zr3, zr4   !   -      -
-      REAL(wp) ::   zrhop, ze, zbw, zb   !   -      -
-      REAL(wp) ::   zd , zc , zaw, za    !   -      -
-      REAL(wp) ::   zb1, za1, zkw, zk0   !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zws
-      !!----------------------------------------------------------------------
-
-      !
-      IF( nn_timing == 1 ) CALL timing_start('eos')
-      !
-      CALL wrk_alloc( jpi, jpj, jpk, zws )
+      !! References :   Roquet et al, Ocean Modelling, in preparation (2014)
+      !!                Vallis, Atmospheric and Oceanic Fluid Dynamics, 2006
+      !!                TEOS-10 Manual, 2010
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celcius]
+      !                                                               ! 2 : salinity               [psu]
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   prd   ! in situ density            [-]
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pdep  ! depth                      [m]
+      !
+      INTEGER  ::   ji, jj, jk                ! dummy loop indices
+      REAL(wp) ::   zt , zh , zs , ztm        ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3   !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )   CALL timing_start('eos-insitu')
       !
       SELECT CASE( nn_eos )
       !
-      CASE( 0 )                !==  Jackett and McDougall (1994) formulation  ==!
-!CDIR NOVERRCHK
-         zws(:,:,:) = SQRT( ABS( pts(:,:,:,jp_sal) ) )
+      CASE( -1, 0 )                !==  polynomial TEOS-10 / EOS-80 ==!
          !
          DO jk = 1, jpkm1
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zt = pts   (ji,jj,jk,jp_tem)
-                  zs = pts   (ji,jj,jk,jp_sal)
-                  zh = pdep(ji,jj,jk)        ! depth
-                  zsr= zws   (ji,jj,jk)        ! square root salinity
-                  !
-                  ! compute volumic mass pure water at atm pressure
-                  zr1= ( ( ( ( 6.536332e-9_wp  *zt - 1.120083e-6_wp )*zt + 1.001685e-4_wp )*zt   &
-                     &        -9.095290e-3_wp )*zt + 6.793952e-2_wp )*zt +  999.842594_wp
-                  ! seawater volumic mass atm pressure
-                  zr2= ( ( ( 5.3875e-9_wp*zt-8.2467e-7_wp ) *zt+7.6438e-5_wp ) *zt        &
-                     &                      -4.0899e-3_wp ) *zt+0.824493_wp
-                  zr3= ( -1.6546e-6_wp*zt+1.0227e-4_wp )    *zt-5.72466e-3_wp
-                  zr4= 4.8314e-4_wp
-                  !
-                  ! potential volumic mass (reference to the surface)
-                  zrhop= ( zr4*zs + zr3*zsr + zr2 ) *zs + zr1
-                  !
-                  ! add the compression terms
-                  ze = ( -3.508914e-8_wp*zt-1.248266e-8_wp ) *zt-2.595994e-6_wp
-                  zbw= (  1.296821e-6_wp*zt-5.782165e-9_wp ) *zt+1.045941e-4_wp
-                  zb = zbw + ze * zs
-                  !
-                  zd = -2.042967e-2_wp
-                  zc =   (-7.267926e-5_wp*zt+2.598241e-3_wp ) *zt+0.1571896_wp
-                  zaw= ( ( 5.939910e-6_wp*zt+2.512549e-3_wp ) *zt-0.1028859_wp ) *zt - 4.721788_wp
-                  za = ( zd*zsr + zc ) *zs + zaw
-                  !
-                  zb1=   (-0.1909078_wp*zt+7.390729_wp )        *zt-55.87545_wp
-                  za1= ( ( 2.326469e-3_wp*zt+1.553190_wp)       *zt-65.00517_wp ) *zt+1044.077_wp
-                  zkw= ( ( (-1.361629e-4_wp*zt-1.852732e-2_wp ) *zt-30.41638_wp ) *zt + 2098.925_wp ) *zt+190925.6_wp
-                  zk0= ( zb1*zsr + za1 )*zs + zkw
-                  !
-                  ! masked in situ density anomaly
-                  prd(ji,jj,jk) = (  zrhop / (  1.0_wp - zh / ( zk0 - zh * ( za - zh * zb ) )  )    &
-                     &             - rau0  ) * r1_rau0 * tmask(ji,jj,jk)
+                  !
+                  zh  = pdep(ji,jj,jk) * r1_Z0                                  ! depth
+                  zt  = pts (ji,jj,jk,jp_tem) * r1_T0                           ! temperature
+                  zs  = SQRT( ABS( pts(ji,jj,jk,jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+                  ztm = tmask(ji,jj,jk)                                         ! tmask
+                  !
+                  zn3 = EOS013*zt   &
+                     &   + EOS103*zs+EOS003
+                     !
+                  zn2 = (EOS022*zt   &
+                     &   + EOS112*zs+EOS012)*zt   &
+                     &   + (EOS202*zs+EOS102)*zs+EOS002
+                     !
+                  zn1 = (((EOS041*zt   &
+                     &   + EOS131*zs+EOS031)*zt   &
+                     &   + (EOS221*zs+EOS121)*zs+EOS021)*zt   &
+                     &   + ((EOS311*zs+EOS211)*zs+EOS111)*zs+EOS011)*zt   &
+                     &   + (((EOS401*zs+EOS301)*zs+EOS201)*zs+EOS101)*zs+EOS001
+                     !
+                  zn0 = (((((EOS060*zt   &
+                     &   + EOS150*zs+EOS050)*zt   &
+                     &   + (EOS240*zs+EOS140)*zs+EOS040)*zt   &
+                     &   + ((EOS330*zs+EOS230)*zs+EOS130)*zs+EOS030)*zt   &
+                     &   + (((EOS420*zs+EOS320)*zs+EOS220)*zs+EOS120)*zs+EOS020)*zt   &
+                     &   + ((((EOS510*zs+EOS410)*zs+EOS310)*zs+EOS210)*zs+EOS110)*zs+EOS010)*zt   &
+                     &   + (((((EOS600*zs+EOS500)*zs+EOS400)*zs+EOS300)*zs+EOS200)*zs+EOS100)*zs+EOS000
+                     !
+                  zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+                  !
+                  prd(ji,jj,jk) = (  zn * r1_rau0 - 1._wp  ) * ztm  ! density anomaly (masked)
+                  !
                END DO
             END DO
          END DO
          !
-      CASE( 1 )                !==  Linear formulation function of temperature only  ==!
+      CASE( 1 )                !==  simplified EOS  ==!
+         !
          DO jk = 1, jpkm1
-            prd(:,:,jk) = ( 0.0285_wp - rn_alpha * pts(:,:,jk,jp_tem) ) * tmask(:,:,jk)
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zt  = pts  (ji,jj,jk,jp_tem) - 10._wp
+                  zs  = pts  (ji,jj,jk,jp_sal) - 35._wp
+                  zh  = pdep (ji,jj,jk)
+                  ztm = tmask(ji,jj,jk)
+                  !
+                  zn =  - rn_a0 * ( 1._wp + 0.5_wp*rn_lambda1*zt + rn_mu1*zh ) * zt   &
+                     &  + rn_b0 * ( 1._wp - 0.5_wp*rn_lambda2*zs - rn_mu2*zh ) * zs   &
+                     &  - rn_nu * zt * zs
+                     !                                 
+                  prd(ji,jj,jk) = zn * r1_rau0 * ztm                ! density anomaly (masked)
+               END DO
+            END DO
          END DO
          !
-      CASE( 2 )                !==  Linear formulation function of temperature and salinity  ==!
-         DO jk = 1, jpkm1
-            prd(:,:,jk) = ( rn_beta  * pts(:,:,jk,jp_sal) - rn_alpha * pts(:,:,jk,jp_tem) ) * tmask(:,:,jk)
-         END DO
-         !
       END SELECT
       !
-      IF(ln_ctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos  : ', ovlap=1, kdim=jpk )
-      !
-      CALL wrk_dealloc( jpi, jpj, jpk, zws )
-      !
-      IF( nn_timing == 1 ) CALL timing_stop('eos')
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos-insitu  : ', ovlap=1, kdim=jpk )
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('eos-insitu')
       !
    END SUBROUTINE eos_insitu
@@ -208,42 +303,8 @@
       !!     namelist parameter nn_eos.
       !!
-      !! ** Method  :
-      !!      nn_eos = 0 : Jackett and McDougall (1994) equation of state.
-      !!         the in situ density is computed directly as a function of
-      !!         potential temperature relative to the surface (the opa t
-      !!         variable), salt and pressure (assuming no pressure variation
-      !!         along geopotential surfaces, i.e. the pressure p in decibars
-      !!         is approximated by the depth in meters.
-      !!              prd(t,s,p) = ( rho(t,s,p) - rau0 ) / rau0
-      !!              rhop(t,s)  = rho(t,s,0)
-      !!         with pressure                      p        decibars
-      !!              potential temperature         t        deg celsius
-      !!              salinity                      s        psu
-      !!              reference volumic mass        rau0     kg/m**3
-      !!              in situ volumic mass          rho      kg/m**3
-      !!              in situ density anomalie      prd      no units
-      !!
-      !!         Check value: rho = 1060.93298 kg/m**3 for p=10000 dbar,
-      !!          t = 40 deg celcius, s=40 psu
-      !!
-      !!      nn_eos = 1 : linear equation of state function of temperature only
-      !!              prd(t) = ( rho(t) - rau0 ) / rau0 = 0.028 - rn_alpha * t
-      !!              rhop(t,s)  = rho(t,s)
-      !!
-      !!      nn_eos = 2 : linear equation of state function of temperature and
-      !!               salinity
-      !!              prd(t,s) = ( rho(t,s) - rau0 ) / rau0
-      !!                       = rn_beta * s - rn_alpha * tn - 1.
-      !!              rhop(t,s)  = rho(t,s)
-      !!      Note that no boundary condition problem occurs in this routine
-      !!      as (tn,sn) or (ta,sa) are defined over the whole domain.
-      !!
       !! ** Action  : - prd  , the in situ density (no units)
       !!              - prhop, the potential volumic mass (Kg/m3)
       !!
-      !! References :   Jackett and McDougall, J. Atmos. Ocean. Tech., 1994
-      !!                Brown and Campana, Mon. Weather Rev., 1978
-      !!----------------------------------------------------------------------
-      !!
+      !!----------------------------------------------------------------------
       REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts    ! 1 : potential temperature  [Celcius]
       !                                                                ! 2 : salinity               [psu]
@@ -252,84 +313,81 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pdep   ! depth                      [m]
       !
-      INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      REAL(wp) ::   zt, zs, zh, zsr, zr1, zr2, zr3, zr4, zrhop, ze, zbw   ! local scalars
-      REAL(wp) ::   zb, zd, zc, zaw, za, zb1, za1, zkw, zk0               !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zws
-      !!----------------------------------------------------------------------
-      !
-      IF( nn_timing == 1 ) CALL timing_start('eos-p')
-      !
-      CALL wrk_alloc( jpi, jpj, jpk, zws )
+      INTEGER  ::   ji, jj, jk                ! dummy loop indices
+      REAL(wp) ::   zt , zh , zs , ztm        ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3   !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )   CALL timing_start('eos-pot')
       !
       SELECT CASE ( nn_eos )
       !
-      CASE( 0 )                !==  Jackett and McDougall (1994) formulation  ==!
-!CDIR NOVERRCHK
-         zws(:,:,:) = SQRT( ABS( pts(:,:,:,jp_sal) ) )
+      CASE( -1, 0 )                !==  polynomial TEOS-10 / EOS-80 ==!
          !
          DO jk = 1, jpkm1
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zt = pts   (ji,jj,jk,jp_tem)
-                  zs = pts   (ji,jj,jk,jp_sal)
-                  zh = pdep(ji,jj,jk)        ! depth
-                  zsr= zws   (ji,jj,jk)        ! square root salinity
-                  !
-                  ! compute volumic mass pure water at atm pressure
-                  zr1= ( ( ( ( 6.536332e-9_wp*zt-1.120083e-6_wp )*zt+1.001685e-4_wp )*zt   &
-                     &                          -9.095290e-3_wp )*zt+6.793952e-2_wp )*zt+999.842594_wp
-                  ! seawater volumic mass atm pressure
-                  zr2= ( ( ( 5.3875e-9_wp*zt-8.2467e-7_wp ) *zt+7.6438e-5_wp ) *zt   &
-                     &                                         -4.0899e-3_wp ) *zt+0.824493_wp
-                  zr3= ( -1.6546e-6_wp*zt+1.0227e-4_wp )    *zt-5.72466e-3_wp
-                  zr4= 4.8314e-4_wp
-                  !
-                  ! potential volumic mass (reference to the surface)
-                  zrhop= ( zr4*zs + zr3*zsr + zr2 ) *zs + zr1
-                  !
-                  ! save potential volumic mass
-                  prhop(ji,jj,jk) = zrhop * tmask(ji,jj,jk)
-                  !
-                  ! add the compression terms
-                  ze = ( -3.508914e-8_wp*zt-1.248266e-8_wp ) *zt-2.595994e-6_wp
-                  zbw= (  1.296821e-6_wp*zt-5.782165e-9_wp ) *zt+1.045941e-4_wp
-                  zb = zbw + ze * zs
-                  !
-                  zd = -2.042967e-2_wp
-                  zc =   (-7.267926e-5_wp*zt+2.598241e-3_wp ) *zt+0.1571896_wp
-                  zaw= ( ( 5.939910e-6_wp*zt+2.512549e-3_wp ) *zt-0.1028859_wp ) *zt - 4.721788_wp
-                  za = ( zd*zsr + zc ) *zs + zaw
-                  !
-                  zb1=   (  -0.1909078_wp  *zt+7.390729_wp    ) *zt-55.87545_wp
-                  za1= ( (   2.326469e-3_wp*zt+1.553190_wp    ) *zt-65.00517_wp ) *zt + 1044.077_wp
-                  zkw= ( ( (-1.361629e-4_wp*zt-1.852732e-2_wp ) *zt-30.41638_wp ) *zt + 2098.925_wp ) *zt+190925.6_wp
-                  zk0= ( zb1*zsr + za1 )*zs + zkw
-                  !
-                  ! masked in situ density anomaly
-                  prd(ji,jj,jk) = (  zrhop / (  1.0_wp - zh / ( zk0 - zh * ( za - zh * zb ) )  )    &
-                     &             - rau0  ) * r1_rau0 * tmask(ji,jj,jk)
+                  !
+                  zh  = pdep(ji,jj,jk) * r1_Z0                                  ! depth
+                  zt  = pts (ji,jj,jk,jp_tem) * r1_T0                           ! temperature
+                  zs  = SQRT( ABS( pts(ji,jj,jk,jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+                  ztm = tmask(ji,jj,jk)                                         ! tmask
+                  !
+                  zn3 = EOS013*zt   &
+                     &   + EOS103*zs+EOS003
+                     !
+                  zn2 = (EOS022*zt   &
+                     &   + EOS112*zs+EOS012)*zt   &
+                     &   + (EOS202*zs+EOS102)*zs+EOS002
+                     !
+                  zn1 = (((EOS041*zt   &
+                     &   + EOS131*zs+EOS031)*zt   &
+                     &   + (EOS221*zs+EOS121)*zs+EOS021)*zt   &
+                     &   + ((EOS311*zs+EOS211)*zs+EOS111)*zs+EOS011)*zt   &
+                     &   + (((EOS401*zs+EOS301)*zs+EOS201)*zs+EOS101)*zs+EOS001
+                     !
+                  zn0 = (((((EOS060*zt   &
+                     &   + EOS150*zs+EOS050)*zt   &
+                     &   + (EOS240*zs+EOS140)*zs+EOS040)*zt   &
+                     &   + ((EOS330*zs+EOS230)*zs+EOS130)*zs+EOS030)*zt   &
+                     &   + (((EOS420*zs+EOS320)*zs+EOS220)*zs+EOS120)*zs+EOS020)*zt   &
+                     &   + ((((EOS510*zs+EOS410)*zs+EOS310)*zs+EOS210)*zs+EOS110)*zs+EOS010)*zt   &
+                     &   + (((((EOS600*zs+EOS500)*zs+EOS400)*zs+EOS300)*zs+EOS200)*zs+EOS100)*zs+EOS000
+                     !
+                  zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+                  !
+                  prhop(ji,jj,jk) = zn0 * ztm                           ! potential density referenced at the surface
+                  !
+                  prd(ji,jj,jk) = (  zn * r1_rau0 - 1._wp  ) * ztm      ! density anomaly (masked)
                END DO
             END DO
          END DO
          !
-      CASE( 1 )                !==  Linear formulation = F( temperature )  ==!
+      CASE( 1 )                !==  simplified EOS  ==!
+         !
          DO jk = 1, jpkm1
-            prd  (:,:,jk) = ( 0.0285_wp - rn_alpha * pts(:,:,jk,jp_tem) )        * tmask(:,:,jk)
-            prhop(:,:,jk) = ( 1.e0_wp   +            prd (:,:,jk)       ) * rau0 * tmask(:,:,jk)
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zt  = pts  (ji,jj,jk,jp_tem) - 10._wp
+                  zs  = pts  (ji,jj,jk,jp_sal) - 35._wp
+                  zh  = pdep (ji,jj,jk)
+                  ztm = tmask(ji,jj,jk)
+                  !                                                     ! potential density referenced at the surface
+                  zn =  - rn_a0 * ( 1._wp + 0.5_wp*rn_lambda1*zt ) * zt   &
+                     &  + rn_b0 * ( 1._wp - 0.5_wp*rn_lambda2*zs ) * zs   &
+                     &  - rn_nu * zt * zs
+                  prhop(ji,jj,jk) = ( rau0 + zn ) * ztm
+                  !                                                     ! density anomaly (masked)
+                  zn = zn - ( rn_a0 * rn_mu1 * zt + rn_b0 * rn_mu2 * zs ) * zh
+                  prd(ji,jj,jk) = zn * r1_rau0 * ztm
+                  !
+               END DO
+            END DO
          END DO
          !
-      CASE( 2 )                !==  Linear formulation = F( temperature , salinity )  ==!
-         DO jk = 1, jpkm1
-            prd  (:,:,jk) = ( rn_beta  * pts(:,:,jk,jp_sal) - rn_alpha * pts(:,:,jk,jp_tem) )        * tmask(:,:,jk)
-            prhop(:,:,jk) = ( 1.e0_wp  + prd (:,:,jk) )                                       * rau0 * tmask(:,:,jk)
-         END DO
-         !
       END SELECT
       !
-      IF(ln_ctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos-p: ', tab3d_2=prhop, clinfo2=' pot : ', ovlap=1, kdim=jpk )
-      !
-      CALL wrk_dealloc( jpi, jpj, jpk, zws )
-      !
-      IF( nn_timing == 1 ) CALL timing_stop('eos-p')
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=prd, clinfo1=' eos-pot: ', tab3d_2=prhop, clinfo2=' pot : ', ovlap=1, kdim=jpk )
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('eos-pot')
       !
    END SUBROUTINE eos_insitu_pot
@@ -344,324 +402,189 @@
       !!      defined through the namelist parameter nn_eos. * 2D field case
       !!
-      !! ** Method :
-      !!      nn_eos = 0 : Jackett and McDougall (1994) equation of state.
-      !!         the in situ density is computed directly as a function of
-      !!         potential temperature relative to the surface (the opa t
-      !!         variable), salt and pressure (assuming no pressure variation
-      !!         along geopotential surfaces, i.e. the pressure p in decibars
-      !!         is approximated by the depth in meters.
-      !!              prd(t,s,p) = ( rho(t,s,p) - rau0 ) / rau0
-      !!         with pressure                      p        decibars
-      !!              potential temperature         t        deg celsius
-      !!              salinity                      s        psu
-      !!              reference volumic mass        rau0     kg/m**3
-      !!              in situ volumic mass          rho      kg/m**3
-      !!              in situ density anomalie      prd      no units
-      !!         Check value: rho = 1060.93298 kg/m**3 for p=10000 dbar,
-      !!          t = 40 deg celcius, s=40 psu
-      !!      nn_eos = 1 : linear equation of state function of temperature only
-      !!              prd(t) = 0.0285 - rn_alpha * t
-      !!      nn_eos = 2 : linear equation of state function of temperature and
-      !!               salinity
-      !!              prd(t,s) = rn_beta * s - rn_alpha * tn - 1.
-      !!      Note that no boundary condition problem occurs in this routine
-      !!      as pts are defined over the whole domain.
-      !!
-      !! ** Action  : - prd , the in situ density (no units)
-      !!
-      !! References :   Jackett and McDougall, J. Atmos. Ocean. Tech., 1994
-      !!----------------------------------------------------------------------
-      !!
+      !! ** Action  : - prd , the in situ density (no units) (unmasked)
+      !!
+      !!----------------------------------------------------------------------
       REAL(wp), DIMENSION(jpi,jpj,jpts), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celcius]
       !                                                           ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj)     , INTENT(in   ) ::   pdep  ! depth                  [m]
+      REAL(wp), DIMENSION(jpi,jpj)     , INTENT(in   ) ::   pdep  ! depth                      [m]
       REAL(wp), DIMENSION(jpi,jpj)     , INTENT(  out) ::   prd   ! in situ density
-      !!
-      INTEGER  ::   ji, jj                    ! dummy loop indices
-      REAL(wp) ::   zt, zs, zh, zsr, zr1, zr2, zr3, zr4, zrhop, ze, zbw   ! temporary scalars
-      REAL(wp) ::   zb, zd, zc, zaw, za, zb1, za1, zkw, zk0, zmask        !    -         -
-      REAL(wp), POINTER, DIMENSION(:,:) :: zws
-      !!----------------------------------------------------------------------
-      !
-      IF( nn_timing == 1 ) CALL timing_start('eos2d')
-      !
-      CALL wrk_alloc( jpi, jpj, zws )
-      !
-
+      !
+      INTEGER  ::   ji, jj, jk                ! dummy loop indices
+      REAL(wp) ::   zt , zh , zs              ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3   !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )   CALL timing_start('eos2d')
+      !
       prd(:,:) = 0._wp
-
+      !
       SELECT CASE( nn_eos )
       !
-      CASE( 0 )                !==  Jackett and McDougall (1994) formulation  ==!
-      !
-!CDIR NOVERRCHK
+      CASE( -1, 0 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
          DO jj = 1, jpjm1
-!CDIR NOVERRCHK
             DO ji = 1, fs_jpim1   ! vector opt.
-               zws(ji,jj) = SQRT( ABS( pts(ji,jj,jp_sal) ) )
+               !
+               zh  = pdep(ji,jj) * r1_Z0                                  ! depth
+               zt  = pts (ji,jj,jp_tem) * r1_T0                           ! temperature
+               zs  = SQRT( ABS( pts(ji,jj,jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+               !
+               zn3 = EOS013*zt   &
+                  &   + EOS103*zs+EOS003
+                  !
+               zn2 = (EOS022*zt   &
+                  &   + EOS112*zs+EOS012)*zt   &
+                  &   + (EOS202*zs+EOS102)*zs+EOS002
+                  !
+               zn1 = (((EOS041*zt   &
+                  &   + EOS131*zs+EOS031)*zt   &
+                  &   + (EOS221*zs+EOS121)*zs+EOS021)*zt   &
+                  &   + ((EOS311*zs+EOS211)*zs+EOS111)*zs+EOS011)*zt   &
+                  &   + (((EOS401*zs+EOS301)*zs+EOS201)*zs+EOS101)*zs+EOS001
+                  !
+               zn0 = (((((EOS060*zt   &
+                  &   + EOS150*zs+EOS050)*zt   &
+                  &   + (EOS240*zs+EOS140)*zs+EOS040)*zt   &
+                  &   + ((EOS330*zs+EOS230)*zs+EOS130)*zs+EOS030)*zt   &
+                  &   + (((EOS420*zs+EOS320)*zs+EOS220)*zs+EOS120)*zs+EOS020)*zt   &
+                  &   + ((((EOS510*zs+EOS410)*zs+EOS310)*zs+EOS210)*zs+EOS110)*zs+EOS010)*zt   &
+                  &   + (((((EOS600*zs+EOS500)*zs+EOS400)*zs+EOS300)*zs+EOS200)*zs+EOS100)*zs+EOS000
+                  !
+               zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+               !
+               prd(ji,jj) = zn * r1_rau0 - 1._wp               ! unmasked in situ density anomaly
+               !
             END DO
          END DO
+         !
+         CALL lbc_lnk( prd, 'T', 1. )                    ! Lateral boundary conditions
+         !
+      CASE( 1 )                !==  simplified EOS  ==!
+         !
          DO jj = 1, jpjm1
             DO ji = 1, fs_jpim1   ! vector opt.
-               zmask = tmask(ji,jj,1)          ! land/sea bottom mask = surf. mask
-               zt    = pts  (ji,jj,jp_tem)            ! interpolated T
-               zs    = pts  (ji,jj,jp_sal)            ! interpolated S
-               zsr   = zws  (ji,jj)            ! square root of interpolated S
-               zh    = pdep (ji,jj)            ! depth at the partial step level
-               !
-               ! compute volumic mass pure water at atm pressure
-               zr1 = ( ( ( ( 6.536332e-9_wp*zt-1.120083e-6_wp )*zt+1.001685e-4_wp )*zt   &
-                  &                        -9.095290e-3_wp )*zt+6.793952e-2_wp )*zt+999.842594_wp
-               ! seawater volumic mass atm pressure
-               zr2 = ( ( ( 5.3875e-9_wp*zt-8.2467e-7_wp )*zt+7.6438e-5_wp ) *zt   &
-                  &                                   -4.0899e-3_wp ) *zt+0.824493_wp
-               zr3 = ( -1.6546e-6_wp*zt+1.0227e-4_wp ) *zt-5.72466e-3_wp
-               zr4 = 4.8314e-4_wp
-               !
-               ! potential volumic mass (reference to the surface)
-               zrhop= ( zr4*zs + zr3*zsr + zr2 ) *zs + zr1
-               !
-               ! add the compression terms
-               ze = ( -3.508914e-8_wp*zt-1.248266e-8_wp ) *zt-2.595994e-6_wp
-               zbw= (  1.296821e-6_wp*zt-5.782165e-9_wp ) *zt+1.045941e-4_wp
-               zb = zbw + ze * zs
-               !
-               zd =    -2.042967e-2_wp
-               zc =   (-7.267926e-5_wp*zt+2.598241e-3_wp ) *zt+0.1571896_wp
-               zaw= ( ( 5.939910e-6_wp*zt+2.512549e-3_wp ) *zt-0.1028859_wp ) *zt -4.721788_wp
-               za = ( zd*zsr + zc ) *zs + zaw
-               !
-               zb1=     (-0.1909078_wp  *zt+7.390729_wp      ) *zt-55.87545_wp
-               za1=   ( ( 2.326469e-3_wp*zt+1.553190_wp      ) *zt-65.00517_wp ) *zt+1044.077_wp
-               zkw= ( ( (-1.361629e-4_wp*zt-1.852732e-2_wp   ) *zt-30.41638_wp ) *zt   &
-                  &                             +2098.925_wp ) *zt+190925.6_wp
-               zk0= ( zb1*zsr + za1 )*zs + zkw
-               !
-               ! masked in situ density anomaly
-               prd(ji,jj) = ( zrhop / (  1.0_wp - zh / ( zk0 - zh * ( za - zh * zb ) )  ) - rau0 ) / rau0 * zmask
+               !
+               zt    = pts  (ji,jj,jp_tem)  - 10._wp
+               zs    = pts  (ji,jj,jp_sal)  - 35._wp
+               zh    = pdep (ji,jj)                         ! depth at the partial step level
+               !
+               zn =  - rn_a0 * ( 1._wp + 0.5_wp*rn_lambda1*zt + rn_mu1*zh ) * zt   &
+                  &  + rn_b0 * ( 1._wp - 0.5_wp*rn_lambda2*zs - rn_mu2*zh ) * zs   &
+                  &  - rn_nu * zt * zs
+                  !
+               prd(ji,jj) = zn * r1_rau0               ! unmasked in situ density anomaly
+               !
             END DO
          END DO
          !
-      CASE( 1 )                !==  Linear formulation = F( temperature )  ==!
-         DO jj = 1, jpjm1
-            DO ji = 1, fs_jpim1   ! vector opt.
-               prd(ji,jj) = ( 0.0285_wp - rn_alpha * pts(ji,jj,jp_tem) ) * tmask(ji,jj,1)
-            END DO
-         END DO
-         !
-      CASE( 2 )                !==  Linear formulation = F( temperature , salinity )  ==!
-         DO jj = 1, jpjm1
-            DO ji = 1, fs_jpim1   ! vector opt.
-               prd(ji,jj) = ( rn_beta * pts(ji,jj,jp_sal) - rn_alpha * pts(ji,jj,jp_tem) ) * tmask(ji,jj,1)
-            END DO
-         END DO
+         CALL lbc_lnk( prd, 'T', 1. )                    ! Lateral boundary conditions
          !
       END SELECT
-
+      !
       IF(ln_ctl)   CALL prt_ctl( tab2d_1=prd, clinfo1=' eos2d: ' )
       !
-      CALL wrk_dealloc( jpi, jpj, zws )
-      !
-      IF( nn_timing == 1 ) CALL timing_stop('eos2d')
+      IF( nn_timing == 1 )   CALL timing_stop('eos2d')
       !
    END SUBROUTINE eos_insitu_2d
 
 
-   SUBROUTINE eos_bn2( pts, pn2 )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE eos_bn2  ***
-      !!
-      !! ** Purpose :   Compute the local Brunt-Vaisala frequency at the time-
-      !!      step of the input arguments
-      !!
-      !! ** Method :
-      !!       * nn_eos = 0  : UNESCO sea water properties
-      !!         The brunt-vaisala frequency is computed using the polynomial
-      !!      polynomial expression of McDougall (1987):
-      !!            N^2 = grav * beta * ( alpha/beta*dk[ t ] - dk[ s ] )/e3w
-      !!      If lk_zdfddm=T, the heat/salt buoyancy flux ratio Rrau is
-      !!      computed and used in zdfddm module :
-      !!              Rrau = alpha/beta * ( dk[ t ] / dk[ s ] )
-      !!       * nn_eos = 1  : linear equation of state (temperature only)
-      !!            N^2 = grav * rn_alpha * dk[ t ]/e3w
-      !!       * nn_eos = 2  : linear equation of state (temperature & salinity)
-      !!            N^2 = grav * (rn_alpha * dk[ t ] - rn_beta * dk[ s ] ) / e3w
-      !!      The use of potential density to compute N^2 introduces e r r o r
-      !!      in the sign of N^2 at great depths. We recommand the use of
-      !!      nn_eos = 0, except for academical studies.
-      !!        Macro-tasked on horizontal slab (jk-loop)
-      !!      N.B. N^2 is set to zero at the first level (JK=1) in inidtr
-      !!      and is never used at this level.
-      !!
-      !! ** Action  : - pn2 : the brunt-vaisala frequency
-      !!
-      !! References :   McDougall, J. Phys. Oceanogr., 17, 1950-1964, 1987.
-      !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts   ! 1 : potential temperature  [Celcius]
-      !                                                               ! 2 : salinity               [psu]
-      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   pn2   ! Brunt-Vaisala frequency    [s-1]
-      !!
-      INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      REAL(wp) ::   zgde3w, zt, zs, zh, zalbet, zbeta   ! local scalars
-#if defined key_zdfddm
-      REAL(wp) ::   zds   ! local scalars
-#endif
-      !!----------------------------------------------------------------------
-
-      !
-      IF( nn_timing == 1 ) CALL timing_start('bn2')
-      !
-      ! pn2 : interior points only (2=< jk =< jpkm1 )
-      ! --------------------------
-      !
-      SELECT CASE( nn_eos )
-      !
-      CASE( 0 )                !==  Jackett and McDougall (1994) formulation  ==!
-         DO jk = 2, jpkm1
+   SUBROUTINE rab_3d( pts, pab )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE rab_3d  ***
+      !!
+      !! ** Purpose :   Calculates thermal/haline expansion ratio at T-points
+      !!
+      !! ** Method  :   calculates alpha / beta at T-points
+      !!
+      !! ** Action  : - pab     : thermal/haline expansion ratio at T-points
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts   ! pot. temperature & salinity
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pab   ! thermal/haline expansion ratio
+      !
+      INTEGER  ::   ji, jj, jk                ! dummy loop indices
+      REAL(wp) ::   zt , zh , zs , ztm        ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3   !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )   CALL timing_start('rab_3d')
+      !
+      SELECT CASE ( nn_eos )
+      !
+      CASE( -1, 0 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+         DO jk = 1, jpkm1
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zgde3w = grav / fse3w(ji,jj,jk)
-                  zt = 0.5 * ( pts(ji,jj,jk,jp_tem) + pts(ji,jj,jk-1,jp_tem) )         ! potential temperature at w-pt
-                  zs = 0.5 * ( pts(ji,jj,jk,jp_sal) + pts(ji,jj,jk-1,jp_sal) ) - 35.0  ! salinity anomaly (s-35) at w-pt
-                  zh = fsdepw(ji,jj,jk)                                                ! depth in meters  at w-point
-                  !
-                  zalbet = ( ( ( - 0.255019e-07_wp * zt + 0.298357e-05_wp ) * zt   &   ! ratio alpha/beta
-                     &                                  - 0.203814e-03_wp ) * zt   &
-                     &                                  + 0.170907e-01_wp ) * zt   &
-                     &   +         0.665157e-01_wp                                 &
-                     &   +     ( - 0.678662e-05_wp * zs                            &
-                     &           - 0.846960e-04_wp * zt + 0.378110e-02_wp ) * zs   &
-                     &   +   ( ( - 0.302285e-13_wp * zh                            &
-                     &           - 0.251520e-11_wp * zs                            &
-                     &           + 0.512857e-12_wp * zt * zt              ) * zh   &
-                     &           - 0.164759e-06_wp * zs                            &
-                     &        +(   0.791325e-08_wp * zt - 0.933746e-06_wp ) * zt   &
-                     &                                  + 0.380374e-04_wp ) * zh
-                     !
-                  zbeta  = ( ( -0.415613e-09_wp * zt + 0.555579e-07_wp ) * zt      &   ! beta
-                     &                               - 0.301985e-05_wp ) * zt      &
-                     &   +       0.785567e-03_wp                                   &
-                     &   + (     0.515032e-08_wp * zs                              &
-                     &         + 0.788212e-08_wp * zt - 0.356603e-06_wp ) * zs     &
-                     &   + ( (   0.121551e-17_wp * zh                              &
-                     &         - 0.602281e-15_wp * zs                              &
-                     &         - 0.175379e-14_wp * zt + 0.176621e-12_wp ) * zh     &
-                     &                                + 0.408195e-10_wp   * zs     &
-                     &     + ( - 0.213127e-11_wp * zt + 0.192867e-09_wp ) * zt     &
-                     &                                - 0.121555e-07_wp ) * zh
-                     !
-                  pn2(ji,jj,jk) = zgde3w * zbeta * tmask(ji,jj,jk)           &   ! N^2
-                     &          * ( zalbet * ( pts(ji,jj,jk-1,jp_tem) - pts(ji,jj,jk,jp_tem) )   &
-                     &                     - ( pts(ji,jj,jk-1,jp_sal) - pts(ji,jj,jk,jp_sal) ) )
-#if defined key_zdfddm
-                  !                                                         !!bug **** caution a traiter zds=dk[S]= 0 !!!!
-                  zds = ( pts(ji,jj,jk-1,jp_sal) - pts(ji,jj,jk,jp_sal) )                    ! Rrau = (alpha / beta) (dk[t] / dk[s])
-                  IF ( ABS( zds) <= 1.e-20_wp ) zds = 1.e-20_wp
-                  rrau(ji,jj,jk) = zalbet * ( pts(ji,jj,jk-1,jp_tem) - pts(ji,jj,jk,jp_tem) ) / zds
-#endif
+                  !
+                  zh  = fsdept(ji,jj,jk) * r1_Z0                                ! depth
+                  zt  = pts (ji,jj,jk,jp_tem) * r1_T0                           ! temperature
+                  zs  = SQRT( ABS( pts(ji,jj,jk,jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+                  ztm = tmask(ji,jj,jk)                                         ! tmask
+                  !
+                  ! alpha
+                  zn3 = ALP003
+                  !
+                  zn2 = ALP012*zt + ALP102*zs+ALP002
+                  !
+                  zn1 = ((ALP031*zt   &
+                     &   + ALP121*zs+ALP021)*zt   &
+                     &   + (ALP211*zs+ALP111)*zs+ALP011)*zt   &
+                     &   + ((ALP301*zs+ALP201)*zs+ALP101)*zs+ALP001
+                     !
+                  zn0 = ((((ALP050*zt   &
+                     &   + ALP140*zs+ALP040)*zt   &
+                     &   + (ALP230*zs+ALP130)*zs+ALP030)*zt   &
+                     &   + ((ALP320*zs+ALP220)*zs+ALP120)*zs+ALP020)*zt   &
+                     &   + (((ALP410*zs+ALP310)*zs+ALP210)*zs+ALP110)*zs+ALP010)*zt   &
+                     &   + ((((ALP500*zs+ALP400)*zs+ALP300)*zs+ALP200)*zs+ALP100)*zs+ALP000
+                     !
+                  zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+                  !
+                  pab(ji,jj,jk,jp_tem) = zn * r1_rau0 * ztm
+                  !
+                  ! beta
+                  zn3 = BET003
+                  !
+                  zn2 = BET012*zt + BET102*zs+BET002
+                  !
+                  zn1 = ((BET031*zt   &
+                     &   + BET121*zs+BET021)*zt   &
+                     &   + (BET211*zs+BET111)*zs+BET011)*zt   &
+                     &   + ((BET301*zs+BET201)*zs+BET101)*zs+BET001
+                     !
+                  zn0 = ((((BET050*zt   &
+                     &   + BET140*zs+BET040)*zt   &
+                     &   + (BET230*zs+BET130)*zs+BET030)*zt   &
+                     &   + ((BET320*zs+BET220)*zs+BET120)*zs+BET020)*zt   &
+                     &   + (((BET410*zs+BET310)*zs+BET210)*zs+BET110)*zs+BET010)*zt   &
+                     &   + ((((BET500*zs+BET400)*zs+BET300)*zs+BET200)*zs+BET100)*zs+BET000
+                     !
+                  zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+                  !
+                  pab(ji,jj,jk,jp_sal) = zn / zs * r1_rau0 * ztm
+                  !
                END DO
             END DO
          END DO
          !
-      CASE( 1 )                !==  Linear formulation = F( temperature )  ==!
-         DO jk = 2, jpkm1
-            pn2(:,:,jk) = grav * rn_alpha * ( pts(:,:,jk-1,jp_tem) - pts(:,:,jk,jp_tem) ) / fse3w(:,:,jk) * tmask(:,:,jk)
-         END DO
-         !
-      CASE( 2 )                !==  Linear formulation = F( temperature , salinity )  ==!
-         DO jk = 2, jpkm1
-            pn2(:,:,jk) = grav * (  rn_alpha * ( pts(:,:,jk-1,jp_tem) - pts(:,:,jk,jp_tem) )      &
-               &                  - rn_beta  * ( pts(:,:,jk-1,jp_sal) - pts(:,:,jk,jp_sal) )  )   &
-               &               / fse3w(:,:,jk) * tmask(:,:,jk)
-         END DO
-#if defined key_zdfddm
-         DO jk = 2, jpkm1                                 ! Rrau = (alpha / beta) (dk[t] / dk[s])
+      CASE( 1 )                  !==  simplified EOS  ==!
+         !
+         DO jk = 1, jpkm1
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zds = ( pts(ji,jj,jk-1,jp_sal) - pts(ji,jj,jk,jp_sal) )
-                  IF ( ABS( zds ) <= 1.e-20_wp ) zds = 1.e-20_wp
-                  rrau(ji,jj,jk) = ralpbet * ( pts(ji,jj,jk-1,jp_tem) - pts(ji,jj,jk,jp_tem) ) / zds
+                  zt  = pts (ji,jj,jk,jp_tem) - 10._wp   ! pot. temperature anomaly (t-T0)
+                  zs  = pts (ji,jj,jk,jp_sal) - 35._wp   ! abs. salinity anomaly (s-S0)
+                  zh  = fsdept(ji,jj,jk)                 ! depth in meters at t-point
+                  ztm = tmask(ji,jj,jk)                  ! land/sea bottom mask = surf. mask
+                  !
+                  zn  = rn_a0 * ( 1._wp + rn_lambda1*zt + rn_mu1*zh ) + rn_nu*zs
+                  pab(ji,jj,jk,jp_tem) = zn * r1_rau0 * ztm   ! alpha
+                  !
+                  zn  = rn_b0 * ( 1._wp - rn_lambda2*zs - rn_mu2*zh ) - rn_nu*zt
+                  pab(ji,jj,jk,jp_sal) = zn * r1_rau0 * ztm   ! beta
+                  !
                END DO
             END DO
          END DO
-#endif
-      END SELECT
-
-      IF(ln_ctl)   CALL prt_ctl( tab3d_1=pn2, clinfo1=' bn2  : ', ovlap=1, kdim=jpk )
-#if defined key_zdfddm
-      IF(ln_ctl)   CALL prt_ctl( tab3d_1=rrau, clinfo1=' rrau : ', ovlap=1, kdim=jpk )
-#endif
-      !
-      IF( nn_timing == 1 ) CALL timing_stop('bn2')
-      !
-   END SUBROUTINE eos_bn2
-
-
-   SUBROUTINE eos_alpbet( pts, palpbet, beta0 )
-      !!----------------------------------------------------------------------
-      !!                 ***  ROUTINE eos_alpbet  ***
-      !!
-      !! ** Purpose :   Calculates the in situ thermal/haline expansion ratio at T-points
-      !!
-      !! ** Method  :   calculates alpha / beta ratio at T-points
-      !!       * nn_eos = 0  : UNESCO sea water properties
-      !!                       The alpha/beta ratio is returned as 3-D array palpbet using the polynomial
-      !!                       polynomial expression of McDougall (1987).
-      !!                       Scalar beta0 is returned = 1.
-      !!       * nn_eos = 1  : linear equation of state (temperature only)
-      !!                       The ratio is undefined, so we return alpha as palpbet
-      !!                       Scalar beta0 is returned = 0.
-      !!       * nn_eos = 2  : linear equation of state (temperature & salinity)
-      !!                       The alpha/beta ratio is returned as ralpbet
-      !!                       Scalar beta0 is returned = 1.
-      !!
-      !! ** Action  : - palpbet : thermal/haline expansion ratio at T-points
-      !!            :   beta0   : 1. or 0.
-      !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts       ! pot. temperature & salinity
-      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   palpbet   ! thermal/haline expansion ratio
-      REAL(wp),                              INTENT(  out) ::   beta0     ! set = 1 except with case 1 eos, rho=rho(T)
-      !!
-      INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      REAL(wp) ::   zt, zs, zh   ! local scalars
-      !!----------------------------------------------------------------------
-      !
-      IF( nn_timing == 1 ) CALL timing_start('eos_alpbet')
-      !
-      SELECT CASE ( nn_eos )
-      !
-      CASE ( 0 )               ! Jackett and McDougall (1994) formulation
-         DO jk = 1, jpk
-            DO jj = 1, jpj
-               DO ji = 1, jpi
-                  zt = pts(ji,jj,jk,jp_tem)           ! potential temperature
-                  zs = pts(ji,jj,jk,jp_sal) - 35._wp  ! salinity anomaly (s-35)
-                  zh = fsdept(ji,jj,jk)               ! depth in meters
-                  !
-                  palpbet(ji,jj,jk) =                                              &
-                     &     ( ( ( - 0.255019e-07_wp * zt + 0.298357e-05_wp ) * zt   &
-                     &                                  - 0.203814e-03_wp ) * zt   &
-                     &                                  + 0.170907e-01_wp ) * zt   &
-                     &   + 0.665157e-01_wp                                         &
-                     &   +     ( - 0.678662e-05_wp * zs                            &
-                     &           - 0.846960e-04_wp * zt + 0.378110e-02_wp ) * zs   &
-                     &   +   ( ( - 0.302285e-13_wp * zh                            &
-                     &           - 0.251520e-11_wp * zs                            &
-                     &           + 0.512857e-12_wp * zt * zt              ) * zh   &
-                     &           - 0.164759e-06_wp * zs                            &
-                     &        +(   0.791325e-08_wp * zt - 0.933746e-06_wp ) * zt   &
-                     &                                  + 0.380374e-04_wp ) * zh
-               END DO
-            END DO
-         END DO
-         beta0 = 1._wp
-         !
-      CASE ( 1 )              !==  Linear formulation = F( temperature )  ==!
-         palpbet(:,:,:) = rn_alpha
-         beta0 = 0._wp
-         !
-      CASE ( 2 )              !==  Linear formulation = F( temperature , salinity )  ==!
-         palpbet(:,:,:) = ralpbet
-         beta0 = 1._wp
          !
       CASE DEFAULT
@@ -672,56 +595,582 @@
       END SELECT
       !
-      IF( nn_timing == 1 ) CALL timing_stop('eos_alpbet')
-      !
-   END SUBROUTINE eos_alpbet
-
-
-   FUNCTION tfreez( psal, pdep ) RESULT( ptf )
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=pab(:,:,:,jp_tem), clinfo1=' rab_3d_t: ', &
+         &                       tab3d_2=pab(:,:,:,jp_sal), clinfo2=' rab_3d_s : ', ovlap=1, kdim=jpk )
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('rab_3d')
+      !
+   END SUBROUTINE rab_3d
+
+   SUBROUTINE rab_2d( pts, pdep, pab )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE rab_2d  ***
+      !!
+      !! ** Purpose :   Calculates thermal/haline expansion ratio for a 2d field (unmasked)
+      !!
+      !! ** Action  : - pab     : thermal/haline expansion ratio at T-points
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpts)    , INTENT(in   ) ::   pts    ! pot. temperature & salinity
+      REAL(wp), DIMENSION(jpi,jpj)         , INTENT(in   ) ::   pdep   ! depth                  [m]
+      REAL(wp), DIMENSION(jpi,jpj,jpts)    , INTENT(  out) ::   pab    ! thermal/haline expansion ratio
+      !
+      INTEGER  ::   ji, jj, jk                ! dummy loop indices
+      REAL(wp) ::   zt , zh , zs              ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3   !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 ) CALL timing_start('rab_2d')
+      !
+      pab(:,:,:) = 0._wp
+      !
+      SELECT CASE ( nn_eos )
+      !
+      CASE( -1, 0 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               !
+               zh  = pdep(ji,jj) * r1_Z0                                  ! depth
+               zt  = pts (ji,jj,jp_tem) * r1_T0                           ! temperature
+               zs  = SQRT( ABS( pts(ji,jj,jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+               !
+               ! alpha
+               zn3 = ALP003
+               !
+               zn2 = ALP012*zt + ALP102*zs+ALP002
+               !
+               zn1 = ((ALP031*zt   &
+                  &   + ALP121*zs+ALP021)*zt   &
+                  &   + (ALP211*zs+ALP111)*zs+ALP011)*zt   &
+                  &   + ((ALP301*zs+ALP201)*zs+ALP101)*zs+ALP001
+                  !
+               zn0 = ((((ALP050*zt   &
+                  &   + ALP140*zs+ALP040)*zt   &
+                  &   + (ALP230*zs+ALP130)*zs+ALP030)*zt   &
+                  &   + ((ALP320*zs+ALP220)*zs+ALP120)*zs+ALP020)*zt   &
+                  &   + (((ALP410*zs+ALP310)*zs+ALP210)*zs+ALP110)*zs+ALP010)*zt   &
+                  &   + ((((ALP500*zs+ALP400)*zs+ALP300)*zs+ALP200)*zs+ALP100)*zs+ALP000
+                  !
+               zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+               !
+               pab(ji,jj,jp_tem) = zn * r1_rau0
+               !
+               ! beta
+               zn3 = BET003
+               !
+               zn2 = BET012*zt + BET102*zs+BET002
+               !
+               zn1 = ((BET031*zt   &
+                  &   + BET121*zs+BET021)*zt   &
+                  &   + (BET211*zs+BET111)*zs+BET011)*zt   &
+                  &   + ((BET301*zs+BET201)*zs+BET101)*zs+BET001
+                  !
+               zn0 = ((((BET050*zt   &
+                  &   + BET140*zs+BET040)*zt   &
+                  &   + (BET230*zs+BET130)*zs+BET030)*zt   &
+                  &   + ((BET320*zs+BET220)*zs+BET120)*zs+BET020)*zt   &
+                  &   + (((BET410*zs+BET310)*zs+BET210)*zs+BET110)*zs+BET010)*zt   &
+                  &   + ((((BET500*zs+BET400)*zs+BET300)*zs+BET200)*zs+BET100)*zs+BET000
+                  !
+               zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+               !
+               pab(ji,jj,jp_sal) = zn / zs * r1_rau0
+               !
+               !
+            END DO
+         END DO
+         !
+         CALL lbc_lnk( pab(:,:,jp_tem), 'T', 1. )                    ! Lateral boundary conditions
+         CALL lbc_lnk( pab(:,:,jp_sal), 'T', 1. )                    
+         !
+      CASE( 1 )                  !==  simplified EOS  ==!
+         !
+         DO jj = 1, jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               !
+               zt    = pts  (ji,jj,jp_tem) - 10._wp   ! pot. temperature anomaly (t-T0)
+               zs    = pts  (ji,jj,jp_sal) - 35._wp   ! abs. salinity anomaly (s-S0)
+               zh    = pdep (ji,jj)                   ! depth at the partial step level
+               !
+               zn  = rn_a0 * ( 1._wp + rn_lambda1*zt + rn_mu1*zh ) + rn_nu*zs
+               pab(ji,jj,jp_tem) = zn * r1_rau0   ! alpha
+               !
+               zn  = rn_b0 * ( 1._wp - rn_lambda2*zs - rn_mu2*zh ) - rn_nu*zt
+               pab(ji,jj,jp_sal) = zn * r1_rau0   ! beta
+               !
+            END DO
+         END DO
+         !
+         CALL lbc_lnk( pab(:,:,jp_tem), 'T', 1. )                    ! Lateral boundary conditions
+         CALL lbc_lnk( pab(:,:,jp_sal), 'T', 1. )                    
+         !
+      CASE DEFAULT
+         IF(lwp) WRITE(numout,cform_err)
+         IF(lwp) WRITE(numout,*) '          bad flag value for nn_eos = ', nn_eos
+         nstop = nstop + 1
+         !
+      END SELECT
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab2d_1=pab(:,:,jp_tem), clinfo1=' rab_2d_t: ', &
+         &                       tab2d_2=pab(:,:,jp_sal), clinfo2=' rab_2d_s : ' )
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('rab_2d')
+      !
+   END SUBROUTINE rab_2d
+
+
+   SUBROUTINE rab_0d( pts, pdep, pab )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE rab_0d  ***
+      !!
+      !! ** Purpose :   Calculates thermal/haline expansion ratio for a 2d field (unmasked)
+      !!
+      !! ** Action  : - pab     : thermal/haline expansion ratio at T-points
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpts)    , INTENT(in   ) ::   pts    ! pot. temperature & salinity
+      REAL(wp),                      INTENT(in   ) ::   pdep   ! depth                  [m]
+      REAL(wp), DIMENSION(jpts)    , INTENT(  out) ::   pab    ! thermal/haline expansion ratio
+      !
+      REAL(wp) ::   zt , zh , zs              ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2, zn3   !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 ) CALL timing_start('rab_2d')
+      !
+      pab(:) = 0._wp
+      !
+      SELECT CASE ( nn_eos )
+      !
+      CASE( -1, 0 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+         !
+         zh  = pdep * r1_Z0                                  ! depth
+         zt  = pts (jp_tem) * r1_T0                           ! temperature
+         zs  = SQRT( ABS( pts(jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+         !
+         ! alpha
+         zn3 = ALP003
+         !
+         zn2 = ALP012*zt + ALP102*zs+ALP002
+         !
+         zn1 = ((ALP031*zt   &
+            &   + ALP121*zs+ALP021)*zt   &
+            &   + (ALP211*zs+ALP111)*zs+ALP011)*zt   &
+            &   + ((ALP301*zs+ALP201)*zs+ALP101)*zs+ALP001
+            !
+         zn0 = ((((ALP050*zt   &
+            &   + ALP140*zs+ALP040)*zt   &
+            &   + (ALP230*zs+ALP130)*zs+ALP030)*zt   &
+            &   + ((ALP320*zs+ALP220)*zs+ALP120)*zs+ALP020)*zt   &
+            &   + (((ALP410*zs+ALP310)*zs+ALP210)*zs+ALP110)*zs+ALP010)*zt   &
+            &   + ((((ALP500*zs+ALP400)*zs+ALP300)*zs+ALP200)*zs+ALP100)*zs+ALP000
+            !
+         zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+         !
+         pab(jp_tem) = zn * r1_rau0
+         !
+         ! beta
+         zn3 = BET003
+         !
+         zn2 = BET012*zt + BET102*zs+BET002
+         !
+         zn1 = ((BET031*zt   &
+            &   + BET121*zs+BET021)*zt   &
+            &   + (BET211*zs+BET111)*zs+BET011)*zt   &
+            &   + ((BET301*zs+BET201)*zs+BET101)*zs+BET001
+            !
+         zn0 = ((((BET050*zt   &
+            &   + BET140*zs+BET040)*zt   &
+            &   + (BET230*zs+BET130)*zs+BET030)*zt   &
+            &   + ((BET320*zs+BET220)*zs+BET120)*zs+BET020)*zt   &
+            &   + (((BET410*zs+BET310)*zs+BET210)*zs+BET110)*zs+BET010)*zt   &
+            &   + ((((BET500*zs+BET400)*zs+BET300)*zs+BET200)*zs+BET100)*zs+BET000
+            !
+         zn  = ( ( zn3 * zh + zn2 ) * zh + zn1 ) * zh + zn0
+         !
+         pab(jp_sal) = zn / zs * r1_rau0
+         !
+         !
+         !
+      CASE( 1 )                  !==  simplified EOS  ==!
+         !
+         zt    = pts(jp_tem) - 10._wp   ! pot. temperature anomaly (t-T0)
+         zs    = pts(jp_sal) - 35._wp   ! abs. salinity anomaly (s-S0)
+         zh    = pdep                    ! depth at the partial step level
+         !
+         zn  = rn_a0 * ( 1._wp + rn_lambda1*zt + rn_mu1*zh ) + rn_nu*zs
+         pab(jp_tem) = zn * r1_rau0   ! alpha
+         !
+         zn  = rn_b0 * ( 1._wp - rn_lambda2*zs - rn_mu2*zh ) - rn_nu*zt
+         pab(jp_sal) = zn * r1_rau0   ! beta
+         !
+      CASE DEFAULT
+         IF(lwp) WRITE(numout,cform_err)
+         IF(lwp) WRITE(numout,*) '          bad flag value for nn_eos = ', nn_eos
+         nstop = nstop + 1
+         !
+      END SELECT
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('rab_2d')
+      !
+   END SUBROUTINE rab_0d
+
+
+   SUBROUTINE bn2( pts, pab, pn2 )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE bn2  ***
+      !!
+      !! ** Purpose :   Compute the local Brunt-Vaisala frequency at the 
+      !!                time-step of the input arguments
+      !!
+      !! ** Method  :   pn2 = grav * (alpha dk[T] + beta dk[S] ) / e3w
+      !!      where alpha and beta are given in pab, and computed on T-points.
+      !!      N.B. N^2 is set one for all to zero at jk=1 in istate module.
+      !!
+      !! ** Action  :   pn2 : square of the brunt-vaisala frequency at w-point 
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pts   ! pot. temperature and salinity   [Celcius,psu]
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::  pab   ! thermal/haline expansion coef.  [Celcius-1,psu-1]
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::  pn2   ! Brunt-Vaisala frequency squared [1/s^2]
+      !
+      INTEGER  ::   ji, jj, jk      ! dummy loop indices
+      REAL(wp) ::   zaw, zbw, zrw   ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 ) CALL timing_start('bn2')
+      !
+      DO jk = 2, jpkm1           ! interior points only (2=< jk =< jpkm1 )
+         DO jj = 1, jpj          ! surface and bottom value set to zero one for all in istate.F90
+            DO ji = 1, jpi
+               zrw =   ( fsdepw(ji,jj,jk  ) - fsdept(ji,jj,jk) )   &
+                  &  / ( fsdept(ji,jj,jk-1) - fsdept(ji,jj,jk) ) 
+                  !
+               zaw = pab(ji,jj,jk,jp_tem) * (1. - zrw) + pab(ji,jj,jk-1,jp_tem) * zrw 
+               zbw = pab(ji,jj,jk,jp_sal) * (1. - zrw) + pab(ji,jj,jk-1,jp_sal) * zrw
+               !
+               pn2(ji,jj,jk) = grav * (  zaw * ( pts(ji,jj,jk-1,jp_tem) - pts(ji,jj,jk,jp_tem) )     &
+                  &                    - zbw * ( pts(ji,jj,jk-1,jp_sal) - pts(ji,jj,jk,jp_sal) )  )  &
+                  &            / fse3w(ji,jj,jk) * tmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      IF(ln_ctl)   CALL prt_ctl( tab3d_1=pn2, clinfo1=' bn2  : ', ovlap=1, kdim=jpk )
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('bn2')
+      !
+   END SUBROUTINE bn2
+
+
+   FUNCTION eos_pt_from_ct( ctmp, psal ) RESULT( ptmp )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE eos_pt_from_ct  ***
+      !!
+      !! ** Purpose :   Compute pot.temp. from cons. temp. [Celcius]
+      !!
+      !! ** Method  :   rational approximation (5/3th order) of TEOS-10 algorithm
+      !!       checkvalue: pt=20.02391895 Celsius for sa=35.7g/kg, ct=20degC
+      !!
+      !! Reference  :   TEOS-10, UNESCO
+      !!                Rational approximation to TEOS10 algorithm (rms error on WOA13 values: 4.0e-5 degC)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   ctmp   ! Cons. Temp [Celcius]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   psal   ! salinity   [psu]
+      ! Leave result array automatic rather than making explicitly allocated
+      REAL(wp), DIMENSION(jpi,jpj) ::   ptmp   ! potential temperature [Celcius]
+      !
+      INTEGER  ::   ji, jj               ! dummy loop indices
+      REAL(wp) ::   zt , zs , ztm        ! local scalars
+      REAL(wp) ::   zn , zd              ! local scalars
+      REAL(wp) ::   zdeltaS , z1_S0 , z1_T0
+      !!----------------------------------------------------------------------
+      !
+      IF ( nn_timing == 1 )   CALL timing_start('eos_pt_from_ct')
+      !
+      zdeltaS = 5._wp
+      z1_S0   = 0.875_wp/35.16504_wp
+      z1_T0   = 1._wp/40._wp
+      !
+      DO jj = 1, jpj
+         DO ji = 1, jpi
+            !
+            zt  = ctmp   (ji,jj) * z1_T0
+            zs  = SQRT( ABS( psal(ji,jj) + zdeltaS ) * r1_S0 )
+            ztm = tmask(ji,jj,1)
+            !
+            zn = ((((-2.1385727895e-01_wp*zt   &
+               &   - 2.7674419971e-01_wp*zs+1.0728094330_wp)*zt   &
+               &   + (2.6366564313_wp*zs+3.3546960647_wp)*zs-7.8012209473_wp)*zt   &
+               &   + ((1.8835586562_wp*zs+7.3949191679_wp)*zs-3.3937395875_wp)*zs-5.6414948432_wp)*zt   &
+               &   + (((3.5737370589_wp*zs-1.5512427389e+01_wp)*zs+2.4625741105e+01_wp)*zs   &
+               &      +1.9912291000e+01_wp)*zs-3.2191146312e+01_wp)*zt   &
+               &   + ((((5.7153204649e-01_wp*zs-3.0943149543_wp)*zs+9.3052495181_wp)*zs   &
+               &      -9.4528934807_wp)*zs+3.1066408996_wp)*zs-4.3504021262e-01_wp
+               !
+            zd = (2.0035003456_wp*zt   &
+               &   -3.4570358592e-01_wp*zs+5.6471810638_wp)*zt   &
+               &   + (1.5393993508_wp*zs-6.9394762624_wp)*zs+1.2750522650e+01_wp
+               !
+            ptmp(ji,jj) = ( zt / z1_T0 + zn / zd ) * ztm
+               !
+         END DO
+      END DO
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('eos_pt_from_ct')
+      !
+   END FUNCTION eos_pt_from_ct
+
+
+   FUNCTION eos_fzp_2d( psal, pdep ) RESULT( ptf )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE eos_fzp  ***
+      !!
+      !! ** Purpose :   Compute the freezing point temperature [Celcius]
+      !!
+      !! ** Method  :   UNESCO freezing point (ptf) in Celcius is given by
+      !!       ptf(t,z) = (-.0575+1.710523e-3*sqrt(abs(s))-2.154996e-4*s)*s - 7.53e-4*z
+      !!       checkvalue: tf=-2.588567 Celsius for s=40psu, z=500m
+      !!
+      !! Reference  :   UNESCO tech. papers in the marine science no. 28. 1978
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   )           ::   psal   ! salinity   [psu]
+      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ), OPTIONAL ::   pdep   ! depth      [m]
+      REAL(wp), DIMENSION(jpi,jpj)                          ::   ptf   ! freezing temperature [Celcius]
+      !
+      INTEGER  ::   ji, jj   ! dummy loop indices
+      REAL(wp) ::   zt, zs   ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE ( nn_eos )
+      !
+      CASE ( -1, 1 )                !==  CT,SA (TEOS-10 formulation) ==!
+         !
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zs= SQRT( ABS( psal(ji,jj) ) * r1_S0 )           ! square root salinity
+               ptf(ji,jj) = ((((1.46873e-03_wp*zs-9.64972e-03_wp)*zs+2.28348e-02_wp)*zs &
+                  &          - 3.12775e-02_wp)*zs+2.07679e-02_wp)*zs-5.87701e-02_wp
+            END DO
+         END DO
+         ptf(:,:) = ptf(:,:) * psal(:,:)
+         !
+         IF( PRESENT( pdep ) )   ptf(:,:) = ptf(:,:) - 7.53e-4 * pdep(:,:)
+         !
+      CASE ( 0 )                     !==  PT,SP (UNESCO formulation)  ==!
+         !
+         ptf(:,:) = ( - 0.0575_wp + 1.710523e-3_wp * SQRT( psal(:,:) )   &
+            &                     - 2.154996e-4_wp *       psal(:,:)   ) * psal(:,:)
+            !
+         IF( PRESENT( pdep ) )   ptf(:,:) = ptf(:,:) - 7.53e-4 * pdep(:,:)
+         !
+      CASE DEFAULT
+         IF(lwp) WRITE(numout,cform_err)
+         IF(lwp) WRITE(numout,*) '          bad flag value for nn_eos = ', nn_eos
+         nstop = nstop + 1
+         !
+      END SELECT
+      !
+   END FUNCTION eos_fzp_2d
+
+  FUNCTION eos_fzp_0d( psal, pdep ) RESULT( ptf )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE eos_fzp  ***
+      !!
+      !! ** Purpose :   Compute the freezing point temperature [Celcius]
+      !!
+      !! ** Method  :   UNESCO freezing point (ptf) in Celcius is given by
+      !!       ptf(t,z) = (-.0575+1.710523e-3*sqrt(abs(s))-2.154996e-4*s)*s - 7.53e-4*z
+      !!       checkvalue: tf=-2.588567 Celsius for s=40psu, z=500m
+      !!
+      !! Reference  :   UNESCO tech. papers in the marine science no. 28. 1978
+      !!----------------------------------------------------------------------
+      REAL(wp), INTENT(in)           ::   psal   ! salinity   [psu]
+      REAL(wp), INTENT(in), OPTIONAL ::   pdep   ! depth      [m]
+      REAL(wp)                       ::   ptf   ! freezing temperature [Celcius]
+      !
+      REAL(wp) :: zs   ! local scalars
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE ( nn_eos )
+      !
+      CASE ( -1, 1 )                !==  CT,SA (TEOS-10 formulation) ==!
+         !
+         zs  = SQRT( ABS( psal ) * r1_S0 )           ! square root salinity
+         ptf = ((((1.46873e-03_wp*zs-9.64972e-03_wp)*zs+2.28348e-02_wp)*zs &
+                  &          - 3.12775e-02_wp)*zs+2.07679e-02_wp)*zs-5.87701e-02_wp
+         ptf = ptf * psal
+         !
+         IF( PRESENT( pdep ) )   ptf = ptf - 7.53e-4 * pdep
+         !
+      CASE ( 0 )                     !==  PT,SP (UNESCO formulation)  ==!
+         !
+         ptf = ( - 0.0575_wp + 1.710523e-3_wp * SQRT( psal )   &
+            &                - 2.154996e-4_wp *       psal   ) * psal
+            !
+         IF( PRESENT( pdep ) )   ptf = ptf - 7.53e-4 * pdep
+         !
+      CASE DEFAULT
+         IF(lwp) WRITE(numout,cform_err)
+         IF(lwp) WRITE(numout,*) '          bad flag value for nn_eos = ', nn_eos
+         nstop = nstop + 1
+         !
+      END SELECT
+      !
+   END FUNCTION eos_fzp_0d
+
+
+   SUBROUTINE eos_pen( pts, pab_pe, ppen )
+      !!----------------------------------------------------------------------
+      !!                 ***  ROUTINE eos_pen  ***
+      !!
+      !! ** Purpose :   Calculates nonlinear anomalies of alpha_PE, beta_PE and PE at T-points
+      !!
+      !! ** Method  :   PE is defined analytically as the vertical 
+      !!                   primitive of EOS times -g integrated between 0 and z>0.
+      !!                pen is the nonlinear bsq-PE anomaly: pen = ( PE - rau0 gz ) / rau0 gz - rd
+      !!                                                      = 1/z * /int_0^z rd dz - rd 
+      !!                                where rd is the density anomaly (see eos_rhd function)
+      !!                ab_pe are partial derivatives of PE anomaly with respect to T and S:
+      !!                    ab_pe(1) = - 1/(rau0 gz) * dPE/dT + drd/dT = - d(pen)/dT
+      !!                    ab_pe(2) =   1/(rau0 gz) * dPE/dS + drd/dS =   d(pen)/dS
+      !!
+      !! ** Action  : - pen         : PE anomaly given at T-points
+      !!            : - pab_pe  : given at T-points
+      !!                    pab_pe(:,:,:,jp_tem) is alpha_pe
+      !!                    pab_pe(:,:,:,jp_sal) is beta_pe
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(in   ) ::   pts     ! pot. temperature & salinity
+      REAL(wp), DIMENSION(jpi,jpj,jpk,jpts), INTENT(  out) ::   pab_pe  ! alpha_pe and beta_pe
+      REAL(wp), DIMENSION(jpi,jpj,jpk)     , INTENT(  out) ::   ppen     ! potential energy anomaly
+      !
+      INTEGER  ::   ji, jj, jk                ! dummy loop indices
+      REAL(wp) ::   zt , zh , zs , ztm        ! local scalars
+      REAL(wp) ::   zn , zn0, zn1, zn2        !   -      -
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )   CALL timing_start('eos_pen')
+      !
+      SELECT CASE ( nn_eos )
+      !
+      CASE( -1, 0 )                !==  polynomial TEOS-10 / EOS-80 ==!
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  !
+                  zh  = fsdept(ji,jj,jk) * r1_Z0                                ! depth
+                  zt  = pts (ji,jj,jk,jp_tem) * r1_T0                           ! temperature
+                  zs  = SQRT( ABS( pts(ji,jj,jk,jp_sal) + rdeltaS ) * r1_S0 )   ! square root salinity
+                  ztm = tmask(ji,jj,jk)                                         ! tmask
+                  !
+                  ! potential energy non-linear anomaly
+                  zn2 = (PEN012)*zt   &
+                     &   + PEN102*zs+PEN002
+                     !
+                  zn1 = ((PEN021)*zt   &
+                     &   + PEN111*zs+PEN011)*zt   &
+                     &   + (PEN201*zs+PEN101)*zs+PEN001
+                     !
+                  zn0 = ((((PEN040)*zt   &
+                     &   + PEN130*zs+PEN030)*zt   &
+                     &   + (PEN220*zs+PEN120)*zs+PEN020)*zt   &
+                     &   + ((PEN310*zs+PEN210)*zs+PEN110)*zs+PEN010)*zt   &
+                     &   + (((PEN400*zs+PEN300)*zs+PEN200)*zs+PEN100)*zs+PEN000
+                     !
+                  zn  = ( zn2 * zh + zn1 ) * zh + zn0
+                  !
+                  ppen(ji,jj,jk)  = zn * zh * r1_rau0 * ztm
+                  !
+                  ! alphaPE non-linear anomaly
+                  zn2 = APE002
+                  !
+                  zn1 = (APE011)*zt   &
+                     &   + APE101*zs+APE001
+                     !
+                  zn0 = (((APE030)*zt   &
+                     &   + APE120*zs+APE020)*zt   &
+                     &   + (APE210*zs+APE110)*zs+APE010)*zt   &
+                     &   + ((APE300*zs+APE200)*zs+APE100)*zs+APE000
+                     !
+                  zn  = ( zn2 * zh + zn1 ) * zh + zn0
+                  !                              
+                  pab_pe(ji,jj,jk,jp_tem) = zn * zh * r1_rau0 * ztm
+                  !
+                  ! betaPE non-linear anomaly
+                  zn2 = BPE002
+                  !
+                  zn1 = (BPE011)*zt   &
+                     &   + BPE101*zs+BPE001
+                     !
+                  zn0 = (((BPE030)*zt   &
+                     &   + BPE120*zs+BPE020)*zt   &
+                     &   + (BPE210*zs+BPE110)*zs+BPE010)*zt   &
+                     &   + ((BPE300*zs+BPE200)*zs+BPE100)*zs+BPE000
+                     !
+                  zn  = ( zn2 * zh + zn1 ) * zh + zn0
+                  !                              
+                  pab_pe(ji,jj,jk,jp_sal) = zn / zs * zh * r1_rau0 * ztm
+                  !
+               END DO
+            END DO
+         END DO
+         !
+      CASE( 1 )                !==  Vallis (2006) simplified EOS  ==!
+         !
+         DO jk = 1, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zt  = pts(ji,jj,jk,jp_tem) - 10._wp  ! temperature anomaly (t-T0)
+                  zs = pts (ji,jj,jk,jp_sal) - 35._wp  ! abs. salinity anomaly (s-S0)
+                  zh  = fsdept(ji,jj,jk)               ! depth in meters  at t-point
+                  ztm = tmask(ji,jj,jk)                ! tmask
+                  zn  = 0.5_wp * zh * r1_rau0 * ztm
+                  !                                    ! Potential Energy
+                  ppen(ji,jj,jk) = ( rn_a0 * rn_mu1 * zt + rn_b0 * rn_mu2 * zs ) * zn
+                  !                                    ! alphaPE
+                  pab_pe(ji,jj,jk,jp_tem) = - rn_a0 * rn_mu1 * zn
+                  pab_pe(ji,jj,jk,jp_sal) =   rn_b0 * rn_mu2 * zn
+                  !
+               END DO
+            END DO
+         END DO
+         !
+      CASE DEFAULT
+         IF(lwp) WRITE(numout,cform_err)
+         IF(lwp) WRITE(numout,*) '          bad flag value for nn_eos = ', nn_eos
+         nstop = nstop + 1
+         !
+      END SELECT
+      !
+      IF( nn_timing == 1 )   CALL timing_stop('eos_pen')
+      !
+   END SUBROUTINE eos_pen
+
+
+   SUBROUTINE eos_init
       !!----------------------------------------------------------------------
       !!                 ***  ROUTINE eos_init  ***
       !!
-      !! ** Purpose :   Compute the sea surface freezing temperature [Celcius]
-      !!
-      !! ** Method  :   UNESCO freezing point at the surface (pressure = 0???)
-      !!       freezing point [Celcius]=(-.0575+1.710523e-3*sqrt(abs(s))-2.154996e-4*s)*s-7.53e-4*p
-      !!       checkvalue: tf= -2.588567 Celsius for s=40.0psu, p=500. decibars
-      !!
-      !! Reference  :   UNESCO tech. papers in the marine science no. 28. 1978
-      !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ) ::   psal   ! salinity             [psu]
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(in   ), OPTIONAL ::   pdep   ! depth      [decibars]
-      ! Leave result array automatic rather than making explicitly allocated
-      REAL(wp), DIMENSION(jpi,jpj)                ::   ptf    ! freezing temperature [Celcius]
-      !!----------------------------------------------------------------------
-      !
-      ptf(:,:) = ( - 0.0575_wp + 1.710523e-3_wp * SQRT( psal(:,:) )   &
-         &                     - 2.154996e-4_wp *       psal(:,:)   ) * psal(:,:)
-      IF ( PRESENT( pdep ) ) THEN   
-         ptf(:,:) = ptf(:,:) - 7.53e-4_wp * pdep(:,:)
-      ENDIF
-      !
-   END FUNCTION tfreez
-
-
-   SUBROUTINE eos_init
-      !!----------------------------------------------------------------------
-      !!                 ***  ROUTINE eos_init  ***
-      !!
       !! ** Purpose :   initializations for the equation of state
       !!
       !! ** Method  :   Read the namelist nameos and control the parameters
       !!----------------------------------------------------------------------
-      NAMELIST/nameos/ nn_eos, rn_alpha, rn_beta
-      !!----------------------------------------------------------------------
-      INTEGER  ::   ios
+      INTEGER  ::   ios   ! local integer
+      !!
+      NAMELIST/nameos/ nn_eos, ln_useCT, rn_a0, rn_b0, rn_lambda1, rn_mu1,   &
+         &                                             rn_lambda2, rn_mu2, rn_nu
+      !!----------------------------------------------------------------------
       !
       REWIND( numnam_ref )              ! Namelist nameos in reference namelist : equation of state
       READ  ( numnam_ref, nameos, IOSTAT = ios, ERR = 901 )
 901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nameos in reference namelist', lwp )
-
+      !
       REWIND( numnam_cfg )              ! Namelist nameos in configuration namelist : equation of state
       READ  ( numnam_cfg, nameos, IOSTAT = ios, ERR = 902 )
 902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'nameos in configuration namelist', lwp )
       IF(lwm) WRITE( numond, nameos )
+      !
+      rau0        = 1026._wp                 !: volumic mass of reference     [kg/m3]
+      rcp         = 3991.86795711963_wp      !: heat capacity     [J/K]
       !
       IF(lwp) THEN                ! Control print
@@ -731,25 +1180,406 @@
          WRITE(numout,*) '          Namelist nameos : set eos parameters'
          WRITE(numout,*) '             flag for eq. of state and N^2  nn_eos   = ', nn_eos
-         WRITE(numout,*) '             thermal exp. coef. (linear)    rn_alpha = ', rn_alpha
-         WRITE(numout,*) '             saline  exp. coef. (linear)    rn_beta  = ', rn_beta
+         IF( ln_useCT )   THEN
+            WRITE(numout,*) '             model uses Conservative Temperature'
+            WRITE(numout,*) '             Important: model must be initialized with CT and SA fields'
+         ENDIF
       ENDIF
       !
       SELECT CASE( nn_eos )         ! check option
       !
-      CASE( 0 )                        !==  Jackett and McDougall (1994) formulation  ==!
+      CASE( -1 )                       !==  polynomial TEOS-10  ==!
          IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) '          use of Jackett & McDougall (1994) equation of state and'
-         IF(lwp) WRITE(numout,*) '                 McDougall (1987) Brunt-Vaisala frequency'
-         !
-      CASE( 1 )                        !==  Linear formulation = F( temperature )  ==!
+         IF(lwp) WRITE(numout,*) '          use of TEOS-10 equation of state (cons. temp. and abs. salinity)'
+         !
+         rdeltaS = 32._wp
+         r1_S0  = 0.875_wp/35.16504_wp
+         r1_T0  = 1._wp/40._wp
+         r1_Z0  = 1.e-4_wp
+         !
+         EOS000 = 8.0189615746e+02_wp
+         EOS100 = 8.6672408165e+02_wp
+         EOS200 = -1.7864682637e+03_wp
+         EOS300 = 2.0375295546e+03_wp
+         EOS400 = -1.2849161071e+03_wp
+         EOS500 = 4.3227585684e+02_wp
+         EOS600 = -6.0579916612e+01_wp
+         EOS010 = 2.6010145068e+01_wp
+         EOS110 = -6.5281885265e+01_wp
+         EOS210 = 8.1770425108e+01_wp
+         EOS310 = -5.6888046321e+01_wp
+         EOS410 = 1.7681814114e+01_wp
+         EOS510 = -1.9193502195_wp
+         EOS020 = -3.7074170417e+01_wp
+         EOS120 = 6.1548258127e+01_wp
+         EOS220 = -6.0362551501e+01_wp
+         EOS320 = 2.9130021253e+01_wp
+         EOS420 = -5.4723692739_wp
+         EOS030 = 2.1661789529e+01_wp
+         EOS130 = -3.3449108469e+01_wp
+         EOS230 = 1.9717078466e+01_wp
+         EOS330 = -3.1742946532_wp
+         EOS040 = -8.3627885467_wp
+         EOS140 = 1.1311538584e+01_wp
+         EOS240 = -5.3563304045_wp
+         EOS050 = 5.4048723791e-01_wp
+         EOS150 = 4.8169980163e-01_wp
+         EOS060 = -1.9083568888e-01_wp
+         EOS001 = 1.9681925209e+01_wp
+         EOS101 = -4.2549998214e+01_wp
+         EOS201 = 5.0774768218e+01_wp
+         EOS301 = -3.0938076334e+01_wp
+         EOS401 = 6.6051753097_wp
+         EOS011 = -1.3336301113e+01_wp
+         EOS111 = -4.4870114575_wp
+         EOS211 = 5.0042598061_wp
+         EOS311 = -6.5399043664e-01_wp
+         EOS021 = 6.7080479603_wp
+         EOS121 = 3.5063081279_wp
+         EOS221 = -1.8795372996_wp
+         EOS031 = -2.4649669534_wp
+         EOS131 = -5.5077101279e-01_wp
+         EOS041 = 5.5927935970e-01_wp
+         EOS002 = 2.0660924175_wp
+         EOS102 = -4.9527603989_wp
+         EOS202 = 2.5019633244_wp
+         EOS012 = 2.0564311499_wp
+         EOS112 = -2.1311365518e-01_wp
+         EOS022 = -1.2419983026_wp
+         EOS003 = -2.3342758797e-02_wp
+         EOS103 = -1.8507636718e-02_wp
+         EOS013 = 3.7969820455e-01_wp
+         !
+         ALP000 = -6.5025362670e-01_wp
+         ALP100 = 1.6320471316_wp
+         ALP200 = -2.0442606277_wp
+         ALP300 = 1.4222011580_wp
+         ALP400 = -4.4204535284e-01_wp
+         ALP500 = 4.7983755487e-02_wp
+         ALP010 = 1.8537085209_wp
+         ALP110 = -3.0774129064_wp
+         ALP210 = 3.0181275751_wp
+         ALP310 = -1.4565010626_wp
+         ALP410 = 2.7361846370e-01_wp
+         ALP020 = -1.6246342147_wp
+         ALP120 = 2.5086831352_wp
+         ALP220 = -1.4787808849_wp
+         ALP320 = 2.3807209899e-01_wp
+         ALP030 = 8.3627885467e-01_wp
+         ALP130 = -1.1311538584_wp
+         ALP230 = 5.3563304045e-01_wp
+         ALP040 = -6.7560904739e-02_wp
+         ALP140 = -6.0212475204e-02_wp
+         ALP050 = 2.8625353333e-02_wp
+         ALP001 = 3.3340752782e-01_wp
+         ALP101 = 1.1217528644e-01_wp
+         ALP201 = -1.2510649515e-01_wp
+         ALP301 = 1.6349760916e-02_wp
+         ALP011 = -3.3540239802e-01_wp
+         ALP111 = -1.7531540640e-01_wp
+         ALP211 = 9.3976864981e-02_wp
+         ALP021 = 1.8487252150e-01_wp
+         ALP121 = 4.1307825959e-02_wp
+         ALP031 = -5.5927935970e-02_wp
+         ALP002 = -5.1410778748e-02_wp
+         ALP102 = 5.3278413794e-03_wp
+         ALP012 = 6.2099915132e-02_wp
+         ALP003 = -9.4924551138e-03_wp
+         !
+         BET000 = 1.0783203594e+01_wp
+         BET100 = -4.4452095908e+01_wp
+         BET200 = 7.6048755820e+01_wp
+         BET300 = -6.3944280668e+01_wp
+         BET400 = 2.6890441098e+01_wp
+         BET500 = -4.5221697773_wp
+         BET010 = -8.1219372432e-01_wp
+         BET110 = 2.0346663041_wp
+         BET210 = -2.1232895170_wp
+         BET310 = 8.7994140485e-01_wp
+         BET410 = -1.1939638360e-01_wp
+         BET020 = 7.6574242289e-01_wp
+         BET120 = -1.5019813020_wp
+         BET220 = 1.0872489522_wp
+         BET320 = -2.7233429080e-01_wp
+         BET030 = -4.1615152308e-01_wp
+         BET130 = 4.9061350869e-01_wp
+         BET230 = -1.1847737788e-01_wp
+         BET040 = 1.4073062708e-01_wp
+         BET140 = -1.3327978879e-01_wp
+         BET050 = 5.9929880134e-03_wp
+         BET001 = -5.2937873009e-01_wp
+         BET101 = 1.2634116779_wp
+         BET201 = -1.1547328025_wp
+         BET301 = 3.2870876279e-01_wp
+         BET011 = -5.5824407214e-02_wp
+         BET111 = 1.2451933313e-01_wp
+         BET211 = -2.4409539932e-02_wp
+         BET021 = 4.3623149752e-02_wp
+         BET121 = -4.6767901790e-02_wp
+         BET031 = -6.8523260060e-03_wp
+         BET002 = -6.1618945251e-02_wp
+         BET102 = 6.2255521644e-02_wp
+         BET012 = -2.6514181169e-03_wp
+         BET003 = -2.3025968587e-04_wp
+         !
+         PEN000 = -9.8409626043_wp
+         PEN100 = 2.1274999107e+01_wp
+         PEN200 = -2.5387384109e+01_wp
+         PEN300 = 1.5469038167e+01_wp
+         PEN400 = -3.3025876549_wp
+         PEN010 = 6.6681505563_wp
+         PEN110 = 2.2435057288_wp
+         PEN210 = -2.5021299030_wp
+         PEN310 = 3.2699521832e-01_wp
+         PEN020 = -3.3540239802_wp
+         PEN120 = -1.7531540640_wp
+         PEN220 = 9.3976864981e-01_wp
+         PEN030 = 1.2324834767_wp
+         PEN130 = 2.7538550639e-01_wp
+         PEN040 = -2.7963967985e-01_wp
+         PEN001 = -1.3773949450_wp
+         PEN101 = 3.3018402659_wp
+         PEN201 = -1.6679755496_wp
+         PEN011 = -1.3709540999_wp
+         PEN111 = 1.4207577012e-01_wp
+         PEN021 = 8.2799886843e-01_wp
+         PEN002 = 1.7507069098e-02_wp
+         PEN102 = 1.3880727538e-02_wp
+         PEN012 = -2.8477365341e-01_wp
+         !
+         APE000 = -1.6670376391e-01_wp
+         APE100 = -5.6087643219e-02_wp
+         APE200 = 6.2553247576e-02_wp
+         APE300 = -8.1748804580e-03_wp
+         APE010 = 1.6770119901e-01_wp
+         APE110 = 8.7657703198e-02_wp
+         APE210 = -4.6988432490e-02_wp
+         APE020 = -9.2436260751e-02_wp
+         APE120 = -2.0653912979e-02_wp
+         APE030 = 2.7963967985e-02_wp
+         APE001 = 3.4273852498e-02_wp
+         APE101 = -3.5518942529e-03_wp
+         APE011 = -4.1399943421e-02_wp
+         APE002 = 7.1193413354e-03_wp
+         !
+         BPE000 = 2.6468936504e-01_wp
+         BPE100 = -6.3170583896e-01_wp
+         BPE200 = 5.7736640125e-01_wp
+         BPE300 = -1.6435438140e-01_wp
+         BPE010 = 2.7912203607e-02_wp
+         BPE110 = -6.2259666565e-02_wp
+         BPE210 = 1.2204769966e-02_wp
+         BPE020 = -2.1811574876e-02_wp
+         BPE120 = 2.3383950895e-02_wp
+         BPE030 = 3.4261630030e-03_wp
+         BPE001 = 4.1079296834e-02_wp
+         BPE101 = -4.1503681096e-02_wp
+         BPE011 = 1.7676120780e-03_wp
+         BPE002 = 1.7269476440e-04_wp
+         !
+      CASE( 0 )                        !==  polynomial EOS-80 formulation  ==!
+         !
          IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) '          use of linear eos rho(T) = rau0 * ( 1.0285 - rn_alpha * T )'
-         IF( lk_zdfddm ) CALL ctl_stop( '          double diffusive mixing parameterization requires',   &
-              &                         ' that T and S are used as state variables' )
-         !
-      CASE( 2 )                        !==  Linear formulation = F( temperature , salinity )  ==!
-         ralpbet = rn_alpha / rn_beta
-         IF(lwp) WRITE(numout,*)
-         IF(lwp) WRITE(numout,*) '          use of linear eos rho(T,S) = rau0 * ( rn_beta * S - rn_alpha * T )'
+         IF(lwp) WRITE(numout,*) '          use of EOS-80 equation of state (pot. temp. and pract. salinity)'
+         !
+         rdeltaS = 20._wp
+         r1_S0  = 1._wp/40._wp
+         r1_T0  = 1._wp/40._wp
+         r1_Z0  = 1.e-4_wp
+         !
+         EOS000 = 9.5356891948e+02_wp
+         EOS100 = 1.7136499189e+02_wp
+         EOS200 = -3.7501039454e+02_wp
+         EOS300 = 5.1856810420e+02_wp
+         EOS400 = -3.7264470465e+02_wp
+         EOS500 = 1.4302533998e+02_wp
+         EOS600 = -2.2856621162e+01_wp
+         EOS010 = 1.0087518651e+01_wp
+         EOS110 = -1.3647741861e+01_wp
+         EOS210 = 8.8478359933_wp
+         EOS310 = -7.2329388377_wp
+         EOS410 = 1.4774410611_wp
+         EOS510 = 2.0036720553e-01_wp
+         EOS020 = -2.5579830599e+01_wp
+         EOS120 = 2.4043512327e+01_wp
+         EOS220 = -1.6807503990e+01_wp
+         EOS320 = 8.3811577084_wp
+         EOS420 = -1.9771060192_wp
+         EOS030 = 1.6846451198e+01_wp
+         EOS130 = -2.1482926901e+01_wp
+         EOS230 = 1.0108954054e+01_wp
+         EOS330 = -6.2675951440e-01_wp
+         EOS040 = -8.0812310102_wp
+         EOS140 = 1.0102374985e+01_wp
+         EOS240 = -4.8340368631_wp
+         EOS050 = 1.2079167803_wp
+         EOS150 = 1.1515380987e-01_wp
+         EOS060 = -2.4520288837e-01_wp
+         EOS001 = 1.0748601068e+01_wp
+         EOS101 = -1.7817043500e+01_wp
+         EOS201 = 2.2181366768e+01_wp
+         EOS301 = -1.6750916338e+01_wp
+         EOS401 = 4.1202230403_wp
+         EOS011 = -1.5852644587e+01_wp
+         EOS111 = -7.6639383522e-01_wp
+         EOS211 = 4.1144627302_wp
+         EOS311 = -6.6955877448e-01_wp
+         EOS021 = 9.9994861860_wp
+         EOS121 = -1.9467067787e-01_wp
+         EOS221 = -1.2177554330_wp
+         EOS031 = -3.4866102017_wp
+         EOS131 = 2.2229155620e-01_wp
+         EOS041 = 5.9503008642e-01_wp
+         EOS002 = 1.0375676547_wp
+         EOS102 = -3.4249470629_wp
+         EOS202 = 2.0542026429_wp
+         EOS012 = 2.1836324814_wp
+         EOS112 = -3.4453674320e-01_wp
+         EOS022 = -1.2548163097_wp
+         EOS003 = 1.8729078427e-02_wp
+         EOS103 = -5.7238495240e-02_wp
+         EOS013 = 3.8306136687e-01_wp
+         !
+         ALP000 = -2.5218796628e-01_wp
+         ALP100 = 3.4119354654e-01_wp
+         ALP200 = -2.2119589983e-01_wp
+         ALP300 = 1.8082347094e-01_wp
+         ALP400 = -3.6936026529e-02_wp
+         ALP500 = -5.0091801383e-03_wp
+         ALP010 = 1.2789915300_wp
+         ALP110 = -1.2021756164_wp
+         ALP210 = 8.4037519952e-01_wp
+         ALP310 = -4.1905788542e-01_wp
+         ALP410 = 9.8855300959e-02_wp
+         ALP020 = -1.2634838399_wp
+         ALP120 = 1.6112195176_wp
+         ALP220 = -7.5817155402e-01_wp
+         ALP320 = 4.7006963580e-02_wp
+         ALP030 = 8.0812310102e-01_wp
+         ALP130 = -1.0102374985_wp
+         ALP230 = 4.8340368631e-01_wp
+         ALP040 = -1.5098959754e-01_wp
+         ALP140 = -1.4394226233e-02_wp
+         ALP050 = 3.6780433255e-02_wp
+         ALP001 = 3.9631611467e-01_wp
+         ALP101 = 1.9159845880e-02_wp
+         ALP201 = -1.0286156825e-01_wp
+         ALP301 = 1.6738969362e-02_wp
+         ALP011 = -4.9997430930e-01_wp
+         ALP111 = 9.7335338937e-03_wp
+         ALP211 = 6.0887771651e-02_wp
+         ALP021 = 2.6149576513e-01_wp
+         ALP121 = -1.6671866715e-02_wp
+         ALP031 = -5.9503008642e-02_wp
+         ALP002 = -5.4590812035e-02_wp
+         ALP102 = 8.6134185799e-03_wp
+         ALP012 = 6.2740815484e-02_wp
+         ALP003 = -9.5765341718e-03_wp
+         !
+         BET000 = 2.1420623987_wp
+         BET100 = -9.3752598635_wp
+         BET200 = 1.9446303907e+01_wp
+         BET300 = -1.8632235232e+01_wp
+         BET400 = 8.9390837485_wp
+         BET500 = -1.7142465871_wp
+         BET010 = -1.7059677327e-01_wp
+         BET110 = 2.2119589983e-01_wp
+         BET210 = -2.7123520642e-01_wp
+         BET310 = 7.3872053057e-02_wp
+         BET410 = 1.2522950346e-02_wp
+         BET020 = 3.0054390409e-01_wp
+         BET120 = -4.2018759976e-01_wp
+         BET220 = 3.1429341406e-01_wp
+         BET320 = -9.8855300959e-02_wp
+         BET030 = -2.6853658626e-01_wp
+         BET130 = 2.5272385134e-01_wp
+         BET230 = -2.3503481790e-02_wp
+         BET040 = 1.2627968731e-01_wp
+         BET140 = -1.2085092158e-01_wp
+         BET050 = 1.4394226233e-03_wp
+         BET001 = -2.2271304375e-01_wp
+         BET101 = 5.5453416919e-01_wp
+         BET201 = -6.2815936268e-01_wp
+         BET301 = 2.0601115202e-01_wp
+         BET011 = -9.5799229402e-03_wp
+         BET111 = 1.0286156825e-01_wp
+         BET211 = -2.5108454043e-02_wp
+         BET021 = -2.4333834734e-03_wp
+         BET121 = -3.0443885826e-02_wp
+         BET031 = 2.7786444526e-03_wp
+         BET002 = -4.2811838287e-02_wp
+         BET102 = 5.1355066072e-02_wp
+         BET012 = -4.3067092900e-03_wp
+         BET003 = -7.1548119050e-04_wp
+         !
+         PEN000 = -5.3743005340_wp
+         PEN100 = 8.9085217499_wp
+         PEN200 = -1.1090683384e+01_wp
+         PEN300 = 8.3754581690_wp
+         PEN400 = -2.0601115202_wp
+         PEN010 = 7.9263222935_wp
+         PEN110 = 3.8319691761e-01_wp
+         PEN210 = -2.0572313651_wp
+         PEN310 = 3.3477938724e-01_wp
+         PEN020 = -4.9997430930_wp
+         PEN120 = 9.7335338937e-02_wp
+         PEN220 = 6.0887771651e-01_wp
+         PEN030 = 1.7433051009_wp
+         PEN130 = -1.1114577810e-01_wp
+         PEN040 = -2.9751504321e-01_wp
+         PEN001 = -6.9171176978e-01_wp
+         PEN101 = 2.2832980419_wp
+         PEN201 = -1.3694684286_wp
+         PEN011 = -1.4557549876_wp
+         PEN111 = 2.2969116213e-01_wp
+         PEN021 = 8.3654420645e-01_wp
+         PEN002 = -1.4046808820e-02_wp
+         PEN102 = 4.2928871430e-02_wp
+         PEN012 = -2.8729602515e-01_wp
+         !
+         APE000 = -1.9815805734e-01_wp
+         APE100 = -9.5799229402e-03_wp
+         APE200 = 5.1430784127e-02_wp
+         APE300 = -8.3694846809e-03_wp
+         APE010 = 2.4998715465e-01_wp
+         APE110 = -4.8667669469e-03_wp
+         APE210 = -3.0443885826e-02_wp
+         APE020 = -1.3074788257e-01_wp
+         APE120 = 8.3359333577e-03_wp
+         APE030 = 2.9751504321e-02_wp
+         APE001 = 3.6393874690e-02_wp
+         APE101 = -5.7422790533e-03_wp
+         APE011 = -4.1827210323e-02_wp
+         APE002 = 7.1824006288e-03_wp
+         !
+         BPE000 = 1.1135652187e-01_wp
+         BPE100 = -2.7726708459e-01_wp
+         BPE200 = 3.1407968134e-01_wp
+         BPE300 = -1.0300557601e-01_wp
+         BPE010 = 4.7899614701e-03_wp
+         BPE110 = -5.1430784127e-02_wp
+         BPE210 = 1.2554227021e-02_wp
+         BPE020 = 1.2166917367e-03_wp
+         BPE120 = 1.5221942913e-02_wp
+         BPE030 = -1.3893222263e-03_wp
+         BPE001 = 2.8541225524e-02_wp
+         BPE101 = -3.4236710714e-02_wp
+         BPE011 = 2.8711395266e-03_wp
+         BPE002 = 5.3661089288e-04_wp
+         !
+      CASE( 1 )                        !==  Simplified EOS     ==!
+         IF(lwp) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) '          use of simplified eos:    rhd(dT=T-10,dS=S-35,Z) = '
+            WRITE(numout,*) '             [-a0*(1+lambda1/2*dT+mu1*Z)*dT + b0*(1+lambda2/2*dT+mu2*Z)*dS - nu*dT*dS]/rau0'
+            WRITE(numout,*)
+            WRITE(numout,*) '             thermal exp. coef.    rn_a0      = ', rn_a0
+            WRITE(numout,*) '             saline  cont. coef.   rn_b0      = ', rn_b0
+            WRITE(numout,*) '             cabbeling coef.       rn_lambda1 = ', rn_lambda1
+            WRITE(numout,*) '             cabbeling coef.       rn_lambda2 = ', rn_lambda2
+            WRITE(numout,*) '             thermobar. coef.      rn_mu1     = ', rn_mu1
+            WRITE(numout,*) '             thermobar. coef.      rn_mu2     = ', rn_mu2
+            WRITE(numout,*) '             2nd cabbel. coef.     rn_nu      = ', rn_nu
+            WRITE(numout,*) '               Caution: rn_beta0=0 incompatible with ddm parameterization '
+         ENDIF
          !
       CASE DEFAULT                     !==  ERROR in nn_eos  ==!
@@ -759,4 +1589,14 @@
       END SELECT
       !
+      r1_rau0     = 1._wp / rau0
+      r1_rcp      = 1._wp / rcp
+      r1_rau0_rcp = 1._wp / ( rau0 * rcp )
+      !
+      IF(lwp) WRITE(numout,*)
+      IF(lwp) WRITE(numout,*) '          volumic mass of reference           rau0  = ', rau0   , ' kg/m^3'
+      IF(lwp) WRITE(numout,*) '          1. / rau0                        r1_rau0  = ', r1_rau0, ' m^3/kg'
+      IF(lwp) WRITE(numout,*) '          ocean specific heat                 rcp   = ', rcp    , ' J/Kelvin'
+      IF(lwp) WRITE(numout,*) '          1. / ( rau0 * rcp )           r1_rau0_rcp = ', r1_rau0_rcp
+      !
    END SUBROUTINE eos_init
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv.F90	(revision 5075)
@@ -32,4 +32,5 @@
    USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
+   USE sbc_oce
 
 
@@ -43,4 +44,5 @@
    LOGICAL ::   ln_traadv_cen2     ! 2nd order centered scheme flag
    LOGICAL ::   ln_traadv_tvd      ! TVD scheme flag
+   LOGICAL ::   ln_traadv_tvd_zts  ! TVD scheme flag with vertical sub time-stepping
    LOGICAL ::   ln_traadv_muscl    ! MUSCL scheme flag
    LOGICAL ::   ln_traadv_muscl2   ! MUSCL2 scheme flag
@@ -120,4 +122,5 @@
       CASE ( 5 )   ;    CALL tra_adv_ubs   ( kt, nit000, 'TRA', r2dtra, zun, zvn, zwn, tsb, tsn, tsa, jpts )   !  UBS 
       CASE ( 6 )   ;    CALL tra_adv_qck   ( kt, nit000, 'TRA', r2dtra, zun, zvn, zwn, tsb, tsn, tsa, jpts )   !  QUICKEST 
+      CASE ( 7 )   ;   CALL tra_adv_tvd_zts( kt, nit000, 'TRA', r2dtra, zun, zvn, zwn, tsb, tsn, tsa, jpts )   !  TVD ZTS
       !
       CASE (-1 )                                      !==  esopa: test all possibility with control print  ==!
@@ -166,5 +169,5 @@
          &                 ln_traadv_muscl, ln_traadv_muscl2,  &
          &                 ln_traadv_ubs  , ln_traadv_qck,     &
-         &                 ln_traadv_msc_ups
+         &                 ln_traadv_msc_ups, ln_traadv_tvd_zts
       !!----------------------------------------------------------------------
 
@@ -190,4 +193,5 @@
          WRITE(numout,*) '      QUICKEST advection scheme      ln_traadv_qck     = ', ln_traadv_qck
          WRITE(numout,*) '      upstream scheme within muscl   ln_traadv_msc_ups = ', ln_traadv_msc_ups
+         WRITE(numout,*) '      TVD advection scheme with zts  ln_traadv_tvd_zts = ', ln_traadv_tvd_zts
       ENDIF
 
@@ -199,5 +203,9 @@
       IF( ln_traadv_ubs    )   ioptio = ioptio + 1
       IF( ln_traadv_qck    )   ioptio = ioptio + 1
+      IF( ln_traadv_tvd_zts)   ioptio = ioptio + 1
       IF( lk_esopa         )   ioptio =          1
+
+      IF( ( ln_traadv_muscl .OR. ln_traadv_muscl2 .OR. ln_traadv_ubs .OR. ln_traadv_qck ) .AND. nn_isf .NE. 0 )  &
+      &   CALL ctl_stop( 'Only traadv_cen2 and traadv_tvd is compatible with ice shelf cavity')
 
       IF( ioptio /= 1 )   CALL ctl_stop( 'Choose ONE advection scheme in namelist namtra_adv' )
@@ -210,4 +218,5 @@
       IF( ln_traadv_ubs    )   nadv =  5
       IF( ln_traadv_qck    )   nadv =  6
+      IF( ln_traadv_tvd_zts)   nadv =  7
       IF( lk_esopa         )   nadv = -1
 
@@ -220,4 +229,5 @@
          IF( nadv ==  5 )   WRITE(numout,*) '         UBS       scheme is used'
          IF( nadv ==  6 )   WRITE(numout,*) '         QUICKEST  scheme is used'
+         IF( nadv ==  7 )   WRITE(numout,*) '         TVD ZTS   scheme is used'
          IF( nadv == -1 )   WRITE(numout,*) '         esopa test: use all advection scheme'
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_cen2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_cen2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_cen2.F90	(revision 5075)
@@ -4,7 +4,7 @@
    !! Ocean  tracers:  horizontal & vertical advective trend
    !!======================================================================
-   !! History :  8.2  ! 2001-08  (G. Madec, E. Durand)  trahad+trazad=traadv 
-   !!            1.0  ! 2002-06  (G. Madec)  F90: Free form and module
-   !!            9.0  ! 2004-08  (C. Talandier) New trends organization
+   !! History :  OPA  ! 2001-08  (G. Madec, E. Durand) v8.2 trahad+trazad=traadv 
+   !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module
+   !!             -   ! 2004-08  (C. Talandier) New trends organization
    !!             -   ! 2005-11  (V. Garnier) Surface pressure gradient organization
    !!            2.0  ! 2006-04  (R. Benshila, G. Madec) Step reorganization
@@ -21,6 +21,6 @@
    USE dom_oce         ! ocean space and time domain
    USE eosbn2          ! equation of state
-   USE trdmod_oce      ! tracers trends
-   USE trdtra          ! tracers trends
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
    USE closea          ! closed sea
    USE sbcrnf          ! river runoffs
@@ -33,12 +33,10 @@
    USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
+   USE phycst
 
    IMPLICIT NONE
    PRIVATE
 
-   PUBLIC   tra_adv_cen2       ! routine called by step.F90
-   PUBLIC   ups_orca_set       ! routine used by traadv_cen2_jki.F90
-
-   LOGICAL  :: l_trd       ! flag to compute trends
+   PUBLIC   tra_adv_cen2   ! routine called by traadv.F90
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) :: upsmsk !: mixed upstream/centered scheme near some straits 
@@ -55,5 +53,5 @@
 
    SUBROUTINE tra_adv_cen2( kt, kit000, cdtype, pun, pvn, pwn,     &
-      &                                 ptb, ptn, pta, kjpt   ) 
+      &                                         ptb, ptn, pta, kjpt   ) 
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE tra_adv_cen2  ***
@@ -85,8 +83,7 @@
       !!       * Add this trend now to the general trend of tracer (ta,sa):
       !!               pta = pta + ztra
-      !!       * trend diagnostic ('key_trdtra' defined): the trend is
+      !!       * trend diagnostic (l_trdtra=T or l_trctra=T): the trend is
       !!      saved for diagnostics. The trends saved is expressed as
-      !!      Uh.gradh(T), i.e.
-      !!                     save trend = ztra + ptn divn
+      !!      Uh.gradh(T), i.e.  save trend = ztra + ptn divn
       !!
       !!         Part II : vertical advection
@@ -104,5 +101,5 @@
       !!         Add this trend now to the general trend of tracer (ta,sa):
       !!             pta = pta + ztra
-      !!         Trend diagnostic ('key_trdtra' defined): the trend is
+      !!         Trend diagnostic (l_trdtra=T or l_trctra=T): the trend is
       !!      saved for diagnostics. The trends saved is expressed as :
       !!             save trend =  w.gradz(T) = ztra - ptn divn.
@@ -111,6 +108,4 @@
       !!              - save trends if needed
       !!----------------------------------------------------------------------
-      USE oce     , ONLY:   zwx => ua        , zwy  => va          ! (ua,va) used as 3D workspace
-      !
       INTEGER                              , INTENT(in   ) ::   kt              ! ocean time-step index
       INTEGER                              , INTENT(in   ) ::   kit000          ! first time step index
@@ -121,6 +116,6 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta             ! tracer trend 
       !
-      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
-      INTEGER  ::   ierr             ! local integer
+      INTEGER  ::   ji, jj, jk, jn, ikt   ! dummy loop indices
+      INTEGER  ::   ierr                 ! local integer
       REAL(wp) ::   zbtr, ztra                            ! local scalars
       REAL(wp) ::   zfp_ui, zfp_vj, zfp_w, zcofi          !   -      -
@@ -128,12 +123,13 @@
       REAL(wp) ::   zupsut, zcenut, zupst                 !   -      -
       REAL(wp) ::   zupsvt, zcenvt, zcent, zice           !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:  ) :: ztfreez 
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwz, zind
+      REAL(wp), POINTER, DIMENSION(:,:)   :: zfzp, zpres   ! 2D workspace
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwx, zwy     ! 3D     -
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwz, zind    !  -     -
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_adv_cen2')
       !
-      CALL wrk_alloc( jpi, jpj, ztfreez )
-      CALL wrk_alloc( jpi, jpj, jpk, zwz, zind )
+      CALL wrk_alloc( jpi, jpj, zpres, zfzp )
+      CALL wrk_alloc( jpi, jpj, jpk, zwx, zwy, zwz, zind )
       !
 
@@ -144,5 +140,5 @@
          IF(lwp) WRITE(numout,*)
          !
-         IF ( .NOT. ALLOCATED( upsmsk ) )  THEN
+         IF( .NOT. ALLOCATED( upsmsk ) )  THEN
              ALLOCATE( upsmsk(jpi,jpj), STAT=ierr )
              IF( ierr /= 0 )   CALL ctl_stop('STOP', 'tra_adv_cen2: unable to allocate array')
@@ -162,18 +158,26 @@
       ENDIF
       !
-      l_trd = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )   l_trd = .TRUE.
-      !
       ! Upstream / centered scheme indicator
       ! ------------------------------------
 !!gm  not strickly exact : the freezing point should be computed at each ocean levels...
 !!gm  not a big deal since cen2 is no more used in global ice-ocean simulations
-      ztfreez(:,:) = tfreez( tsn(:,:,1,jp_sal) )
+!!ch  changes for ice shelf to retain standard behaviour elsewhere, even if not optimal 
+      DO jj = 1, jpj 
+         DO ji = 1, jpi 
+            ikt = mikt(ji,jj) 
+            IF (ikt > 1 ) THEN 
+               zpres(ji,jj) = grav * rau0 * fsdept(ji,jj,ikt) * 1.e-04  
+            ELSE 
+               zpres(ji,jj) = 0.0 
+            ENDIF  
+         END DO 
+      END DO 
+      zfzp(:,:) = eos_fzp( tsn(:,:,1,jp_sal), zpres(:,:) )
       DO jk = 1, jpk
          DO jj = 1, jpj
             DO ji = 1, jpi
                !                                        ! below ice covered area (if tn < "freezing"+0.1 )
-               IF( tsn(ji,jj,jk,jp_tem) <= ztfreez(ji,jj) + 0.1 ) THEN   ;   zice = 1.e0
-               ELSE                                                      ;   zice = 0.e0
+               IF( tsn(ji,jj,jk,jp_tem) <= zfzp(ji,jj) + 0.1 ) THEN   ;   zice = 1._wp
+               ELSE                                                   ;   zice = 0._wp
                ENDIF
                zind(ji,jj,jk) = MAX (   &
@@ -224,5 +228,12 @@
          !                                                     ! Surface value : 
          IF( lk_vvl ) THEN   ;   zwz(:,:, 1 ) = 0.e0                         ! volume variable
-         ELSE                ;   zwz(:,:, 1 ) = pwn(:,:,1) * ptn(:,:,1,jn)   ! linear free surface 
+         ELSE
+            DO jj = 1, jpj   ! vector opt.
+               DO ji = 1, jpi   ! vector opt.
+                  ikt = mikt(ji,jj)                
+                  zwz(ji,jj,ikt ) = pwn(ji,jj,ikt) * ptn(ji,jj,ikt,jn)   ! linear free surface 
+                  zwz(ji,jj,1:ikt-1) = 0.e0
+               END DO
+            END DO
          ENDIF
          !
@@ -260,17 +271,18 @@
          END DO
 
-         !                                 ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd ) THEN
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_xad, zwx, pun, ptn(:,:,:,jn) )
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_yad, zwy, pvn, ptn(:,:,:,jn) )
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_zad, zwz, pwn, ptn(:,:,:,jn) )
+         !                                 ! trend diagnostics
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR.    &
+            &( cdtype == 'TRC' .AND. l_trdtrc ) )   THEN
+            CALL trd_tra( kt, cdtype, jn, jptra_xad, zwx, pun, ptn(:,:,:,jn) )
+            CALL trd_tra( kt, cdtype, jn, jptra_yad, zwy, pvn, ptn(:,:,:,jn) )
+            CALL trd_tra( kt, cdtype, jn, jptra_zad, zwz, pwn, ptn(:,:,:,jn) )
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
          IF( cdtype == 'TRA' .AND. ln_diaptr .AND. ( MOD( kt, nn_fptr ) == 0 ) ) THEN  
-           IF( jn == jp_tem )  htr_adv(:) = ptr_vj( zwy(:,:,:) )
-           IF( jn == jp_sal )  str_adv(:) = ptr_vj( zwy(:,:,:) )
+           IF( jn == jp_tem )   htr_adv(:) = ptr_vj( zwy(:,:,:) )
+           IF( jn == jp_sal )   str_adv(:) = ptr_vj( zwy(:,:,:) )
          ENDIF
          !
-      ENDDO
+      END DO
 
       ! ---------------------------  required in restart file to ensure restartability)
@@ -281,6 +293,6 @@
       ENDIF
       !
-      CALL wrk_dealloc( jpi, jpj, ztfreez )
-      CALL wrk_dealloc( jpi, jpj, jpk, zwz, zind )
+      CALL wrk_dealloc( jpi, jpj, zpres, zfzp )
+      CALL wrk_dealloc( jpi, jpj, jpk, zwx, zwy, zwz, zind )
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_adv_cen2')
@@ -303,5 +315,4 @@
       INTEGER  ::   ii0, ii1, ij0, ij1      ! temporary integers
       !!----------------------------------------------------------------------
-      
       !
       IF( nn_timing == 1 )  CALL timing_start('ups_orca_set')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_eiv.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_eiv.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_eiv.F90	(revision 5075)
@@ -25,5 +25,4 @@
    USE phycst          ! physical constants
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
-   USE diaar5, ONLY:   lk_diaar5
 # endif  
    USE wrk_nemo        ! Memory Allocation
@@ -161,5 +160,5 @@
          CALL iom_put( "voce_eiv", v_eiv )    ! j-eiv current
          CALL iom_put( "woce_eiv", w_eiv )    ! vert. eiv current
-         IF( lk_diaar5 ) THEN
+         IF( iom_use('ueiv_heattr') ) THEN
             zztmp = 0.5 * rau0 * rcp 
             z2d(:,:) = 0.e0 
@@ -167,5 +166,5 @@
                DO jj = 2, jpjm1
                   DO ji = fs_2, fs_jpim1   ! vector opt.
-                     z2d(ji,jj) = z2d(ji,jj) + zztmp * u_eiv(ji,jj,jk) &
+                     z2d(ji,jj) = z2d(ji,jj) + u_eiv(ji,jj,jk) &
                        &         * (tsn(ji,jj,jk,jp_tem)+tsn(ji+1,jj,jk,jp_tem)) * e2u(ji,jj) * fse3u(ji,jj,jk) 
                   END DO
@@ -173,10 +172,14 @@
             END DO
             CALL lbc_lnk( z2d, 'U', -1. )
-            CALL iom_put( "ueiv_heattr", z2d )                  ! heat transport in i-direction
+            CALL iom_put( "ueiv_heattr", zztmp * z2d )                  ! heat transport in i-direction
+         ENDIF
+            
+         IF( iom_use('veiv_heattr') ) THEN
+            zztmp = 0.5 * rau0 * rcp 
             z2d(:,:) = 0.e0 
             DO jk = 1, jpkm1
                DO jj = 2, jpjm1
                   DO ji = fs_2, fs_jpim1   ! vector opt.
-                     z2d(ji,jj) = z2d(ji,jj) + zztmp * v_eiv(ji,jj,jk) &
+                     z2d(ji,jj) = z2d(ji,jj) + v_eiv(ji,jj,jk) &
                      &           * (tsn(ji,jj,jk,jp_tem)+tsn(ji,jj+1,jk,jp_tem)) * e1v(ji,jj) * fse3v(ji,jj,jk) 
                   END DO
@@ -184,5 +187,5 @@
             END DO
             CALL lbc_lnk( z2d, 'V', -1. )
-            CALL iom_put( "veiv_heattr", z2d )                  !  heat transport in i-direction
+            CALL iom_put( "veiv_heattr", zztmp * z2d )                  !  heat transport in i-direction
          ENDIF
     END IF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_mle.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_mle.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_mle.F90	(revision 5075)
@@ -203,6 +203,11 @@
       !
       !                                      !==  structure function value at uw- and vw-points  ==!
-      zhu(:,:) = 1._wp / zhu(:,:)                   ! hu --> 1/hu
-      zhv(:,:) = 1._wp / zhv(:,:)
+      DO jj = 1, jpjm1
+         DO ji = 1, fs_jpim1   ! vector opt.
+            zhu(ji,jj) = 1._wp / zhu(ji,jj)                   ! hu --> 1/hu
+            zhv(ji,jj) = 1._wp / zhv(ji,jj)
+         END DO
+      END DO
+      !
       zpsi_uw(:,:,:) = 0._wp
       zpsi_vw(:,:,:) = 0._wp
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl.F90	(revision 5075)
@@ -16,29 +16,28 @@
    !!----------------------------------------------------------------------
    USE oce            ! ocean dynamics and active tracers
+   USE trc_oce        ! share passive tracers/Ocean variables
    USE dom_oce        ! ocean space and time domain
-   USE trdmod_oce     ! tracers trends 
-   USE trdtra         ! tracers trends 
-   USE in_out_manager ! I/O manager
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! tracers trends manager
    USE dynspg_oce     ! choice/control of key cpp for surface pressure gradient
-   USE trabbl         ! tracers: bottom boundary layer
-   USE lib_mpp        ! distribued memory computing
-   USE lbclnk         ! ocean lateral boundary condition (or mpp link) 
+   USE sbcrnf          ! river runoffs
    USE diaptr         ! poleward transport diagnostics
-   USE trc_oce        ! share passive tracers/Ocean variables
+   !
    USE wrk_nemo       ! Memory Allocation
    USE timing         ! Timing
    USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
-   USE eosbn2          ! equation of state
-   USE sbcrnf          ! river runoffs
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! distribued memory computing
+   USE lbclnk         ! ocean lateral boundary condition (or mpp link) 
 
    IMPLICIT NONE
    PRIVATE
 
-   PUBLIC   tra_adv_muscl  ! routine called by step.F90
-
-   LOGICAL  :: l_trd                        ! flag to compute trends
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) :: upsmsk !: mixed upstream/centered scheme near some straits
-   !                                                             !  and in closed seas (orca 2 and 4 configurations)
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: xind         !: mixed upstream/centered index
+   PUBLIC   tra_adv_muscl   ! routine called by traadv.F90
+   
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   upsmsk   !: mixed upstream/centered scheme near some straits
+   !                                                           !  and in closed seas (orca 2 and 4 configurations)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   xind     !: mixed upstream/centered index
+   
    !! * Substitutions
 #  include "domzgr_substitute.h90"
@@ -51,6 +50,6 @@
 CONTAINS
 
-   SUBROUTINE tra_adv_muscl( kt, kit000, cdtype, p2dt, pun, pvn, pwn, &
-      &                                        ptb, pta, kjpt, ld_msc_ups )
+   SUBROUTINE tra_adv_muscl( kt, kit000, cdtype, p2dt, pun, pvn, pwn,   &
+      &                                                ptb, pta, kjpt, ld_msc_ups )
       !!----------------------------------------------------------------------
       !!                    ***  ROUTINE tra_adv_muscl  ***
@@ -68,6 +67,4 @@
       !!              IPSL, Sept. 2000 (http://www.lodyc.jussieu.fr/opa)
       !!----------------------------------------------------------------------
-      USE oce     , ONLY:   zwx   => ua    , zwy   => va          ! (ua,va) used as workspace
-      !
       INTEGER                              , INTENT(in   ) ::   kt              ! ocean time-step index
       INTEGER                              , INTENT(in   ) ::   kit000          ! first time step index
@@ -79,19 +76,18 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptb             ! before tracer field
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta             ! tracer trend 
-
-      !
-      INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
+      !
+      INTEGER  ::   ji, jj, jk, jn            ! dummy loop indices
+      INTEGER  ::   ierr                      ! local integer
       REAL(wp) ::   zu, z0u, zzwx, zw         ! local scalars
       REAL(wp) ::   zv, z0v, zzwy, z0w        !   -      -
       REAL(wp) ::   ztra, zbtr, zdt, zalpha   !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zslpx, zslpy
-      INTEGER  ::   ierr
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zslpx, zslpy   ! 3D workspace
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zwx  , zwy     ! -      - 
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_adv_muscl')
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zslpx, zslpy )
-      !
-
+      CALL wrk_alloc( jpi, jpj, jpk, zslpx, zslpy, zwx, zwy )
+      !
       IF( kt == kit000 )  THEN
          IF(lwp) WRITE(numout,*)
@@ -117,25 +113,20 @@
 
          !
-         ! Upstream / centered scheme indicator
+         ! Upstream / MUSCL scheme indicator
          ! ------------------------------------
+!!gm  useless
          xind(:,:,:) = 1._wp                             ! set equal to 1 where up-stream is not needed
+!!gm
          !
          IF( ld_msc_ups )  THEN
-            DO jk = 1, jpk
-               DO jj = 1, jpj
-                  DO ji = 1, jpi
-                     xind(ji,jj,jk) = 1  - MAX (           &
-                        rnfmsk(ji,jj) * rnfmsk_z(jk),      &  ! near runoff mouths (& closed sea outflows)
-                        upsmsk(ji,jj) ) * tmask(ji,jj,jk)     ! some of some straits
-                  END DO
-               END DO
+            DO jk = 1, jpkm1
+               xind(:,:,jk) = 1._wp                              &                 ! =>1 where up-stream is not needed
+                  &         - MAX ( rnfmsk(:,:) * rnfmsk_z(jk),  &                 ! =>0 near runoff mouths (& closed sea outflows)
+                  &                 upsmsk(:,:)                ) * tmask(:,:,jk)   ! =>0 near some straits
             END DO
          ENDIF 
          !
       ENDIF 
-      !
-      l_trd = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) ) l_trd = .TRUE.
-      
+      !      
       !                                                     ! ===========
       DO jn = 1, kjpt                                       ! tracer loop
@@ -192,6 +183,6 @@
                   zalpha = 0.5 - z0u
                   zu  = z0u - 0.5 * pun(ji,jj,jk) * zdt / ( e1u(ji,jj) * e2u(ji,jj) * fse3u(ji,jj,jk) )
-                  zzwx = ptb(ji+1,jj,jk,jn) + xind(ji,jj,jk) * (zu * zslpx(ji+1,jj,jk))
-                  zzwy = ptb(ji  ,jj,jk,jn) + xind(ji,jj,jk) * (zu * zslpx(ji  ,jj,jk))
+                  zzwx = ptb(ji+1,jj,jk,jn) + xind(ji,jj,jk) * zu * zslpx(ji+1,jj,jk)
+                  zzwy = ptb(ji  ,jj,jk,jn) + xind(ji,jj,jk) * zu * zslpx(ji  ,jj,jk)
                   zwx(ji,jj,jk) = pun(ji,jj,jk) * ( zalpha * zzwx + (1.-zalpha) * zzwy )
                   !
@@ -199,6 +190,6 @@
                   zalpha = 0.5 - z0v
                   zv  = z0v - 0.5 * pvn(ji,jj,jk) * zdt / ( e1v(ji,jj) * e2v(ji,jj) * fse3v(ji,jj,jk) )
-                  zzwx = ptb(ji,jj+1,jk,jn) + xind(ji,jj,jk) * (zv * zslpy(ji,jj+1,jk))
-                  zzwy = ptb(ji,jj  ,jk,jn) + xind(ji,jj,jk) * (zv * zslpy(ji,jj  ,jk))
+                  zzwx = ptb(ji,jj+1,jk,jn) + xind(ji,jj,jk) * zv * zslpy(ji,jj+1,jk)
+                  zzwy = ptb(ji,jj  ,jk,jn) + xind(ji,jj,jk) * zv * zslpy(ji,jj  ,jk)
                   zwy(ji,jj,jk) = pvn(ji,jj,jk) * ( zalpha * zzwx + (1.-zalpha) * zzwy )
                END DO
@@ -222,7 +213,8 @@
          END DO        
          !                                 ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd )  THEN
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_xad, zwx, pun, ptb(:,:,:,jn) )
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_yad, zwy, pvn, ptb(:,:,:,jn) )
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR.   &
+            &( cdtype == 'TRC' .AND. l_trdtrc )      )  THEN
+            CALL trd_tra( kt, cdtype, jn, jptra_xad, zwx, pun, ptb(:,:,:,jn) )
+            CALL trd_tra( kt, cdtype, jn, jptra_yad, zwy, pvn, ptb(:,:,:,jn) )
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
@@ -274,6 +266,6 @@
                   zalpha = 0.5 + z0w
                   zw  = z0w - 0.5 * pwn(ji,jj,jk+1) * zdt * zbtr 
-                  zzwx = ptb(ji,jj,jk+1,jn) + xind(ji,jj,jk) * (zw * zslpx(ji,jj,jk+1))
-                  zzwy = ptb(ji,jj,jk  ,jn) + xind(ji,jj,jk) * (zw * zslpx(ji,jj,jk  ))
+                  zzwx = ptb(ji,jj,jk+1,jn) + xind(ji,jj,jk) * zw * zslpx(ji,jj,jk+1)
+                  zzwy = ptb(ji,jj,jk  ,jn) + xind(ji,jj,jk) * zw * zslpx(ji,jj,jk  )
                   zwx(ji,jj,jk+1) = pwn(ji,jj,jk+1) * ( zalpha * zzwx + (1.-zalpha) * zzwy )
                END DO 
@@ -281,9 +273,8 @@
          END DO
 
-         ! Compute & add the vertical advective trend
-         DO jk = 1, jpkm1
+         DO jk = 1, jpkm1                    ! Compute & add the vertical advective trend
             DO jj = 2, jpjm1      
                DO ji = fs_2, fs_jpim1   ! vector opt.
-                  zbtr = 1. / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
+                  zbtr = 1. / ( e1e2t(ji,jj) * fse3t(ji,jj,jk) )
                   ! vertical advective trends 
                   ztra = - zbtr * ( zwx(ji,jj,jk) - zwx(ji,jj,jk+1) )
@@ -294,9 +285,11 @@
          END DO
          !                                 ! Save the vertical advective trends for diagnostic
-         IF( l_trd ) CALL trd_tra( kt, cdtype, jn, jptra_trd_zad, zwx, pwn, ptb(:,:,:,jn) )
-         !
-      ENDDO
-      !
-      CALL wrk_dealloc( jpi, jpj, jpk, zslpx, zslpy )
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR.     &
+            &( cdtype == 'TRC' .AND. l_trdtrc )      )   &
+            CALL trd_tra( kt, cdtype, jn, jptra_zad, zwx, pwn, ptb(:,:,:,jn) )
+         !
+      END DO
+      !
+      CALL wrk_dealloc( jpi, jpj, jpk, zslpx, zslpy, zwx, zwy )
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_adv_muscl')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl2.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl2.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_muscl2.F90	(revision 5075)
@@ -13,14 +13,14 @@
    !!----------------------------------------------------------------------
    USE oce             ! ocean dynamics and active tracers
+   USE trc_oce         ! share passive tracers/Ocean variables
    USE dom_oce         ! ocean space and time domain
-   USE trdmod_oce      ! tracers trends 
-   USE trdtra          ! tracers trends 
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
    USE in_out_manager  ! I/O manager
    USE dynspg_oce      ! choice/control of key cpp for surface pressure gradient
-   USE trabbl          ! tracers: bottom boundary layer
+   USE diaptr          ! poleward transport diagnostics
+   !
    USE lib_mpp         ! distribued memory computing
    USE lbclnk          ! ocean lateral boundary condition (or mpp link) 
-   USE diaptr          ! poleward transport diagnostics
-   USE trc_oce         ! share passive tracers/Ocean variables
    USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
@@ -31,6 +31,4 @@
 
    PUBLIC   tra_adv_muscl2        ! routine called by step.F90
-
-   LOGICAL  :: l_trd       ! flag to compute trends
 
    !! * Substitutions
@@ -61,6 +59,4 @@
       !!              IPSL, Sept. 2000 (http://www.lodyc.jussieu.fr/opa)
       !!----------------------------------------------------------------------
-      USE oce     , ONLY:   zwx   => ua    , zwy   => va         ! (ua,va) used as 3D workspace
-      !!
       INTEGER                              , INTENT(in   ) ::   kt              ! ocean time-step index
       INTEGER                              , INTENT(in   ) ::   kit000          ! first time step index
@@ -76,10 +72,10 @@
       REAL(wp) ::   zv, z0v, zzwy, z0w        !   -      -
       REAL(wp) ::   ztra, zbtr, zdt, zalpha   !   -      -
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zslpx, zslpy
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zslpx, zslpy , zwx, zwy
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_adv_muscl2')
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zslpx, zslpy )
+      CALL wrk_alloc( jpi, jpj, jpk, zslpx, zslpy, zwx, zwy )
       !
 
@@ -90,7 +86,4 @@
       ENDIF
       !
-      l_trd = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )   l_trd = .TRUE.
-
       !                                                          ! ===========
       DO jn = 1, kjpt                                            ! tracer loop
@@ -200,7 +193,8 @@
          END DO
          !                                 ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd ) THEN
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_xad, zwx, pun, ptb(:,:,:,jn) )
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_yad, zwy, pvn, ptb(:,:,:,jn) )
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR.   &
+            &( cdtype == 'TRC' .AND. l_trdtrc )      ) THEN
+            CALL trd_tra( kt, cdtype, jn, jptra_xad, zwx, pun, ptb(:,:,:,jn) )
+            CALL trd_tra( kt, cdtype, jn, jptra_yad, zwy, pvn, ptb(:,:,:,jn) )
          END IF
 
@@ -284,9 +278,11 @@
          END DO
          !                       ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd )  CALL trd_tra( kt, cdtype, jn, jptra_trd_zad, zwx, pwn, ptb(:,:,:,jn) )
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR.     &
+            &( cdtype == 'TRC' .AND. l_trdtrc )      )   &
+            CALL trd_tra( kt, cdtype, jn, jptra_zad, zwx, pwn, ptb(:,:,:,jn) )
          !
       END DO
       !
-      CALL wrk_dealloc( jpi, jpj, jpk, zslpx, zslpy )
+      CALL wrk_dealloc( jpi, jpj, jpk, zslpx, zslpy, zwx, zwy )
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_adv_muscl2')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_qck.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_qck.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_qck.F90	(revision 5075)
@@ -17,13 +17,13 @@
    USE oce             ! ocean dynamics and active tracers
    USE dom_oce         ! ocean space and time domain
-   USE trdmod_oce      ! ocean space and time domain
-   USE trdtra          ! ocean tracers trends 
-   USE trabbl          ! advective term in the BBL
+   USE trc_oce         ! share passive tracers/Ocean variables
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
+   USE dynspg_oce      ! surface pressure gradient variables
+   USE diaptr          ! poleward transport diagnostics
+   !
    USE lib_mpp         ! distribued memory computing
    USE lbclnk          ! ocean lateral boundary condition (or mpp link)
-   USE dynspg_oce      ! surface pressure gradient variables
    USE in_out_manager  ! I/O manager
-   USE diaptr          ! poleward transport diagnostics
-   USE trc_oce         ! share passive tracers/Ocean variables
    USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
@@ -93,5 +93,4 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta             ! tracer trend 
       !!----------------------------------------------------------------------
-
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_adv_qck')
@@ -103,8 +102,7 @@
          IF(lwp) WRITE(numout,*)
       ENDIF
-      !
       l_trd = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) ) l_trd = .TRUE.
-
+      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) )   l_trd = .TRUE.
+      !
       ! I. The horizontal fluxes are computed with the QUICKEST + ULTIMATE scheme
       CALL tra_adv_qck_i( kt, cdtype, p2dt, pun, ptb, ptn, pta, kjpt ) 
@@ -124,6 +122,4 @@
       !!
       !!----------------------------------------------------------------------
-      USE oce     , ONLY:   zwx => ua       ! ua used as workspace
-      !
       INTEGER                              , INTENT(in   ) ::   kt         ! ocean time-step index
       CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
@@ -136,8 +132,8 @@
       INTEGER  :: ji, jj, jk, jn   ! dummy loop indices
       REAL(wp) :: ztra, zbtr, zdir, zdx, zdt, zmsk   ! local scalars
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zfu, zfc, zfd
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwx, zfu, zfc, zfd
       !----------------------------------------------------------------------
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zfu, zfc, zfd )
+      CALL wrk_alloc( jpi, jpj, jpk, zwx, zfu, zfc, zfd )
       !                                                          ! ===========
       DO jn = 1, kjpt                                            ! tracer loop
@@ -233,9 +229,9 @@
          END DO
          !                                 ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd )  CALL trd_tra( kt, cdtype, jn, jptra_trd_xad, zwx, pun, ptn(:,:,:,jn) )
+         IF( l_trd )   CALL trd_tra( kt, cdtype, jn, jptra_xad, zwx, pun, ptn(:,:,:,jn) )
          !
       END DO
       !
-      CALL wrk_dealloc( jpi, jpj, jpk, zfu, zfc, zfd )
+      CALL wrk_dealloc( jpi, jpj, jpk, zwx, zfu, zfc, zfd )
       !
    END SUBROUTINE tra_adv_qck_i
@@ -247,6 +243,4 @@
       !!
       !!----------------------------------------------------------------------
-      USE oce     , ONLY:   zwy => ua       ! ua used as workspace
-      !
       INTEGER                              , INTENT(in   ) ::   kt         ! ocean time-step index
       CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
@@ -259,8 +253,8 @@
       INTEGER  :: ji, jj, jk, jn   ! dummy loop indices
       REAL(wp) :: ztra, zbtr, zdir, zdx, zdt, zmsk   ! local scalars
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zfu, zfc, zfd
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwy, zfu, zfc, zfd
       !----------------------------------------------------------------------
       !
-      CALL wrk_alloc( jpi, jpj, jpk, zfu, zfc, zfd )
+      CALL wrk_alloc( jpi, jpj, jpk, zwy, zfu, zfc, zfd )
       !
       !                                                          ! ===========
@@ -359,5 +353,5 @@
          END DO
          !                                 ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd )  CALL trd_tra( kt, cdtype, jn, jptra_trd_yad, zwy, pvn, ptn(:,:,:,jn) )
+         IF( l_trd )   CALL trd_tra( kt, cdtype, jn, jptra_yad, zwy, pvn, ptn(:,:,:,jn) )
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
          IF( cdtype == 'TRA' .AND. ln_diaptr .AND. ( MOD( kt, nn_fptr ) == 0 ) ) THEN  
@@ -368,5 +362,5 @@
       END DO
       !
-      CALL wrk_dealloc( jpi, jpj, jpk, zfu, zfc, zfd )
+      CALL wrk_dealloc( jpi, jpj, jpk, zwy, zfu, zfc, zfd )
       !
    END SUBROUTINE tra_adv_qck_j
@@ -378,6 +372,4 @@
       !!
       !!----------------------------------------------------------------------
-      USE oce, ONLY:   zwz => ua   ! ua used as workspace
-      !
       INTEGER                              , INTENT(in   ) ::   kt       ! ocean time-step index
       CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype   ! =TRA or TRC (tracer indicator)
@@ -389,6 +381,8 @@
       INTEGER  ::   ji, jj, jk, jn   ! dummy loop indices
       REAL(wp) ::   zbtr , ztra      ! local scalars
-      !!----------------------------------------------------------------------
-
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwz
+      !!----------------------------------------------------------------------
+      !
+      CALL wrk_alloc( jpi, jpj, jpk, zwz )
       !                                                          ! ===========
       DO jn = 1, kjpt                                            ! tracer loop
@@ -422,7 +416,9 @@
          END DO
          !                                 ! Save the vertical advective trends for diagnostic
-         IF( l_trd )  CALL trd_tra( kt, cdtype, jn, jptra_trd_zad, zwz, pwn, ptn(:,:,:,jn) )
+         IF( l_trd )  CALL trd_tra( kt, cdtype, jn, jptra_zad, zwz, pwn, ptn(:,:,:,jn) )
          !
       END DO
+      !
+      CALL wrk_dealloc( jpi, jpj, jpk, zwz )
       !
    END SUBROUTINE tra_adv_cen2_k
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_tvd.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_tvd.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_tvd.F90	(revision 5075)
@@ -22,12 +22,13 @@
    USE oce            ! ocean dynamics and active tracers
    USE dom_oce        ! ocean space and time domain
-   USE trdmod_oce     ! tracers trends
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE trd_oce        ! trends: ocean variables
    USE trdtra         ! tracers trends
-   USE in_out_manager ! I/O manager
    USE dynspg_oce     ! choice/control of key cpp for surface pressure gradient
+   USE diaptr         ! poleward transport diagnostics
+   !
    USE lib_mpp        ! MPP library
    USE lbclnk         ! ocean lateral boundary condition (or mpp link) 
-   USE diaptr         ! poleward transport diagnostics
-   USE trc_oce        ! share passive tracers/Ocean variables
+   USE in_out_manager ! I/O manager
    USE wrk_nemo       ! Memory Allocation
    USE timing         ! Timing
@@ -37,5 +38,6 @@
    PRIVATE
 
-   PUBLIC   tra_adv_tvd    ! routine called by step.F90
+   PUBLIC   tra_adv_tvd        ! routine called by traadv.F90
+   PUBLIC   tra_adv_tvd_zts    ! routine called by traadv.F90
 
    LOGICAL ::   l_trd   ! flag to compute trends
@@ -77,5 +79,6 @@
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta             ! tracer trend 
       !
-      INTEGER  ::   ji, jj, jk, jn           ! dummy loop indices  
+      INTEGER  ::   ji, jj, jk, jn           ! dummy loop indices
+      INTEGER  ::   ik  
       REAL(wp) ::   z2dtt, zbtr, ztra        ! local scalar
       REAL(wp) ::   zfp_ui, zfp_vj, zfp_wk   !   -      -
@@ -93,8 +96,8 @@
          IF(lwp) WRITE(numout,*) 'tra_adv_tvd : TVD advection scheme on ', cdtype
          IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+         !
+         l_trd = .FALSE.
+         IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) ) l_trd = .TRUE.
       ENDIF
-      !
-      l_trd = .FALSE.
-      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) ) l_trd = .TRUE.
       !
       IF( l_trd )  THEN
@@ -103,5 +106,5 @@
       ENDIF
       !
-      zwi(:,:,:) = 0.e0
+      zwi(:,:,:) = 0.e0 ; zwz(:,:,:) = 0.e0
       !
       !                                                          ! ===========
@@ -132,11 +135,21 @@
          ! upstream tracer flux in the k direction
          ! Surface value
-         IF( lk_vvl ) THEN   ;   zwz(:,:, 1 ) = 0.e0                         ! volume variable
-         ELSE                ;   zwz(:,:, 1 ) = pwn(:,:,1) * ptb(:,:,1,jn)   ! linear free surface 
+         IF( lk_vvl ) THEN   
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zwz(ji,jj, mikt(ji,jj) ) = 0.e0                         ! volume variable
+               END DO
+            END DO
+         ELSE                
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  zwz(ji,jj, mikt(ji,jj) ) = pwn(ji,jj,mikt(ji,jj)) * ptb(ji,jj,mikt(ji,jj),jn)   ! linear free surface 
+               END DO
+            END DO   
          ENDIF
          ! Interior value
-         DO jk = 2, jpkm1
-            DO jj = 1, jpj
-               DO ji = 1, jpi
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               DO jk = mikt(ji,jj)+1, jpkm1
                   zfp_wk = pwn(ji,jj,jk) + ABS( pwn(ji,jj,jk) )
                   zfm_wk = pwn(ji,jj,jk) - ABS( pwn(ji,jj,jk) )
@@ -157,5 +170,5 @@
                      &             + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) )
                   ! update and guess with monotonic sheme
-                  pta(ji,jj,jk,jn) =   pta(ji,jj,jk,jn)         + ztra
+                  pta(ji,jj,jk,jn) =   pta(ji,jj,jk,jn)         + ztra   * tmask(ji,jj,jk)
                   zwi(ji,jj,jk)    = ( ptb(ji,jj,jk,jn) + z2dtt * ztra ) * tmask(ji,jj,jk)
                END DO
@@ -191,8 +204,286 @@
          zwz(:,:,1) = 0.e0         ! Surface value
          !
-         DO jk = 2, jpkm1          ! Interior value
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               ik=mikt(ji,jj)
+               ! surface value
+               zwz(ji,jj,1:ik) = 0.e0
+               ! Interior value
+               DO jk = mikt(ji,jj)+1, jpkm1                    
+                  zwz(ji,jj,jk) = 0.5 * pwn(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji,jj,jk-1,jn) ) - zwz(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         CALL lbc_lnk( zwx, 'U', -1. )   ;   CALL lbc_lnk( zwy, 'V', -1. )         ! Lateral bondary conditions
+         CALL lbc_lnk( zwz, 'W',  1. )
+
+         ! 4. monotonicity algorithm
+         ! -------------------------
+         CALL nonosc( ptb(:,:,:,jn), zwx, zwy, zwz, zwi, p2dt )
+
+
+         ! 5. final trend with corrected fluxes
+         ! ------------------------------------
+         DO jk = 1, jpkm1
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.  
+                  zbtr = 1. / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
+                  ! total advective trends
+                  ztra = - zbtr * (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )   &
+                     &             + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  )   &
+                     &             + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) )
+                  ! add them to the general tracer trends
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + ztra * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+
+         !                                 ! trend diagnostics (contribution of upstream fluxes)
+         IF( l_trd )  THEN 
+            ztrdx(:,:,:) = ztrdx(:,:,:) + zwx(:,:,:)  ! <<< Add to previously computed
+            ztrdy(:,:,:) = ztrdy(:,:,:) + zwy(:,:,:)  ! <<< Add to previously computed
+            ztrdz(:,:,:) = ztrdz(:,:,:) + zwz(:,:,:)  ! <<< Add to previously computed
+            
+            CALL trd_tra( kt, cdtype, jn, jptra_xad, ztrdx, pun, ptn(:,:,:,jn) )   
+            CALL trd_tra( kt, cdtype, jn, jptra_yad, ztrdy, pvn, ptn(:,:,:,jn) )  
+            CALL trd_tra( kt, cdtype, jn, jptra_zad, ztrdz, pwn, ptn(:,:,:,jn) ) 
+         END IF
+         !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
+         IF( cdtype == 'TRA' .AND. ln_diaptr .AND. ( MOD( kt, nn_fptr ) == 0 ) ) THEN  
+           IF( jn == jp_tem )  htr_adv(:) = ptr_vj( zwy(:,:,:) ) + htr_adv(:)
+           IF( jn == jp_sal )  str_adv(:) = ptr_vj( zwy(:,:,:) ) + str_adv(:)
+         ENDIF
+         !
+      END DO
+      !
+                   CALL wrk_dealloc( jpi, jpj, jpk, zwi, zwz )
+      IF( l_trd )  CALL wrk_dealloc( jpi, jpj, jpk, ztrdx, ztrdy, ztrdz )
+      !
+      IF( nn_timing == 1 )  CALL timing_stop('tra_adv_tvd')
+      !
+   END SUBROUTINE tra_adv_tvd
+
+   SUBROUTINE tra_adv_tvd_zts ( kt, kit000, cdtype, p2dt, pun, pvn, pwn,      &
+      &                                       ptb, ptn, pta, kjpt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE tra_adv_tvd_zts  ***
+      !! 
+      !! **  Purpose :   Compute the now trend due to total advection of 
+      !!       tracers and add it to the general trend of tracer equations
+      !!
+      !! **  Method  :   TVD ZTS scheme, i.e. 2nd order centered scheme with
+      !!       corrected flux (monotonic correction). This version use sub-
+      !!       timestepping for the vertical advection which increases stability
+      !!       when vertical metrics are small.
+      !!       note: - this advection scheme needs a leap-frog time scheme
+      !!
+      !! ** Action : - update (pta) with the now advective tracer trends
+      !!             - save the trends 
+      !!----------------------------------------------------------------------
+      USE oce     , ONLY:   zwx => ua        , zwy => va          ! (ua,va) used as workspace
+      !
+      INTEGER                              , INTENT(in   ) ::   kt              ! ocean time-step index
+      INTEGER                              , INTENT(in   ) ::   kit000          ! first time step index
+      CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype          ! =TRA or TRC (tracer indicator)
+      INTEGER                              , INTENT(in   ) ::   kjpt            ! number of tracers
+      REAL(wp), DIMENSION(        jpk     ), INTENT(in   ) ::   p2dt            ! vertical profile of tracer time-step
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ) ::   pun, pvn, pwn   ! 3 ocean velocity components
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptb, ptn        ! before and now tracer fields
+      REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta             ! tracer trend 
+      !
+      REAL(wp), DIMENSION( jpk )                           ::   zts             ! length of sub-timestep for vertical advection
+      REAL(wp), DIMENSION( jpk )                           ::   zr_p2dt         ! reciprocal of tracer timestep
+      INTEGER  ::   ji, jj, jk, jl, jn       ! dummy loop indices  
+      INTEGER  ::   jnzts = 5       ! number of sub-timesteps for vertical advection
+      INTEGER  ::   jtb, jtn, jta   ! sub timestep pointers for leap-frog/euler forward steps
+      INTEGER  ::   jtaken          ! toggle for collecting appropriate fluxes from sub timesteps
+      REAL(wp) ::   z_rzts          ! Fractional length of Euler forward sub-timestep for vertical advection
+      REAL(wp) ::   z2dtt, zbtr, ztra        ! local scalar
+      REAL(wp) ::   zfp_ui, zfp_vj, zfp_wk   !   -      -
+      REAL(wp) ::   zfm_ui, zfm_vj, zfm_wk   !   -      -
+      REAL(wp), POINTER, DIMENSION(:,:  ) :: zwx_sav , zwy_sav
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zwi, zwz, zhdiv, zwz_sav, zwzts
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: ztrdx, ztrdy, ztrdz
+      REAL(wp), POINTER, DIMENSION(:,:,:,:) :: ztrs
+      !!----------------------------------------------------------------------
+      !
+      IF( nn_timing == 1 )  CALL timing_start('tra_adv_tvd_zts')
+      !
+      CALL wrk_alloc( jpi, jpj, zwx_sav, zwy_sav )
+      CALL wrk_alloc( jpi, jpj, jpk, zwi, zwz , zhdiv, zwz_sav, zwzts )
+      CALL wrk_alloc( jpi, jpj, jpk, 3, ztrs )
+      !
+      IF( kt == kit000 )  THEN
+         IF(lwp) WRITE(numout,*)
+         IF(lwp) WRITE(numout,*) 'tra_adv_tvd_zts : TVD ZTS advection scheme on ', cdtype
+         IF(lwp) WRITE(numout,*) '~~~~~~~~~~~'
+      ENDIF
+      !
+      l_trd = .FALSE.
+      IF( ( cdtype == 'TRA' .AND. l_trdtra ) .OR. ( cdtype == 'TRC' .AND. l_trdtrc ) ) l_trd = .TRUE.
+      !
+      IF( l_trd )  THEN
+         CALL wrk_alloc( jpi, jpj, jpk, ztrdx, ztrdy, ztrdz )
+         ztrdx(:,:,:) = 0._wp  ;    ztrdy(:,:,:) = 0._wp  ;   ztrdz(:,:,:) = 0._wp
+      ENDIF
+      !
+      zwi(:,:,:) = 0._wp
+      z_rzts = 1._wp / REAL( jnzts, wp )
+      zr_p2dt(:) = 1._wp / p2dt(:)
+      !
+      !                                                          ! ===========
+      DO jn = 1, kjpt                                            ! tracer loop
+         !                                                       ! ===========
+         ! 1. Bottom value : flux set to zero
+         ! ----------------------------------
+         zwx(:,:,jpk) = 0._wp   ;    zwz(:,:,jpk) = 0._wp
+         zwy(:,:,jpk) = 0._wp   ;    zwi(:,:,jpk) = 0._wp
+
+         ! 2. upstream advection with initial mass fluxes & intermediate update
+         ! --------------------------------------------------------------------
+         ! upstream tracer flux in the i and j direction
+         DO jk = 1, jpkm1
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  ! upstream scheme
+                  zfp_ui = pun(ji,jj,jk) + ABS( pun(ji,jj,jk) )
+                  zfm_ui = pun(ji,jj,jk) - ABS( pun(ji,jj,jk) )
+                  zfp_vj = pvn(ji,jj,jk) + ABS( pvn(ji,jj,jk) )
+                  zfm_vj = pvn(ji,jj,jk) - ABS( pvn(ji,jj,jk) )
+                  zwx(ji,jj,jk) = 0.5_wp * ( zfp_ui * ptb(ji,jj,jk,jn) + zfm_ui * ptb(ji+1,jj  ,jk,jn) )
+                  zwy(ji,jj,jk) = 0.5_wp * ( zfp_vj * ptb(ji,jj,jk,jn) + zfm_vj * ptb(ji  ,jj+1,jk,jn) )
+               END DO
+            END DO
+         END DO
+
+         ! upstream tracer flux in the k direction
+         ! Surface value
+         IF( lk_vvl ) THEN   ;   zwz(:,:, 1 ) = 0._wp                        ! volume variable
+         ELSE                ;   zwz(:,:, 1 ) = pwn(:,:,1) * ptb(:,:,1,jn)   ! linear free surface 
+         ENDIF
+         ! Interior value
+         DO jk = 2, jpkm1
             DO jj = 1, jpj
                DO ji = 1, jpi
-                  zwz(ji,jj,jk) = 0.5 * pwn(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji,jj,jk-1,jn) ) - zwz(ji,jj,jk)
+                  zfp_wk = pwn(ji,jj,jk) + ABS( pwn(ji,jj,jk) )
+                  zfm_wk = pwn(ji,jj,jk) - ABS( pwn(ji,jj,jk) )
+                  zwz(ji,jj,jk) = 0.5_wp * ( zfp_wk * ptb(ji,jj,jk,jn) + zfm_wk * ptb(ji,jj,jk-1,jn) )
+               END DO
+            END DO
+         END DO
+
+         ! total advective trend
+         DO jk = 1, jpkm1
+            z2dtt = p2dt(jk)
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1   ! vector opt.
+                  zbtr = 1._wp / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
+                  ! total intermediate advective trends
+                  ztra = - zbtr * (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk  )   &
+                     &             + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk  )   &
+                     &             + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) )
+                  ! update and guess with monotonic sheme
+                  pta(ji,jj,jk,jn) =   pta(ji,jj,jk,jn)         + ztra
+                  zwi(ji,jj,jk)    = ( ptb(ji,jj,jk,jn) + z2dtt * ztra ) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         !                             ! Lateral boundary conditions on zwi  (unchanged sign)
+         CALL lbc_lnk( zwi, 'T', 1. )  
+
+         !                                 ! trend diagnostics (contribution of upstream fluxes)
+         IF( l_trd )  THEN 
+            ! store intermediate advective trends
+            ztrdx(:,:,:) = zwx(:,:,:)   ;    ztrdy(:,:,:) = zwy(:,:,:)  ;   ztrdz(:,:,:) = zwz(:,:,:)
+         END IF
+         !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
+         IF( cdtype == 'TRA' .AND. ln_diaptr .AND. ( MOD( kt, nn_fptr ) == 0 ) ) THEN  
+           IF( jn == jp_tem )  htr_adv(:) = ptr_vj( zwy(:,:,:) )
+           IF( jn == jp_sal )  str_adv(:) = ptr_vj( zwy(:,:,:) )
+         ENDIF
+
+         ! 3. antidiffusive flux : high order minus low order
+         ! --------------------------------------------------
+         ! antidiffusive flux on i and j
+
+
+         DO jk = 1, jpkm1
+
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwx_sav(ji,jj) = zwx(ji,jj,jk)
+                  zwy_sav(ji,jj) = zwy(ji,jj,jk)
+
+                  zwx(ji,jj,jk) = 0.5_wp * pun(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji+1,jj,jk,jn) )
+                  zwy(ji,jj,jk) = 0.5_wp * pvn(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji,jj+1,jk,jn) )
+               END DO
+            END DO
+
+            DO jj = 2, jpjm1         ! partial horizontal divergence
+               DO ji = fs_2, fs_jpim1
+                  zhdiv(ji,jj,jk) = (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk)   &
+                     &               + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk)  )
+               END DO
+            END DO
+
+            DO jj = 1, jpjm1
+               DO ji = 1, fs_jpim1   ! vector opt.
+                  zwx(ji,jj,jk) = zwx(ji,jj,jk)  - zwx_sav(ji,jj)
+                  zwy(ji,jj,jk) = zwy(ji,jj,jk)  - zwy_sav(ji,jj)
+               END DO
+            END DO
+         END DO
+      
+         ! antidiffusive flux on k
+         zwz(:,:,1) = 0._wp        ! Surface value
+         zwz_sav(:,:,:) = zwz(:,:,:)
+         !
+         ztrs(:,:,:,1) = ptb(:,:,:,jn)
+         zwzts(:,:,:) = 0._wp
+
+         DO jl = 1, jnzts                   ! Start of sub timestepping loop
+
+            IF( jl == 1 ) THEN              ! Euler forward to kick things off
+              jtb = 1   ;   jtn = 1   ;   jta = 2
+              zts(:) = p2dt(:) * z_rzts
+              jtaken = MOD( jnzts + 1 , 2)  ! Toggle to collect every second flux
+                                            ! starting at jl =1 if jnzts is odd; 
+                                            ! starting at jl =2 otherwise
+            ELSEIF( jl == 2 ) THEN          ! First leapfrog step
+              jtb = 1   ;   jtn = 2   ;   jta = 3
+              zts(:) = 2._wp * p2dt(:) * z_rzts
+            ELSE                            ! Shuffle pointers for subsequent leapfrog steps
+              jtb = MOD(jtb,3) + 1
+              jtn = MOD(jtn,3) + 1
+              jta = MOD(jta,3) + 1
+            ENDIF
+            DO jk = 2, jpkm1          ! Interior value
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     zwz(ji,jj,jk) = 0.5_wp * pwn(ji,jj,jk) * ( ztrs(ji,jj,jk,jtn) + ztrs(ji,jj,jk-1,jtn) )
+                     IF( jtaken == 0 ) zwzts(ji,jj,jk) = zwzts(ji,jj,jk) + zwz(ji,jj,jk)*zts(jk)           ! Accumulate time-weighted vertcal flux
+                  END DO
+               END DO
+            END DO
+
+            jtaken = MOD( jtaken + 1 , 2 )
+
+            DO jk = 2, jpkm1          ! Interior value
+               DO jj = 2, jpjm1
+                  DO ji = fs_2, fs_jpim1
+                     zbtr = 1._wp / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
+                     ! total advective trends
+                     ztra = - zbtr * (  zhdiv(ji,jj,jk) + zwz(ji,jj,jk) - zwz(ji  ,jj  ,jk+1) )
+                     ztrs(ji,jj,jk,jta) = ztrs(ji,jj,jk,jtb) + zts(jk) * ztra
+                  END DO
+               END DO
+            END DO
+
+         END DO
+
+         DO jk = 2, jpkm1          ! Anti-diffusive vertical flux using average flux from the sub-timestepping
+            DO jj = 2, jpjm1
+               DO ji = fs_2, fs_jpim1
+                  zwz(ji,jj,jk) = zwzts(ji,jj,jk) * zr_p2dt(jk) - zwz_sav(ji,jj,jk)
                END DO
             END DO
@@ -228,7 +519,7 @@
             ztrdz(:,:,:) = ztrdz(:,:,:) + zwz(:,:,:)  ! <<< Add to previously computed
             
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_xad, ztrdx, pun, ptn(:,:,:,jn) )   
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_yad, ztrdy, pvn, ptn(:,:,:,jn) )  
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_zad, ztrdz, pwn, ptn(:,:,:,jn) ) 
+            CALL trd_tra( kt, cdtype, jn, jptra_xad, ztrdx, pun, ptn(:,:,:,jn) )   
+            CALL trd_tra( kt, cdtype, jn, jptra_yad, ztrdy, pvn, ptn(:,:,:,jn) )  
+            CALL trd_tra( kt, cdtype, jn, jptra_zad, ztrdz, pwn, ptn(:,:,:,jn) ) 
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
@@ -240,11 +531,12 @@
       END DO
       !
-                   CALL wrk_dealloc( jpi, jpj, jpk, zwi, zwz )
+                   CALL wrk_dealloc( jpi, jpj, jpk, zwi, zwz, zhdiv, zwz_sav, zwzts )
+                   CALL wrk_dealloc( jpi, jpj, jpk, 3, ztrs )
+                   CALL wrk_dealloc( jpi, jpj, zwx_sav, zwy_sav )
       IF( l_trd )  CALL wrk_dealloc( jpi, jpj, jpk, ztrdx, ztrdy, ztrdz )
       !
-      IF( nn_timing == 1 )  CALL timing_stop('tra_adv_tvd')
-      !
-   END SUBROUTINE tra_adv_tvd
-
+      IF( nn_timing == 1 )  CALL timing_stop('tra_adv_tvd_zts')
+      !
+   END SUBROUTINE tra_adv_tvd_zts
 
    SUBROUTINE nonosc( pbef, paa, pbb, pcc, paft, p2dt )
@@ -261,12 +553,10 @@
       !!       in-space based differencing for fluid
       !!----------------------------------------------------------------------
-      !
-      !!----------------------------------------------------------------------
       REAL(wp), DIMENSION(jpk)         , INTENT(in   ) ::   p2dt            ! vertical profile of tracer time-step
       REAL(wp), DIMENSION (jpi,jpj,jpk), INTENT(in   ) ::   pbef, paft      ! before & after field
       REAL(wp), DIMENSION (jpi,jpj,jpk), INTENT(inout) ::   paa, pbb, pcc   ! monotonic fluxes in the 3 directions
       !
-      INTEGER ::   ji, jj, jk   ! dummy loop indices
-      INTEGER ::   ikm1         ! local integer
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   ikm1         ! local integer
       REAL(wp) ::   zpos, zneg, zbt, za, zb, zc, zbig, zrtrn, z2dtt   ! local scalars
       REAL(wp) ::   zau, zbu, zcu, zav, zbv, zcv, zup, zdo            !   -      -
@@ -278,24 +568,22 @@
       CALL wrk_alloc( jpi, jpj, jpk, zbetup, zbetdo, zbup, zbdo )
       !
-
       zbig  = 1.e+40_wp
       zrtrn = 1.e-15_wp
-      zbetup(:,:,jpk) = 0._wp   ;   zbetdo(:,:,jpk) = 0._wp
-
+      zbetup(:,:,:) = 0._wp   ;   zbetdo(:,:,:) = 0._wp
 
       ! Search local extrema
       ! --------------------
       ! max/min of pbef & paft with large negative/positive value (-/+zbig) inside land
-      zbup = MAX( pbef * tmask - zbig * ( 1.e0 - tmask ),   &
-         &        paft * tmask - zbig * ( 1.e0 - tmask )  )
-      zbdo = MIN( pbef * tmask + zbig * ( 1.e0 - tmask ),   &
-         &        paft * tmask + zbig * ( 1.e0 - tmask )  )
-
-      DO jk = 1, jpkm1
-         ikm1 = MAX(jk-1,1)
-         z2dtt = p2dt(jk)
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1   ! vector opt.
-
+      zbup = MAX( pbef * tmask - zbig * ( 1._wp - tmask ),   &
+         &        paft * tmask - zbig * ( 1._wp - tmask )  )
+      zbdo = MIN( pbef * tmask + zbig * ( 1._wp - tmask ),   &
+         &        paft * tmask + zbig * ( 1._wp - tmask )  )
+
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            DO jk = mikt(ji,jj), jpkm1
+               ikm1 = MAX(jk-1,mikt(ji,jj))
+               z2dtt = p2dt(jk)
+               
                ! search maximum in neighbourhood
                zup = MAX(  zbup(ji  ,jj  ,jk  ),   &
@@ -334,13 +622,13 @@
          DO jj = 2, jpjm1
             DO ji = fs_2, fs_jpim1   ! vector opt.
-               zau = MIN( 1.e0, zbetdo(ji,jj,jk), zbetup(ji+1,jj,jk) )
-               zbu = MIN( 1.e0, zbetup(ji,jj,jk), zbetdo(ji+1,jj,jk) )
+               zau = MIN( 1._wp, zbetdo(ji,jj,jk), zbetup(ji+1,jj,jk) )
+               zbu = MIN( 1._wp, zbetup(ji,jj,jk), zbetdo(ji+1,jj,jk) )
                zcu =       ( 0.5  + SIGN( 0.5 , paa(ji,jj,jk) ) )
-               paa(ji,jj,jk) = paa(ji,jj,jk) * ( zcu * zau + ( 1.e0 - zcu) * zbu )
-
-               zav = MIN( 1.e0, zbetdo(ji,jj,jk), zbetup(ji,jj+1,jk) )
-               zbv = MIN( 1.e0, zbetup(ji,jj,jk), zbetdo(ji,jj+1,jk) )
+               paa(ji,jj,jk) = paa(ji,jj,jk) * ( zcu * zau + ( 1._wp - zcu) * zbu )
+
+               zav = MIN( 1._wp, zbetdo(ji,jj,jk), zbetup(ji,jj+1,jk) )
+               zbv = MIN( 1._wp, zbetup(ji,jj,jk), zbetdo(ji,jj+1,jk) )
                zcv =       ( 0.5  + SIGN( 0.5 , pbb(ji,jj,jk) ) )
-               pbb(ji,jj,jk) = pbb(ji,jj,jk) * ( zcv * zav + ( 1.e0 - zcv) * zbv )
+               pbb(ji,jj,jk) = pbb(ji,jj,jk) * ( zcv * zav + ( 1._wp - zcv) * zbv )
 
       ! monotonic flux in the k direction, i.e. pcc
@@ -349,5 +637,5 @@
                zb = MIN( 1., zbetup(ji,jj,jk+1), zbetdo(ji,jj,jk) )
                zc =       ( 0.5  + SIGN( 0.5 , pcc(ji,jj,jk+1) ) )
-               pcc(ji,jj,jk+1) = pcc(ji,jj,jk+1) * ( zc * za + ( 1.e0 - zc) * zb )
+               pcc(ji,jj,jk+1) = pcc(ji,jj,jk+1) * ( zc * za + ( 1._wp - zc) * zb )
             END DO
          END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_ubs.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_ubs.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traadv_ubs.F90	(revision 5075)
@@ -14,12 +14,13 @@
    USE oce            ! ocean dynamics and active tracers
    USE dom_oce        ! ocean space and time domain
-   USE trdmod_oce     ! ocean space and time domain
-   USE trdtra
-   USE lib_mpp
+   USE trc_oce        ! share passive tracers/Ocean variables
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers 
+   USE dynspg_oce     ! choice/control of key cpp for surface pressure gradient
+   USE diaptr         ! poleward transport diagnostics
+   !
+   USE lib_mpp        ! I/O library
    USE lbclnk         ! ocean lateral boundary condition (or mpp link)
    USE in_out_manager ! I/O manager
-   USE diaptr         ! poleward transport diagnostics
-   USE dynspg_oce     ! choice/control of key cpp for surface pressure gradient
-   USE trc_oce        ! share passive tracers/Ocean variables
    USE wrk_nemo       ! Memory Allocation
    USE timing         ! Timing
@@ -51,10 +52,10 @@
       !!      and add it to the general trend of passive tracer equations.
       !!
-      !! ** Method  :   The upstream biased 3rd order scheme (UBS) is based on an
+      !! ** Method  :   The upstream biased scheme (UBS) is based on a 3rd order
       !!      upstream-biased parabolic interpolation (Shchepetkin and McWilliams 2005)
       !!      It is only used in the horizontal direction.
       !!      For example the i-component of the advective fluxes are given by :
       !!                !  e2u e3u un ( mi(Tn) - zltu(i  ) )   if un(i) >= 0
-      !!          zwx = !  or 
+      !!          ztu = !  or 
       !!                !  e2u e3u un ( mi(Tn) - zltu(i+1) )   if un(i) < 0
       !!      where zltu is the second derivative of the before temperature field:
@@ -76,6 +77,4 @@
       !!             Farrow, D.E., Stevens, D.P., 1995, J. Phys. Ocean. 25, 1731Ð1741. 
       !!----------------------------------------------------------------------
-      USE oce     , ONLY:   zwx  => ua       , zwy  => va         ! (ua,va) used as workspace
-      !
       INTEGER                              , INTENT(in   ) ::   kt              ! ocean time-step index
       INTEGER                              , INTENT(in   ) ::   kit000          ! first time step index
@@ -98,5 +97,4 @@
       CALL wrk_alloc( jpi, jpj, jpk, ztu, ztv, zltu, zltv, zti, ztw )
       !
-
       IF( kt == kit000 )  THEN
          IF(lwp) WRITE(numout,*)
@@ -151,6 +149,6 @@
                   zcenvt = pvn(ji,jj,jk) * ( ptn(ji,jj,jk,jn) + ptn(ji  ,jj+1,jk,jn) )
                   ! UBS advective fluxes
-                  zwx(ji,jj,jk) = 0.5 * ( zcenut - zfp_ui * zltu(ji,jj,jk) - zfm_ui * zltu(ji+1,jj,jk) )
-                  zwy(ji,jj,jk) = 0.5 * ( zcenvt - zfp_vj * zltv(ji,jj,jk) - zfm_vj * zltv(ji,jj+1,jk) )
+                  ztu(ji,jj,jk) = 0.5 * ( zcenut - zfp_ui * zltu(ji,jj,jk) - zfm_ui * zltu(ji+1,jj,jk) )
+                  ztv(ji,jj,jk) = 0.5 * ( zcenvt - zfp_vj * zltv(ji,jj,jk) - zfm_vj * zltv(ji,jj+1,jk) )
                END DO
             END DO
@@ -159,15 +157,10 @@
          zltu(:,:,:) = pta(:,:,:,jn)      ! store pta trends
 
-         ! Horizontal advective trends
-         DO jk = 1, jpkm1
-            !  Tracer flux divergence at t-point added to the general trend
+         DO jk = 1, jpkm1                 ! Horizontal advective trends
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1   ! vector opt.
-                  zbtr = 1. / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
-                  ! horizontal advective
-                  ztra = - zbtr * (  zwx(ji,jj,jk) - zwx(ji-1,jj  ,jk)   &
-                     &             + zwy(ji,jj,jk) - zwy(ji  ,jj-1,jk)  )
-                  ! add it to the general tracer trends
-                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + ztra
+                  pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn)                        &
+                     &             - (  ztu(ji,jj,jk) - ztu(ji-1,jj  ,jk)    &
+                     &                + ztv(ji,jj,jk) - ztv(ji  ,jj-1,jk)  ) / ( e1e2t(ji,jj) * fse3t(ji,jj,jk) )
                END DO
             END DO
@@ -178,15 +171,13 @@
          zltu(:,:,:) = pta(:,:,:,jn) - zltu(:,:,:)
 
-         ! 3. Save the horizontal advective trends for diagnostic
-         ! ------------------------------------------------------
-         !                                 ! trend diagnostics (contribution of upstream fluxes)
-         IF( l_trd ) THEN
-             CALL trd_tra( kt, cdtype, jn, jptra_trd_xad, zwx, pun, ptn(:,:,:,jn) )
-             CALL trd_tra( kt, cdtype, jn, jptra_trd_yad, zwy, pvn, ptn(:,:,:,jn) )
+         !                
+         IF( l_trd ) THEN                  ! trend diagnostics
+             CALL trd_tra( kt, cdtype, jn, jptra_xad, ztu, pun, ptn(:,:,:,jn) )
+             CALL trd_tra( kt, cdtype, jn, jptra_yad, ztv, pvn, ptn(:,:,:,jn) )
          END IF
          !                                 ! "Poleward" heat and salt transports (contribution of upstream fluxes)
          IF( cdtype == 'TRA' .AND. ln_diaptr .AND. ( MOD( kt, nn_fptr ) == 0 ) ) THEN  
-            IF( jn == jp_tem )  htr_adv(:) = ptr_vj( zwy(:,:,:) )
-            IF( jn == jp_sal )  str_adv(:) = ptr_vj( zwy(:,:,:) )
+            IF( jn == jp_tem )  htr_adv(:) = ptr_vj( ztv(:,:,:) )
+            IF( jn == jp_sal )  str_adv(:) = ptr_vj( ztv(:,:,:) )
          ENDIF
          
@@ -265,8 +256,8 @@
                END DO
             END DO
-            CALL trd_tra( kt, cdtype, jn, jptra_trd_zad, zltv )
+            CALL trd_tra( kt, cdtype, jn, jptra_zad, zltv )
          ENDIF
          !
-      ENDDO
+      END DO
       !
       CALL wrk_dealloc( jpi, jpj, jpk, ztu, ztv, zltu, zltv, zti, ztw )
@@ -290,5 +281,4 @@
       !!       in-space based differencing for fluid
       !!----------------------------------------------------------------------
-      !
       REAL(wp), INTENT(in   ), DIMENSION(jpk)          ::   p2dt   ! vertical profile of tracer time-step
       REAL(wp),                DIMENSION (jpi,jpj,jpk) ::   pbef   ! before field
@@ -306,5 +296,4 @@
       CALL wrk_alloc( jpi, jpj, jpk, zbetup, zbetdo )
       !
-
       zbig  = 1.e+40_wp
       zrtrn = 1.e-15_wp
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trabbc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trabbc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trabbc.F90	(revision 5075)
@@ -18,6 +18,6 @@
    USE dom_oce         ! domain: ocean
    USE phycst          ! physical constants
-   USE trdmod_oce      ! trends: ocean variables 
-   USE trdtra          ! trends: active tracers 
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
    USE in_out_manager  ! I/O manager
    USE prtctl          ! Print control
@@ -84,11 +84,6 @@
       !
       !                             !  Add the geothermal heat flux trend on temperature
-#if defined key_vectopt_loop
-      DO jj = 1, 1
-         DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
-#else
       DO jj = 2, jpjm1
          DO ji = 2, jpim1
-#endif
             ik = mbkt(ji,jj)
             zqgh_trd = qgh_trd0(ji,jj) / fse3t(ji,jj,ik)
@@ -99,5 +94,5 @@
       IF( l_trdtra ) THEN        ! Save the geothermal heat flux trend for diagnostics
          ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_bbc, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_bbc, ztrdt )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdt )
       ENDIF
@@ -130,5 +125,5 @@
       INTEGER  ::   inum                ! temporary logical unit
       INTEGER  ::   ios                 ! Local integer output status for namelist read
-      !!
+      !
       NAMELIST/nambbc/ln_trabbc, nn_geoflx, rn_geoflx_cst 
       !!----------------------------------------------------------------------
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trabbl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trabbl.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trabbl.F90	(revision 5075)
@@ -12,4 +12,5 @@
    !!             -   ! 2010-06  (C. Ethe, G. Madec)  merge TRA-TRC
    !!             -   ! 2010-11  (G. Madec) add mbk. arrays associated to the deepest ocean level
+   !!             -   ! 2013-04  (F. Roquet, G. Madec)  use of eosbn2 instead of local hard coded alpha and beta
    !!----------------------------------------------------------------------
 #if   defined key_trabbl   ||   defined key_esopa
@@ -28,7 +29,8 @@
    USE phycst         ! physical constant
    USE eosbn2         ! equation of state
-   USE trdmod_oce     ! trends: ocean variables
+   USE trd_oce     ! trends: ocean variables
    USE trdtra         ! trends: active tracers
-   USE iom            ! IOM server
+   !
+   USE iom            ! IOM library               
    USE in_out_manager ! I/O manager
    USE lbclnk         ! ocean lateral boundary conditions
@@ -36,5 +38,5 @@
    USE wrk_nemo       ! Memory Allocation
    USE timing         ! Timing
-
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
 
    IMPLICIT NONE
@@ -57,5 +59,5 @@
    REAL(wp), PUBLIC ::   rn_gambbl   !: lateral coeff. for bottom boundary layer scheme [s]
 
-   LOGICAL , PUBLIC ::   l_bbl                  !: flag to compute bbl diffu. flux coef and transport
+   LOGICAL , PUBLIC ::   l_bbl       !: flag to compute bbl diffu. flux coef and transport
 
    REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::   utr_bbl  , vtr_bbl   ! u- (v-) transport in the bottom boundary layer
@@ -84,5 +86,5 @@
          &      vtr_bbl  (jpi,jpj) , ahv_bbl  (jpi,jpj) , mbkv_d  (jpi,jpj) , mgrhv(jpi,jpj) ,     &
          &      ahu_bbl_0(jpi,jpj) , ahv_bbl_0(jpi,jpj) ,                                          &
-         &      e3u_bbl_0(jpi,jpj) , e3v_bbl_0(jpi,jpj) , STAT= tra_bbl_alloc                )
+         &      e3u_bbl_0(jpi,jpj) , e3v_bbl_0(jpi,jpj) ,                                      STAT=tra_bbl_alloc )
          !
       IF( lk_mpp            )   CALL mpp_sum ( tra_bbl_alloc )
@@ -104,5 +106,5 @@
       !!----------------------------------------------------------------------
       INTEGER, INTENT( in ) ::   kt   ! ocean time-step
-      !!
+      !
       REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztrdt, ztrds
       !!----------------------------------------------------------------------
@@ -110,5 +112,5 @@
       IF( nn_timing == 1 )  CALL timing_start( 'tra_bbl')
       !
-      IF( l_trdtra )   THEN                        !* Save ta and sa trends
+      IF( l_trdtra )   THEN                         !* Save ta and sa trends
          CALL wrk_alloc( jpi, jpj, jpk, ztrdt, ztrds )
          ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
@@ -116,12 +118,12 @@
       ENDIF
 
-      IF( l_bbl )  CALL bbl( kt, nit000, 'TRA' )   !* bbl coef. and transport (only if not already done in trcbbl)
-
-      IF( nn_bbl_ldf == 1 ) THEN                   !* Diffusive bbl
+      IF( l_bbl )   CALL bbl( kt, nit000, 'TRA' )   !* bbl coef. and transport (only if not already done in trcbbl)
+
+      IF( nn_bbl_ldf == 1 ) THEN                    !* Diffusive bbl
          !
          CALL tra_bbl_dif( tsb, tsa, jpts )
          IF( ln_ctl )  &
          CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' bbl_ldf  - Ta: ', mask1=tmask, &
-         &             tab3d_2=tsa(:,:,:,jp_sal), clinfo2=           ' Sa: ', mask2=tmask, clinfo3='tra' )
+            &          tab3d_2=tsa(:,:,:,jp_sal), clinfo2=           ' Sa: ', mask2=tmask, clinfo3='tra' )
          ! lateral boundary conditions ; just need for outputs
          CALL lbc_lnk( ahu_bbl, 'U', 1. )     ;     CALL lbc_lnk( ahv_bbl, 'V', 1. )
@@ -131,10 +133,10 @@
       END IF
 
-      IF( nn_bbl_adv /= 0 ) THEN                !* Advective bbl
+      IF( nn_bbl_adv /= 0 ) THEN                    !* Advective bbl
          !
          CALL tra_bbl_adv( tsb, tsa, jpts )
          IF(ln_ctl)   &
          CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' bbl_adv  - Ta: ', mask1=tmask,   &
-         &             tab3d_2=tsa(:,:,:,jp_sal), clinfo2=           ' Sa: ', mask2=tmask, clinfo3='tra' )
+            &          tab3d_2=tsa(:,:,:,jp_sal), clinfo2=           ' Sa: ', mask2=tmask, clinfo3='tra' )
          ! lateral boundary conditions ; just need for outputs
          CALL lbc_lnk( utr_bbl, 'U', 1. )     ;   CALL lbc_lnk( vtr_bbl, 'V', 1. )
@@ -147,6 +149,6 @@
          ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
          ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_bbl, ztrdt )
-         CALL trd_tra( kt, 'TRA', jp_sal, jptra_trd_bbl, ztrds )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_bbl, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_bbl, ztrds )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds )
       ENDIF
@@ -164,6 +166,5 @@
       !!                advection terms.
       !!
-      !! ** Method  :
-      !!        * diffusive bbl (nn_bbl_ldf=1) :
+      !! ** Method  : * diffusive bbl only (nn_bbl_ldf=1) :
       !!        When the product grad( rho) * grad(h) < 0 (where grad is an
       !!      along bottom slope gradient) an additional lateral 2nd order
@@ -179,5 +180,4 @@
       !!              Campin, J.-M., and H. Goosse, 1999, Tellus, 412-430.
       !!----------------------------------------------------------------------
-      !
       INTEGER                              , INTENT(in   ) ::   kjpt   ! number of tracers
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptb    ! before and now tracer fields
@@ -196,24 +196,14 @@
       DO jn = 1, kjpt                                     ! tracer loop
          !                                                ! ===========
-#  if defined key_vectopt_loop
-         DO jj = 1, 1   ! vector opt. (forced unrolling)
-            DO ji = 1, jpij
-#else
          DO jj = 1, jpj
             DO ji = 1, jpi
-#endif
-               ik = mbkt(ji,jj)                        ! bottom T-level index
-               zptb(ji,jj) = ptb(ji,jj,ik,jn)              ! bottom before T and S
+               ik = mbkt(ji,jj)                              ! bottom T-level index
+               zptb(ji,jj) = ptb(ji,jj,ik,jn)       ! bottom before T and S
             END DO
          END DO
-         !                                                ! Compute the trend
-#  if defined key_vectopt_loop
-         DO jj = 1, 1   ! vector opt. (forced unrolling)
-            DO ji = jpi+1, jpij-jpi-1
-#  else
-         DO jj = 2, jpjm1
+         !               
+         DO jj = 2, jpjm1                                    ! Compute the trend
             DO ji = 2, jpim1
-#  endif
-               ik = mbkt(ji,jj)                            ! bottom T-level index
+               ik = mbkt(ji,jj)                              ! bottom T-level index
                zbtr = r1_e12t(ji,jj)  / fse3t(ji,jj,ik)
                pta(ji,jj,ik,jn) = pta(ji,jj,ik,jn)                                                         &
@@ -264,11 +254,6 @@
       DO jn = 1, kjpt                                            ! tracer loop
          !                                                       ! ===========
-# if defined key_vectopt_loop
-         DO jj = 1, 1
-            DO ji = 1, jpij-jpi-1   ! vector opt. (forced unrolling)
-# else
          DO jj = 1, jpjm1
             DO ji = 1, jpim1            ! CAUTION start from i=1 to update i=2 when cyclic east-west
-# endif
                IF( utr_bbl(ji,jj) /= 0.e0 ) THEN            ! non-zero i-direction bbl advection
                   ! down-slope i/k-indices (deep)      &   up-slope i/k indices (shelf)
@@ -333,6 +318,5 @@
       !!                advection terms.
       !!
-      !! ** Method  :
-      !!        * diffusive bbl (nn_bbl_ldf=1) :
+      !! ** Method  : * diffusive bbl (nn_bbl_ldf=1) :
       !!        When the product grad( rho) * grad(h) < 0 (where grad is an
       !!      along bottom slope gradient) an additional lateral 2nd order
@@ -342,5 +326,5 @@
       !!      a downslope velocity of 20 cm/s if the condition for slope
       !!      convection is satified)
-      !!        * advective bbl (nn_bbl_adv=1 or 2) :
+      !!              * advective bbl (nn_bbl_adv=1 or 2) :
       !!      nn_bbl_adv = 1   use of the ocean velocity as bbl velocity
       !!      nn_bbl_adv = 2   follow Campin and Goosse (1999) implentation
@@ -353,56 +337,20 @@
       !!              Campin, J.-M., and H. Goosse, 1999, Tellus, 412-430.
       !!----------------------------------------------------------------------
-      !
       INTEGER         , INTENT(in   ) ::   kt       ! ocean time-step index
-      INTEGER         , INTENT(in   ) ::   kit000          ! first time step index
+      INTEGER         , INTENT(in   ) ::   kit000   ! first time step index
       CHARACTER(len=3), INTENT(in   ) ::   cdtype   ! =TRA or TRC (tracer indicator)
       !!
       INTEGER  ::   ji, jj                    ! dummy loop indices
       INTEGER  ::   ik                        ! local integers
-      INTEGER  ::   iis , iid , ijs , ijd     !   -       -
-      INTEGER  ::   ikus, ikud, ikvs, ikvd    !   -       -
-      REAL(wp) ::   zsign, zsigna, zgbbl      ! local scalars
-      REAL(wp) ::   zgdrho, zt, zs, zh        !   -      -
-      !!
-      REAL(wp) ::   fsalbt, fsbeta, pft, pfs, pfh   ! statement function
-      REAL(wp), POINTER, DIMENSION(:,:) :: zub, zvb, ztb, zsb, zdep
-      !!----------------------- zv_bbl-----------------------------------------------
-      ! ratio alpha/beta = fsalbt : ratio of thermal over saline expension coefficients
-      ! ================            pft :  potential temperature in degrees celcius
-      !                             pfs :  salinity anomaly (s-35) in psu
-      !                             pfh :  depth in meters
-      ! nn_eos = 0  (Jackett and McDougall 1994 formulation)
-      fsalbt( pft, pfs, pfh ) =                                              &   ! alpha/beta
-         ( ( ( -0.255019e-07 * pft + 0.298357e-05 ) * pft                    &
-                                   - 0.203814e-03 ) * pft                    &
-                                   + 0.170907e-01 ) * pft                    &
-                                   + 0.665157e-01                            &
-         +(-0.678662e-05 * pfs - 0.846960e-04 * pft + 0.378110e-02 ) * pfs   &
-         +  ( ( - 0.302285e-13 * pfh                                         &
-                - 0.251520e-11 * pfs                                         &
-                + 0.512857e-12 * pft * pft          ) * pfh                  &
-                                     - 0.164759e-06   * pfs                  &
-             +(   0.791325e-08 * pft - 0.933746e-06 ) * pft                  &
-                                     + 0.380374e-04 ) * pfh
-      fsbeta( pft, pfs, pfh ) =                                              &   ! beta
-         ( ( -0.415613e-09 * pft + 0.555579e-07 ) * pft                      &
-                                 - 0.301985e-05 ) * pft                      &
-                                 + 0.785567e-03                              &
-         + (     0.515032e-08 * pfs                                          &
-               + 0.788212e-08 * pft - 0.356603e-06 ) * pfs                   &
-               +(  (   0.121551e-17 * pfh                                    &
-                     - 0.602281e-15 * pfs                                    &
-                     - 0.175379e-14 * pft + 0.176621e-12 ) * pfh             &
-                                          + 0.408195e-10   * pfs             &
-                 + ( - 0.213127e-11 * pft + 0.192867e-09 ) * pft             &
-                                          - 0.121555e-07 ) * pfh
-      !!----------------------------------------------------------------------
-
+      INTEGER  ::   iis, iid, ikus, ikud      !   -       -
+      INTEGER  ::   ijs, ijd, ikvs, ikvd      !   -       -
+      REAL(wp) ::   za, zb, zgdrho            ! local scalars
+      REAL(wp) ::   zsign, zsigna, zgbbl      !   -      -
+      REAL(wp), DIMENSION(jpi,jpj,jpts)   :: zts, zab         ! 3D workspace
+      REAL(wp), DIMENSION(jpi,jpj)        :: zub, zvb, zdep   ! 2D workspace
+      !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start( 'bbl')
       !
-      CALL wrk_alloc( jpi, jpj, zub, zvb, ztb, zsb, zdep )
-      !
-
       IF( kt == kit000 )  THEN
          IF(lwp)  WRITE(numout,*)
@@ -410,50 +358,43 @@
          IF(lwp)  WRITE(numout,*) '~~~~~~~~~~'
       ENDIF
-
-      !                                        !* bottom temperature, salinity, velocity and depth
-#if defined key_vectopt_loop
-      DO jj = 1, 1   ! vector opt. (forced unrolling)
-         DO ji = 1, jpij
-#else
+      !                                        !* bottom variables (T, S, alpha, beta, depth, velocity)
       DO jj = 1, jpj
          DO ji = 1, jpi
-#endif
-            ik = mbkt(ji,jj)                        ! bottom T-level index
-            ztb (ji,jj) = tsb(ji,jj,ik,jp_tem) * tmask(ji,jj,1)      ! bottom before T and S
-            zsb (ji,jj) = tsb(ji,jj,ik,jp_sal) * tmask(ji,jj,1)
-            zdep(ji,jj) = gdept_0(ji,jj,ik)         ! bottom T-level reference depth
+            ik = mbkt(ji,jj)                             ! bottom T-level index
+            zts (ji,jj,jp_tem) = tsb(ji,jj,ik,jp_tem)    ! bottom before T and S
+            zts (ji,jj,jp_sal) = tsb(ji,jj,ik,jp_sal)
             !
-            zub(ji,jj) = un(ji,jj,mbku(ji,jj))      ! bottom velocity
-            zvb(ji,jj) = vn(ji,jj,mbkv(ji,jj))
+            zdep(ji,jj) = fsdept(ji,jj,ik)               ! bottom T-level reference depth
+            zub (ji,jj) = un(ji,jj,mbku(ji,jj))          ! bottom velocity
+            zvb (ji,jj) = vn(ji,jj,mbkv(ji,jj))
          END DO
       END DO
-
+      !
+      CALL eos_rab( zts, zdep, zab )
+      !
       !                                   !-------------------!
       IF( nn_bbl_ldf == 1 ) THEN          !   diffusive bbl   !
          !                                !-------------------!
          DO jj = 1, jpjm1                      ! (criteria for non zero flux: grad(rho).grad(h) < 0 )
-            DO ji = 1, jpim1
-               !                                                ! i-direction
-               zt = 0.5 * ( ztb (ji,jj) + ztb (ji+1,jj) )  ! T, S anomalie, and depth
-               zs = 0.5 * ( zsb (ji,jj) + zsb (ji+1,jj) ) - 35.0
-               zh = 0.5 * ( zdep(ji,jj) + zdep(ji+1,jj) )
-               !                                                         ! masked bbl i-gradient of density
-               zgdrho = (  fsalbt( zt, zs, zh ) * ( ztb(ji+1,jj) - ztb(ji,jj) )    &
-                  &                             - ( zsb(ji+1,jj) - zsb(ji,jj) )  ) * umask(ji,jj,1)
+            DO ji = 1, fs_jpim1   ! vector opt.
+               !                                                   ! i-direction
+               za = zab(ji+1,jj,jp_tem) + zab(ji,jj,jp_tem)              ! 2*(alpha,beta) at u-point
+               zb = zab(ji+1,jj,jp_sal) + zab(ji,jj,jp_sal)
+               !                                                         ! 2*masked bottom density gradient
+               zgdrho = (  za * ( zts(ji+1,jj,jp_tem) - zts(ji,jj,jp_tem) )    &
+                  &      - zb * ( zts(ji+1,jj,jp_sal) - zts(ji,jj,jp_sal) )  ) * umask(ji,jj,1)
                !
-               zsign          = SIGN(  0.5, - zgdrho * REAL( mgrhu(ji,jj) )  )    ! sign of ( i-gradient * i-slope )
-               ahu_bbl(ji,jj) = ( 0.5 - zsign ) * ahu_bbl_0(ji,jj)                  ! masked diffusive flux coeff.
+               zsign  = SIGN(  0.5, -zgdrho * REAL( mgrhu(ji,jj) )  )    ! sign of ( i-gradient * i-slope )
+               ahu_bbl(ji,jj) = ( 0.5 - zsign ) * ahu_bbl_0(ji,jj)       ! masked diffusive flux coeff.
                !
-               !                                                ! j-direction
-               zt = 0.5 * ( ztb (ji,jj+1) + ztb (ji,jj) )                ! T, S anomalie, and depth
-               zs = 0.5 * ( zsb (ji,jj+1) + zsb (ji,jj) ) - 35.0
-               zh = 0.5 * ( zdep(ji,jj+1) + zdep(ji,jj) )
-               !                                                         ! masked bbl j-gradient of density
-               zgdrho = (  fsalbt( zt, zs, zh ) * ( ztb(ji,jj+1) - ztb(ji,jj) )    &
-                  &                             - ( zsb(ji,jj+1) - zsb(ji,jj) )  ) * vmask(ji,jj,1)
+               !                                                   ! j-direction
+               za = zab(ji,jj+1,jp_tem) + zab(ji,jj,jp_tem)              ! 2*(alpha,beta) at v-point
+               zb = zab(ji,jj+1,jp_sal) + zab(ji,jj,jp_sal)
+               !                                                         ! 2*masked bottom density gradient
+               zgdrho = (  za * ( zts(ji,jj+1,jp_tem) - zts(ji,jj,jp_tem) )    &
+                  &      - zb * ( zts(ji,jj+1,jp_sal) - zts(ji,jj,jp_sal) )  ) * vmask(ji,jj,1)
                !
-               zsign          = SIGN(  0.5, -zgdrho * REAL( mgrhv(ji,jj) )  )     ! sign of ( j-gradient * j-slope )
+               zsign = SIGN(  0.5, -zgdrho * REAL( mgrhv(ji,jj) )  )     ! sign of ( j-gradient * j-slope )
                ahv_bbl(ji,jj) = ( 0.5 - zsign ) * ahv_bbl_0(ji,jj)
-               !
             END DO
          END DO
@@ -469,29 +410,27 @@
             DO jj = 1, jpjm1                                 ! criteria: grad(rho).grad(h)<0  and grad(rho).grad(h)<0
                DO ji = 1, fs_jpim1   ! vector opt.
-                  !                                               ! i-direction
-                  zt = 0.5 * ( ztb (ji,jj) + ztb (ji+1,jj) )                  ! T, S anomalie, and depth
-                  zs = 0.5 * ( zsb (ji,jj) + zsb (ji+1,jj) ) - 35.0
-                  zh = 0.5 * ( zdep(ji,jj) + zdep(ji+1,jj) )
-                  !                                                           ! masked bbl i-gradient of density
-                  zgdrho = (  fsalbt( zt, zs, zh ) * ( ztb(ji+1,jj) - ztb(ji,jj) )    &
-                     &                             - ( zsb(ji+1,jj) - zsb(ji,jj) )  ) * umask(ji,jj,1)
-                  !
-                  zsign = SIGN(  0.5, - zgdrho   * REAL( mgrhu(ji,jj) )  )    ! sign of i-gradient * i-slope
-                  zsigna= SIGN(  0.5, zub(ji,jj) * REAL( mgrhu(ji,jj) )  )    ! sign of u * i-slope
-                  !
-                  !                                                           ! bbl velocity
+                  !                                                  ! i-direction
+                  za = zab(ji+1,jj,jp_tem) + zab(ji,jj,jp_tem)               ! 2*(alpha,beta) at u-point
+                  zb = zab(ji+1,jj,jp_sal) + zab(ji,jj,jp_sal)
+                  !                                                          ! 2*masked bottom density gradient 
+                  zgdrho = (  za * ( zts(ji+1,jj,jp_tem) - zts(ji,jj,jp_tem) )    &
+                            - zb * ( zts(ji+1,jj,jp_sal) - zts(ji,jj,jp_sal) )  ) * umask(ji,jj,1)
+                  !
+                  zsign = SIGN(  0.5, - zgdrho   * REAL( mgrhu(ji,jj) )  )   ! sign of i-gradient * i-slope
+                  zsigna= SIGN(  0.5, zub(ji,jj) * REAL( mgrhu(ji,jj) )  )   ! sign of u * i-slope
+                  !
+                  !                                                          ! bbl velocity
                   utr_bbl(ji,jj) = ( 0.5 + zsigna ) * ( 0.5 - zsign ) * e2u(ji,jj) * e3u_bbl_0(ji,jj) * zub(ji,jj)
                   !
-                  !                                               ! j-direction
-                  zt = 0.5 * ( ztb (ji,jj+1) + ztb (ji,jj) )                  ! T, S anomalie, and depth
-                  zs = 0.5 * ( zsb (ji,jj+1) + zsb (ji,jj) ) - 35.0
-                  zh = 0.5 * ( zdep(ji,jj+1) + zdep(ji,jj) )
-                  !                                                           ! masked bbl j-gradient of density
-                  zgdrho = (  fsalbt( zt, zs, zh ) * ( ztb(ji,jj+1) - ztb(ji,jj) )    &
-                     &                             - ( zsb(ji,jj+1) - zsb(ji,jj) )  ) * vmask(ji,jj,1)
-                  zsign = SIGN(  0.5, - zgdrho   * REAL( mgrhv(ji,jj) )  )    ! sign of j-gradient * j-slope
-                  zsigna= SIGN(  0.5, zvb(ji,jj) * REAL( mgrhv(ji,jj) )  )    ! sign of u * i-slope
-                  !
-                  !                                                           ! bbl velocity
+                  !                                                  ! j-direction
+                  za = zab(ji,jj+1,jp_tem) + zab(ji,jj,jp_tem)               ! 2*(alpha,beta) at v-point
+                  zb = zab(ji,jj+1,jp_sal) + zab(ji,jj,jp_sal)
+                  !                                                          ! 2*masked bottom density gradient
+                  zgdrho = (  za * ( zts(ji,jj+1,jp_tem) - zts(ji,jj,jp_tem) )    &
+                     &      - zb * ( zts(ji,jj+1,jp_sal) - zts(ji,jj,jp_sal) )  ) * vmask(ji,jj,1)
+                  zsign = SIGN(  0.5, - zgdrho   * REAL( mgrhv(ji,jj) )  )   ! sign of j-gradient * j-slope
+                  zsigna= SIGN(  0.5, zvb(ji,jj) * REAL( mgrhv(ji,jj) )  )   ! sign of u * i-slope
+                  !
+                  !                                                          ! bbl transport
                   vtr_bbl(ji,jj) = ( 0.5 + zsigna ) * ( 0.5 - zsign ) * e1v(ji,jj) * e3v_bbl_0(ji,jj) * zvb(ji,jj)
                END DO
@@ -502,36 +441,38 @@
             DO jj = 1, jpjm1                            ! criteria: rho_up > rho_down
                DO ji = 1, fs_jpim1   ! vector opt.
-                  !                                         ! i-direction
+                  !                                                  ! i-direction
                   ! down-slope T-point i/k-index (deep)  &   up-slope T-point i/k-index (shelf)
-                  iid  = ji + MAX( 0, mgrhu(ji,jj) )     ;    iis  = ji + 1 - MAX( 0, mgrhu(ji,jj) )
-                  ikud = mbku_d(ji,jj)                   ;    ikus = mbku(ji,jj)
-                  !
-                  !                                             ! mid-depth density anomalie (up-slope minus down-slope)
-                  zt = 0.5 * ( ztb (ji,jj) + ztb (ji+1,jj) )           ! mid slope depth of T, S, and depth
-                  zs = 0.5 * ( zsb (ji,jj) + zsb (ji+1,jj) ) - 35.0
-                  zh = 0.5 * ( zdep(ji,jj) + zdep(ji+1,jj) )
-                  zgdrho =    fsbeta( zt, zs, zh )                                    &
-                     &   * (  fsalbt( zt, zs, zh ) * ( ztb(iid,jj) - ztb(iis,jj) )    &
-                     &                             - ( zsb(iid,jj) - zsb(iis,jj) )  ) * umask(ji,jj,1)
-                  zgdrho = MAX( 0.e0, zgdrho )                         ! only if shelf is denser than deep
-                  !
-                  !                                             ! bbl transport (down-slope direction)
+                  iid  = ji + MAX( 0, mgrhu(ji,jj) )
+                  iis  = ji + 1 - MAX( 0, mgrhu(ji,jj) )
+                  !
+                  ikud = mbku_d(ji,jj)
+                  ikus = mbku(ji,jj)
+                  !
+                  za = zab(ji+1,jj,jp_tem) + zab(ji,jj,jp_tem)               ! 2*(alpha,beta) at u-point
+                  zb = zab(ji+1,jj,jp_sal) + zab(ji,jj,jp_sal)
+                  !                                                          !   masked bottom density gradient
+                  zgdrho = 0.5 * (  za * ( zts(iid,jj,jp_tem) - zts(iis,jj,jp_tem) )    &
+                     &            - zb * ( zts(iid,jj,jp_sal) - zts(iis,jj,jp_sal) )  ) * umask(ji,jj,1)
+                  zgdrho = MAX( 0.e0, zgdrho )                               ! only if shelf is denser than deep
+                  !
+                  !                                                          ! bbl transport (down-slope direction)
                   utr_bbl(ji,jj) = e2u(ji,jj) * e3u_bbl_0(ji,jj) * zgbbl * zgdrho * REAL( mgrhu(ji,jj) )
                   !
-                  !                                         ! j-direction
+                  !                                                  ! j-direction
                   !  down-slope T-point j/k-index (deep)  &   of the up  -slope T-point j/k-index (shelf)
-                  ijd  = jj + MAX( 0, mgrhv(ji,jj) )      ;    ijs  = jj + 1 - MAX( 0, mgrhv(ji,jj) )
-                  ikvd = mbkv_d(ji,jj)                    ;    ikvs = mbkv(ji,jj)
-                  !
-                  !                                             ! mid-depth density anomalie (up-slope minus down-slope)
-                  zt = 0.5 * ( ztb (ji,jj) + ztb (ji,jj+1) )           ! mid slope depth of T, S, and depth
-                  zs = 0.5 * ( zsb (ji,jj) + zsb (ji,jj+1) ) - 35.0
-                  zh = 0.5 * ( zdep(ji,jj) + zdep(ji,jj+1) )
-                  zgdrho =    fsbeta( zt, zs, zh )                                    &
-                     &   * (  fsalbt( zt, zs, zh ) * ( ztb(ji,ijd) - ztb(ji,ijs) )    &
-                     &                             - ( zsb(ji,ijd) - zsb(ji,ijs) )  ) * vmask(ji,jj,1)
-                  zgdrho = MAX( 0.e0, zgdrho )                         ! only if shelf is denser than deep
-                  !
-                  !                                             ! bbl transport (down-slope direction)
+                  ijd  = jj + MAX( 0, mgrhv(ji,jj) )
+                  ijs  = jj + 1 - MAX( 0, mgrhv(ji,jj) )
+                  !
+                  ikvd = mbkv_d(ji,jj)
+                  ikvs = mbkv(ji,jj)
+                  !
+                  za = zab(ji,jj+1,jp_tem) + zab(ji,jj,jp_tem)               ! 2*(alpha,beta) at v-point
+                  zb = zab(ji,jj+1,jp_sal) + zab(ji,jj,jp_sal)
+                  !                                                          !   masked bottom density gradient
+                  zgdrho = 0.5 * (  za * ( zts(ji,ijd,jp_tem) - zts(ji,ijs,jp_tem) )    &
+                     &            - zb * ( zts(ji,ijd,jp_sal) - zts(ji,ijs,jp_sal) )  ) * vmask(ji,jj,1)
+                  zgdrho = MAX( 0.e0, zgdrho )                               ! only if shelf is denser than deep
+                  !
+                  !                                                          ! bbl transport (down-slope direction)
                   vtr_bbl(ji,jj) = e1v(ji,jj) * e3v_bbl_0(ji,jj) * zgbbl * zgdrho * REAL( mgrhv(ji,jj) )
                END DO
@@ -541,6 +482,4 @@
       ENDIF
       !
-      CALL wrk_dealloc( jpi, jpj, zub, zvb, ztb, zsb, zdep )
-      !
       IF( nn_timing == 1 )  CALL timing_stop( 'bbl')
       !
@@ -558,6 +497,6 @@
       !!----------------------------------------------------------------------
       INTEGER ::   ji, jj               ! dummy loop indices
-      INTEGER ::   ii0, ii1, ij0, ij1   ! temporary integer
-      INTEGER  ::   ios                 ! Local integer output status for namelist read
+      INTEGER ::   ii0, ii1, ij0, ij1   ! local integer
+      INTEGER ::   ios                  !   -      -
       REAL(wp), POINTER, DIMENSION(:,:) :: zmbk
       !!
@@ -598,6 +537,4 @@
       IF( nn_bbl_adv == 2 )    WRITE(numout,*) '       * Advective BBL using velocity = F( delta rho)'
 
-      IF( nn_eos /= 0 )   CALL ctl_stop ( ' bbl parameterisation requires eos = 0. We stop.' )
-
       !                             !* vertical index of  "deep" bottom u- and v-points
       DO jj = 1, jpjm1                    ! (the "shelf" bottom k-indices are mbku and mbkv)
@@ -607,10 +544,10 @@
          END DO
       END DO
-      ! convert into REAL to use lbc_lnk ; impose a min value of 1 as a zero can be set in lbclnk
+      ! converte into REAL to use lbc_lnk ; impose a min value of 1 as a zero can be set in lbclnk
       zmbk(:,:) = REAL( mbku_d(:,:), wp )   ;   CALL lbc_lnk(zmbk,'U',1.)   ;   mbku_d(:,:) = MAX( INT( zmbk(:,:) ), 1 )
       zmbk(:,:) = REAL( mbkv_d(:,:), wp )   ;   CALL lbc_lnk(zmbk,'V',1.)   ;   mbkv_d(:,:) = MAX( INT( zmbk(:,:) ), 1 )
 
-                                     !* sign of grad(H) at u- and v-points
-      mgrhu(jpi,:) = 0.    ;    mgrhu(:,jpj) = 0.   ;    mgrhv(jpi,:) = 0.    ;    mgrhv(:,jpj) = 0.
+                                        !* sign of grad(H) at u- and v-points
+      mgrhu(jpi,:) = 0   ;   mgrhu(:,jpj) = 0   ;   mgrhv(jpi,:) = 0   ;   mgrhv(:,jpj) = 0
       DO jj = 1, jpjm1
          DO ji = 1, jpim1
@@ -621,5 +558,5 @@
 
       DO jj = 1, jpjm1              !* bbl thickness at u- (v-) point
-         DO ji = 1, jpim1           ! minimum of top & bottom e3u_0 (e3v_0)
+         DO ji = 1, jpim1                 ! minimum of top & bottom e3u_0 (e3v_0)
             e3u_bbl_0(ji,jj) = MIN( e3u_0(ji,jj,mbkt(ji+1,jj  )), e3u_0(ji,jj,mbkt(ji,jj)) )
             e3v_bbl_0(ji,jj) = MIN( e3v_0(ji,jj,mbkt(ji  ,jj+1)), e3v_0(ji,jj,mbkt(ji,jj)) )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tradmp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tradmp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tradmp.F90	(revision 5075)
@@ -28,6 +28,6 @@
    USE dom_oce        ! ocean: domain variables
    USE c1d            ! 1D vertical configuration
-   USE trdmod_oce     ! ocean: trend variables
-   USE trdtra         ! active tracers: trends
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers 
    USE zdf_oce        ! ocean: vertical physics
    USE phycst         ! physical constants
@@ -48,4 +48,6 @@
    PUBLIC   dtacof_zoom  ! routine called by tradmp.F90, trcdmp.F90 and dyndmp.F90
 
+!!gm  why all namelist variable public????   only ln_tradmp should be sufficient
+
    !                               !!* Namelist namtra_dmp : T & S newtonian damping *
    LOGICAL , PUBLIC ::   ln_tradmp   !: internal damping flag
@@ -112,4 +114,5 @@
       !
       CALL wrk_alloc( jpi, jpj, jpk, jpts,  zts_dta )
+      !
       !                           !==   input T-S data at kt   ==!
       CALL dta_tsd( kt, zts_dta )            ! read and interpolates T-S data at kt
@@ -172,6 +175,6 @@
       !
       IF( l_trdtra )   THEN       ! trend diagnostic
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_dmp, ttrdmp )
-         CALL trd_tra( kt, 'TRA', jp_sal, jptra_trd_dmp, strdmp )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_dmp, ttrdmp )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_dmp, strdmp )
       ENDIF
       !                           ! Control print
@@ -194,12 +197,13 @@
       !! ** Method  :   read the namtra_dmp namelist and check the parameters
       !!----------------------------------------------------------------------
+      INTEGER  ::   ios   ! Local integer output status for namelist read
+      !!
       NAMELIST/namtra_dmp/ ln_tradmp, nn_hdmp, nn_zdmp, rn_surf, rn_bot, rn_dep, nn_file
-      INTEGER  ::   ios                 ! Local integer output status for namelist read
-      !!----------------------------------------------------------------------
-
+      !!----------------------------------------------------------------------
+      !
       REWIND( numnam_ref )              ! Namelist namtra_dmp in reference namelist : Temperature and salinity damping term
       READ  ( numnam_ref, namtra_dmp, IOSTAT = ios, ERR = 901)
 901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namtra_dmp in reference namelist', lwp )
-
+      !
       REWIND( numnam_cfg )              ! Namelist namtra_dmp in configuration namelist : Temperature and salinity damping term
       READ  ( numnam_cfg, namtra_dmp, IOSTAT = ios, ERR = 902 )
@@ -228,4 +232,7 @@
          IF( tra_dmp_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'tra_dmp_init: unable to allocate arrays' )
          !
+!!gm  I don't understand the specificities of c1d case......   
+!!gm  to be check with the autor of these lines
+         
 #if ! defined key_c1d
          SELECT CASE ( nn_hdmp )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf.F90	(revision 5075)
@@ -23,6 +23,7 @@
    USE traldf_iso_grif ! lateral mixing          (tra_ldf_iso_grif routine)
    USE traldf_lap      ! lateral mixing               (tra_ldf_lap routine)
-   USE trdmod_oce      ! ocean space and time domain
-   USE trdtra          ! ocean active tracers trends
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
+   !
    USE prtctl          ! Print control
    USE in_out_manager  ! I/O manager
@@ -35,6 +36,6 @@
    PRIVATE
 
-   PUBLIC   tra_ldf         ! called by step.F90 
-   PUBLIC   tra_ldf_init    ! called by opa.F90 
+   PUBLIC   tra_ldf        ! called by step.F90 
+   PUBLIC   tra_ldf_init   ! called by opa.F90 
    !
    INTEGER ::   nldf = 0   ! type of lateral diffusion used defined from ln_traldf_... namlist logicals)
@@ -75,16 +76,20 @@
 
       SELECT CASE ( nldf )                       ! compute lateral mixing trend and add it to the general trend
-      CASE ( 0 )   ;   CALL tra_ldf_lap     ( kt, nit000, 'TRA', gtsu, gtsv, tsb, tsa, jpts        )  ! iso-level laplacian
+      CASE ( 0 )   ;   CALL tra_ldf_lap     ( kt, nit000, 'TRA', gtsu, gtsv, gtui, gtvi,        &
+                               &                                   tsb, tsa, jpts        )  ! iso-level laplacian
       CASE ( 1 )                                                                              ! rotated laplacian
          IF( ln_traldf_grif ) THEN                                                          
                        CALL tra_ldf_iso_grif( kt, nit000,'TRA', gtsu, gtsv, tsb, tsa, jpts, ahtb0 )      ! Griffies operator
          ELSE                                                                                
-                       CALL tra_ldf_iso     ( kt, nit000, 'TRA', gtsu, gtsv, tsb, tsa, jpts, ahtb0 )      ! Madec operator
-         ENDIF
-      CASE ( 2 )   ;   CALL tra_ldf_bilap   ( kt, nit000, 'TRA', gtsu, gtsv, tsb, tsa, jpts        )  ! iso-level bilaplacian
+                       CALL tra_ldf_iso     ( kt, nit000, 'TRA', gtsu, gtsv, gtui, gtvi,        &
+                               &                                  tsb, tsa, jpts, ahtb0 )      ! Madec operator
+         ENDIF
+      CASE ( 2 )   ;   CALL tra_ldf_bilap   ( kt, nit000, 'TRA', gtsu, gtsv, gtui, gtvi,        &
+                               &                                   tsb, tsa, jpts        )  ! iso-level bilaplacian
       CASE ( 3 )   ;   CALL tra_ldf_bilapg  ( kt, nit000, 'TRA',             tsb, tsa, jpts        )  ! s-coord. geopot. bilap.
          !
       CASE ( -1 )                                ! esopa: test all possibility with control print
-         CALL tra_ldf_lap   ( kt, nit000, 'TRA', gtsu, gtsv, tsb, tsa, jpts        ) 
+         CALL tra_ldf_lap   ( kt, nit000, 'TRA', gtsu, gtsv, gtui, gtvi,        &
+         &                                       tsb, tsa, jpts        ) 
          CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' ldf0 - Ta: ', mask1=tmask,               &
          &             tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
@@ -92,9 +97,11 @@
             CALL tra_ldf_iso_grif( kt, nit000, 'TRA', gtsu, gtsv, tsb, tsa, jpts, ahtb0 )
          ELSE
-            CALL tra_ldf_iso     ( kt, nit000, 'TRA', gtsu, gtsv, tsb, tsa, jpts, ahtb0 )  
+            CALL tra_ldf_iso     ( kt, nit000, 'TRA', gtsu, gtsv, gtui, gtvi,        &
+            &                                               tsb, tsa, jpts, ahtb0 )  
          ENDIF
          CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' ldf1 - Ta: ', mask1=tmask,               &
          &             tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
-         CALL tra_ldf_bilap ( kt, nit000, 'TRA', gtsu, gtsv, tsb, tsa, jpts        ) 
+         CALL tra_ldf_bilap ( kt, nit000, 'TRA', gtsu, gtsv, gtui, gtvi,        &
+         &                                       tsb, tsa, jpts        ) 
          CALL prt_ctl( tab3d_1=tsa(:,:,:,jp_tem), clinfo1=' ldf2 - Ta: ', mask1=tmask,               &
          &             tab3d_2=tsa(:,:,:,jp_sal), clinfo2=       ' Sa: ', mask2=tmask, clinfo3='tra' )
@@ -112,6 +119,6 @@
          ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
          ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_ldf, ztrdt )
-         CALL trd_tra( kt, 'TRA', jp_sal, jptra_trd_ldf, ztrds )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_ldf, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_ldf, ztrds )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds ) 
       ENDIF
@@ -174,10 +181,10 @@
             IF ( ln_traldf_iso   )   nldf = 1      ! isoneutral (   rotation)
          ENDIF
-         IF ( ln_zps ) THEN             ! z-coordinate
+         IF ( ln_zps ) THEN             ! zps-coordinate
             IF ( ln_traldf_level )   ierr = 1      ! iso-level not allowed
             IF ( ln_traldf_hor   )   nldf = 0      ! horizontal (no rotation)
             IF ( ln_traldf_iso   )   nldf = 1      ! isoneutral (   rotation)
          ENDIF
-         IF ( ln_sco ) THEN             ! z-coordinate
+         IF ( ln_sco ) THEN             ! s-coordinate
             IF ( ln_traldf_level )   nldf = 0      ! iso-level  (no rotation)
             IF ( ln_traldf_hor   )   nldf = 1      ! horizontal (   rotation)
@@ -192,10 +199,10 @@
             IF ( ln_traldf_iso   )   ierr = 2      ! isoneutral (   rotation)
          ENDIF
-         IF ( ln_zps ) THEN             ! z-coordinate
+         IF ( ln_zps ) THEN             ! zps-coordinate
             IF ( ln_traldf_level )   ierr = 1      ! iso-level not allowed 
             IF ( ln_traldf_hor   )   nldf = 2      ! horizontal (no rotation)
             IF ( ln_traldf_iso   )   ierr = 2      ! isoneutral (   rotation)
          ENDIF
-         IF ( ln_sco ) THEN             ! z-coordinate
+         IF ( ln_sco ) THEN             ! s-coordinate
             IF ( ln_traldf_level )   nldf = 2      ! iso-level  (no rotation)
             IF ( ln_traldf_hor   )   nldf = 3      ! horizontal (   rotation)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilap.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilap.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_bilap.F90	(revision 5075)
@@ -49,5 +49,6 @@
 CONTAINS
  
-   SUBROUTINE tra_ldf_bilap( kt, kit000, cdtype, pgu, pgv,      &
+   SUBROUTINE tra_ldf_bilap( kt, kit000, cdtype, pgu, pgv,            &
+      &                                          pgui, pgvi,          &
       &                                  ptb, pta, kjpt )  
       !!----------------------------------------------------------------------
@@ -82,5 +83,6 @@
       CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
       INTEGER                              , INTENT(in   ) ::   kjpt       ! number of tracers
-      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(in   ) ::   pgu , pgv  ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(in   ) ::   pgui, pgvi ! tracer gradient at pstep levels
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptb        ! before and now tracer fields
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta        ! tracer trend 
@@ -128,4 +130,7 @@
                      IF( mbku(ji,jj) == jk )  ztu(ji,jj,jk) = zeeu(ji,jj) * pgu(ji,jj,jn)
                      IF( mbkv(ji,jj) == jk )  ztv(ji,jj,jk) = zeev(ji,jj) * pgv(ji,jj,jn)
+                     ! (ISH)
+                     IF( miku(ji,jj) == jk )  ztu(ji,jj,jk) = zeeu(ji,jj) * pgui(ji,jj,jn)
+                     IF( mikv(ji,jj) == jk )  ztu(ji,jj,jk) = zeev(ji,jj) * pgvi(ji,jj,jn)
                   END DO
                END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso.F90	(revision 5075)
@@ -52,4 +52,5 @@
 
    SUBROUTINE tra_ldf_iso( kt, kit000, cdtype, pgu, pgv,              &
+      &                                pgui, pgvi,                    &
       &                                ptb, pta, kjpt, pahtb0 )
       !!----------------------------------------------------------------------
@@ -98,5 +99,6 @@
       CHARACTER(len=3)                     , INTENT(in   ) ::   cdtype     ! =TRA or TRC (tracer indicator)
       INTEGER                              , INTENT(in   ) ::   kjpt       ! number of tracers
-      REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::   pgu , pgv    ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::   pgui, pgvi   ! tracer gradient at pstep levels
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptb        ! before and now tracer fields
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta        ! tracer trend 
@@ -110,12 +112,12 @@
       REAL(wp)                         ::   zztmp               ! local scalar
 #endif
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::  zdkt, zdk1t, z2d
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::  zdit, zdjt, ztfw 
+      REAL(wp), POINTER, DIMENSION(:,:  ) ::  z2d
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::  zdkt, zdk1t, zdit, zdjt, ztfw 
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_ldf_iso')
       !
-      CALL wrk_alloc( jpi, jpj,      zdkt, zdk1t, z2d ) 
-      CALL wrk_alloc( jpi, jpj, jpk, zdit, zdjt, ztfw  ) 
+      CALL wrk_alloc( jpi, jpj,      z2d ) 
+      CALL wrk_alloc( jpi, jpj, jpk, zdit, zdjt, ztfw, zdkt, zdk1t ) 
       !
 
@@ -150,6 +152,10 @@
             DO jj = 1, jpjm1
                DO ji = 1, fs_jpim1   ! vector opt.
-                  zdit(ji,jj,mbku(ji,jj)) = pgu(ji,jj,jn)          
-                  zdjt(ji,jj,mbkv(ji,jj)) = pgv(ji,jj,jn)      
+! IF useless if zpshde defines pgu everywhere
+                  IF (mbku(ji,jj) > 1) zdit(ji,jj,mbku(ji,jj)) = pgu(ji,jj,jn)          
+                  IF (mbkv(ji,jj) > 1) zdjt(ji,jj,mbkv(ji,jj)) = pgv(ji,jj,jn)
+                  ! (ISF)
+                  IF (miku(ji,jj) > 1) zdit(ji,jj,miku(ji,jj)) = pgui(ji,jj,jn)          
+                  IF (mikv(ji,jj) > 1) zdjt(ji,jj,mikv(ji,jj)) = pgvi(ji,jj,jn)     
                END DO
             END DO
@@ -161,19 +167,25 @@
 !CDIR PARALLEL DO PRIVATE( zdk1t ) 
          !                                                ! ===============
-         DO jk = 1, jpkm1                                 ! Horizontal slab
+         DO jj = 1, jpj                                 ! Horizontal slab
             !                                             ! ===============
-            ! 1. Vertical tracer gradient at level jk and jk+1
-            ! ------------------------------------------------
-            ! surface boundary condition: zdkt(jk=1)=zdkt(jk=2)
-            zdk1t(:,:) = ( ptb(:,:,jk,jn) - ptb(:,:,jk+1,jn) ) * tmask(:,:,jk+1)
-            !
-            IF( jk == 1 ) THEN   ;   zdkt(:,:) = zdk1t(:,:)
-            ELSE                 ;   zdkt(:,:) = ( ptb(:,:,jk-1,jn) - ptb(:,:,jk,jn) ) * tmask(:,:,jk)
-            ENDIF
+            DO ji = 1, jpi   ! vector opt.
+               DO jk = mikt(ji,jj), jpkm1
+               ! 1. Vertical tracer gradient at level jk and jk+1
+               ! ------------------------------------------------
+               ! surface boundary condition: zdkt(jk=1)=zdkt(jk=2)
+                  zdk1t(ji,jj,jk) = ( ptb(ji,jj,jk,jn) - ptb(ji,jj,jk+1,jn) ) * tmask(ji,jj,jk+1)
+               !
+                  IF( jk == mikt(ji,jj) ) THEN  ;   zdkt(ji,jj,jk) = zdk1t(ji,jj,jk)
+                  ELSE                          ;   zdkt(ji,jj,jk) = ( ptb(ji,jj,jk-1,jn) - ptb(ji,jj,jk,jn) ) * tmask(ji,jj,jk)
+                  ENDIF
+               END DO
+            END DO
+         END DO
 
             ! 2. Horizontal fluxes
             ! --------------------   
-            DO jj = 1 , jpjm1
-               DO ji = 1, fs_jpim1   ! vector opt.
+         DO jj = 1 , jpjm1
+            DO ji = 1, fs_jpim1   ! vector opt.
+               DO jk = mikt(ji,jj), jpkm1
                   zabe1 = ( fsahtu(ji,jj,jk) + pahtb0 ) * re2u_e1u(ji,jj) * fse3u_n(ji,jj,jk)
                   zabe2 = ( fsahtv(ji,jj,jk) + pahtb0 ) * re1v_e2v(ji,jj) * fse3v_n(ji,jj,jk)
@@ -189,17 +201,19 @@
                   !
                   zftu(ji,jj,jk ) = (  zabe1 * zdit(ji,jj,jk)   &
-                     &              + zcof1 * (  zdkt (ji+1,jj) + zdk1t(ji,jj)      &
-                     &                         + zdk1t(ji+1,jj) + zdkt (ji,jj)  )  ) * umask(ji,jj,jk)
+                     &              + zcof1 * (  zdkt (ji+1,jj,jk) + zdk1t(ji,jj,jk)      &
+                     &                         + zdk1t(ji+1,jj,jk) + zdkt (ji,jj,jk)  )  ) * umask(ji,jj,jk)
                   zftv(ji,jj,jk) = (  zabe2 * zdjt(ji,jj,jk)   &
-                     &              + zcof2 * (  zdkt (ji,jj+1) + zdk1t(ji,jj)      &
-                     &                         + zdk1t(ji,jj+1) + zdkt (ji,jj)  )  ) * vmask(ji,jj,jk)                  
-               END DO
-            END DO
+                     &              + zcof2 * (  zdkt (ji,jj+1,jk) + zdk1t(ji,jj,jk)      &
+                     &                         + zdk1t(ji,jj+1,jk) + zdkt (ji,jj,jk)  )  ) * vmask(ji,jj,jk)                  
+               END DO
+            END DO
+         END DO
 
             ! II.4 Second derivative (divergence) and add to the general trend
             ! ----------------------------------------------------------------
-            DO jj = 2 , jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
-                  zbtr = 1.0 / ( e12t(ji,jj) * fse3t_n(ji,jj,jk) )
+         DO jj = 2 , jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               DO jk = mikt(ji,jj), jpkm1
+                  zbtr = 1.0 / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
                   ztra = zbtr * ( zftu(ji,jj,jk) - zftu(ji-1,jj,jk) + zftv(ji,jj,jk) - zftv(ji,jj-1,jk)  )
                   pta(ji,jj,jk,jn) = pta(ji,jj,jk,jn) + ztra
@@ -264,5 +278,5 @@
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1   ! vector opt.
-                  zcoef0 = - fsahtw(ji,jj,jk) * tmask(ji,jj,jk)
+                  zcoef0 = - fsahtw(ji,jj,jk) * tmask(ji,jj,jk) * tmask(ji,jj,jk-1)
                   !
                   zmsku = 1./MAX(   umask(ji  ,jj,jk-1) + umask(ji-1,jj,jk)      &
@@ -297,6 +311,6 @@
       END DO
       !
-      CALL wrk_dealloc( jpi, jpj,      zdkt, zdk1t, z2d ) 
-      CALL wrk_dealloc( jpi, jpj, jpk, zdit, zdjt, ztfw  ) 
+      CALL wrk_dealloc( jpi, jpj, z2d ) 
+      CALL wrk_dealloc( jpi, jpj, jpk, zdit, zdjt, ztfw, zdkt, zdk1t ) 
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_ldf_iso')
@@ -309,8 +323,8 @@
    !!----------------------------------------------------------------------
 CONTAINS
-   SUBROUTINE tra_ldf_iso( kt, kit000,cdtype, pgu, pgv, ptb, pta, kjpt, pahtb0 )      ! Empty routine
+   SUBROUTINE tra_ldf_iso( kt, kit000,cdtype, pgu, pgv, pgui, pgvi, ptb, pta, kjpt, pahtb0 )      ! Empty routine
       INTEGER:: kt, kit000
       CHARACTER(len=3) ::   cdtype
-      REAL, DIMENSION(:,:,:) ::   pgu, pgv   ! tracer gradient at pstep levels
+      REAL, DIMENSION(:,:,:) ::   pgu, pgv, pgui, pgvi    ! tracer gradient at pstep levels
       REAL, DIMENSION(:,:,:,:) ::   ptb, pta
       WRITE(*,*) 'tra_ldf_iso: You should not have seen this print! error?', kt, kit000, cdtype,   &
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso_grif.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso_grif.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_iso_grif.F90	(revision 5075)
@@ -252,11 +252,6 @@
          END DO
          IF( ln_zps.and.l_grad_zps ) THEN              ! partial steps: correction at the last level
-# if defined key_vectopt_loop
-            DO jj = 1, 1
-               DO ji = 1, jpij-jpi   ! vector opt. (forced unrolling)
-# else
             DO jj = 1, jpjm1
                DO ji = 1, jpim1
-# endif
                   zdit(ji,jj,mbku(ji,jj)) = pgu(ji,jj,jn)
                   zdjt(ji,jj,mbkv(ji,jj)) = pgv(ji,jj,jn)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_lap.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_lap.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traldf_lap.F90	(revision 5075)
@@ -43,5 +43,6 @@
 CONTAINS
 
-   SUBROUTINE tra_ldf_lap( kt, kit000, cdtype, pgu, pgv,      &
+   SUBROUTINE tra_ldf_lap( kt, kit000, cdtype, pgu , pgv ,    &
+      &                                        pgui, pgvi,    &
       &                                ptb, pta, kjpt ) 
       !!----------------------------------------------------------------------
@@ -69,4 +70,5 @@
       INTEGER                              , INTENT(in   ) ::   kjpt       ! number of tracers
       REAL(wp), DIMENSION(jpi,jpj    ,kjpt), INTENT(in   ) ::   pgu, pgv   ! tracer gradient at pstep levels
+      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(in   ) ::   pgui, pgvi ! tracer gradient at top levels
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   ) ::   ptb        ! before and now tracer fields
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(inout) ::   pta        ! tracer trend 
@@ -114,4 +116,17 @@
                         ztv(ji,jj,jk) = zabe2 * pgv(ji,jj,jn)
                      ENDIF
+                     
+                     ! (ISH)
+                     ! ice shelf level level MAX(2,jk) => only where ice shelf
+                     iku = miku(ji,jj) 
+                     ikv = mikv(ji,jj) 
+                     IF( iku == MAX(2,jk) ) THEN 
+                        zabe1 = fsahtu(ji,jj,iku) * umask(ji,jj,iku) * re2u_e1u(ji,jj) * fse3u_n(ji,jj,iku) 
+                        ztu(ji,jj,jk) = zabe1 * pgui(ji,jj,jn) 
+                     ENDIF 
+                     IF( ikv == MAX(2,jk) ) THEN 
+                        zabe2 = fsahtv(ji,jj,ikv) * vmask(ji,jj,ikv) * re1v_e2v(ji,jj) * fse3v_n(ji,jj,ikv) 
+                        ztv(ji,jj,jk) = zabe2 * pgvi(ji,jj,jn) 
+                     END IF 
                   END DO
                END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tranpc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tranpc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tranpc.F90	(revision 5075)
@@ -2,5 +2,5 @@
    !!==============================================================================
    !!                       ***  MODULE  tranpc  ***
-   !! Ocean active tracers:  non penetrative convection scheme
+   !! Ocean active tracers:  non penetrative convective adjustment scheme
    !!==============================================================================
    !! History :  1.0  ! 1990-09  (G. Madec)  Original code
@@ -9,4 +9,5 @@
    !!            3.0  ! 2008-06  (G. Madec)  applied on ta, sa and called before tranxt in step.F90
    !!            3.3  ! 2010-05  (C. Ethe, G. Madec)  merge TRC-TRA
+   !!            3.7  ! 2014-06  (L. Brodeau) new algorithm based on local Brunt-Vaisala freq.
    !!----------------------------------------------------------------------
 
@@ -14,10 +15,12 @@
    !!   tra_npc : apply the non penetrative convection scheme
    !!----------------------------------------------------------------------
-   USE oce             ! ocean dynamics and active tracers 
+   USE oce             ! ocean dynamics and active tracers
    USE dom_oce         ! ocean space and time domain
+   USE phycst          ! physical constants
    USE zdf_oce         ! ocean vertical physics
-   USE trdmod_oce      ! ocean active tracer trends
+   USE trd_oce         ! ocean active tracer trends
    USE trdtra          ! ocean active tracer trends
-   USE eosbn2          ! equation of state (eos routine) 
+   USE eosbn2          ! equation of state (eos routine)
+   !
    USE lbclnk          ! lateral boundary conditions (or mpp link)
    USE in_out_manager  ! I/O manager
@@ -29,11 +32,12 @@
    PRIVATE
 
-   PUBLIC   tra_npc       ! routine called by step.F90
+   PUBLIC   tra_npc    ! routine called by step.F90
 
    !! * Substitutions
 #  include "domzgr_substitute.h90"
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$ 
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.6 , NEMO Consortium (2014)
+   !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
    !!----------------------------------------------------------------------
@@ -44,44 +48,48 @@
       !!                  ***  ROUTINE tranpc  ***
       !!
-      !! ** Purpose :   Non penetrative convective adjustment scheme. solve 
+      !! ** Purpose : Non-penetrative convective adjustment scheme. solve
       !!      the static instability of the water column on after fields
       !!      while conserving heat and salt contents.
       !!
-      !! ** Method  :   The algorithm used converges in a maximium of jpk 
-      !!      iterations. instabilities are treated when the vertical density
-      !!      gradient is less than 1.e-5.
-      !!      l_trdtra=T: the trend associated with this algorithm is saved.
+      !! ** Method  : updated algorithm able to deal with non-linear equation of state
+      !!              (i.e. static stability computed locally)
       !!
       !! ** Action  : - (ta,sa) after the application od the npc scheme
-      !!              - save the associated trends (ttrd,strd) ('key_trdtra')
+      !!              - send the associated trends for on-line diagnostics (l_trdtra=T)
       !!
-      !! References : Madec, et al., 1991, JPO, 21, 9, 1349-1371.
+      !! References :     Madec, et al., 1991, JPO, 21, 9, 1349-1371.
       !!----------------------------------------------------------------------
-      !
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
       !
       INTEGER  ::   ji, jj, jk   ! dummy loop indices
       INTEGER  ::   inpcc        ! number of statically instable water column
-      INTEGER  ::   inpci        ! number of iteration for npc scheme
-      INTEGER  ::   jiter, jkdown, jkp        ! ???
-      INTEGER  ::   ikbot, ik, ikup, ikdown   ! ???
-      REAL(wp) ::   ze3tot, zta, zsa, zraua, ze3dwn
-      REAL(wp), POINTER, DIMENSION(:,:  ) :: zwx, zwy, zwz
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: ztrdt, ztrds, zrhop
+      INTEGER  ::   jiter, ikbot, ik, ikup, ikdown, ilayer, ikm   ! local integers
+      LOGICAL  ::   l_bottom_reached, l_column_treated
+      REAL(wp) ::   zta, zalfa, zsum_temp, zsum_alfa, zaw, zdz, zsum_z
+      REAL(wp) ::   zsa, zbeta, zsum_sali, zsum_beta, zbw, zrw, z1_r2dt
+      REAL(wp), POINTER, DIMENSION(:)       ::   zvn2   ! vertical profile of N2 at 1 given point...
+      REAL(wp), POINTER, DIMENSION(:,:)     ::   zvts   ! vertical profile of T and S at 1 given point...
+      REAL(wp), POINTER, DIMENSION(:,:)     ::   zvab   ! vertical profile of alpha and beta
+      REAL(wp), POINTER, DIMENSION(:,:,:)   ::   zn2    ! N^2 
+      REAL(wp), POINTER, DIMENSION(:,:,:,:) ::   zab    ! alpha and beta
+      REAL(wp), POINTER, DIMENSION(:,:,:)   ::   ztrdt, ztrds   ! 3D workspace
+      !
+      !!LB debug:
+      LOGICAL, PARAMETER :: l_LB_debug = .FALSE.
+      INTEGER :: ilc1, jlc1, klc1, nncpu
+      LOGICAL :: lp_monitor_point = .FALSE.
+      !!LB debug.
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('tra_npc')
       !
-      CALL wrk_alloc(jpi, jpj, jpk, zrhop )
-      CALL wrk_alloc(jpi, jpk, zwx, zwy, zwz )
-      !
       IF( MOD( kt, nn_npc ) == 0 ) THEN
-
-         inpcc = 0
-         inpci = 0
-
-         CALL eos( tsa, rhd, zrhop, fsdept_n(:,:,:) )         ! Potential density
-
-         IF( l_trdtra )   THEN                    !* Save ta and sa trends
+         !
+         CALL wrk_alloc( jpi, jpj, jpk, zn2 )    ! N2
+         CALL wrk_alloc( jpi, jpj, jpk, 2, zab ) ! Alpha and Beta
+         CALL wrk_alloc( jpk, 2, zvts, zvab )    ! 1D column vector at point ji,jj
+         CALL wrk_alloc( jpk, zvn2 )             ! 1D column vector at point ji,jj
+
+         IF( l_trdtra )   THEN                    !* Save initial after fields
             CALL wrk_alloc( jpi, jpj, jpk, ztrdt, ztrds )
             ztrdt(:,:,:) = tsa(:,:,:,jp_tem) 
@@ -89,135 +97,240 @@
          ENDIF
 
-         !                                                ! ===============
-         DO jj = 1, jpj                                   !  Vertical slab
-            !                                             ! ===============
-            !  Static instability pointer 
-            ! ----------------------------
-            DO jk = 1, jpkm1
-               DO ji = 1, jpi
-                  zwx(ji,jk) = ( zrhop(ji,jj,jk) - zrhop(ji,jj,jk+1) ) * tmask(ji,jj,jk+1)
-               END DO
-            END DO
-
-            ! 1.1 do not consider the boundary points
-
-            ! even if east-west cyclic b. c. do not considere ji=1 or jpi
-            DO jk = 1, jpkm1
-               zwx( 1 ,jk) = 0.e0
-               zwx(jpi,jk) = 0.e0
-            END DO
-            ! even if south-symmetric b. c. used, do not considere jj=1
-            IF( jj == 1 )   zwx(:,:) = 0.e0
-
-            DO jk = 1, jpkm1
-               DO ji = 1, jpi
-                  zwx(ji,jk) = 1.
-                  IF( zwx(ji,jk) < 1.e-5 ) zwx(ji,jk) = 0.e0
-               END DO
-            END DO
-
-            zwy(:,1) = 0.e0
-            DO ji = 1, jpi
-               DO jk = 1, jpkm1
-                  zwy(ji,1) = zwy(ji,1) + zwx(ji,jk)
-               END DO
-            END DO
-
-            zwz(1,1) = 0.e0
-            DO ji = 1, jpi
-               zwz(1,1) = zwz(1,1) + zwy(ji,1)
-            END DO
-
-            inpcc = inpcc + NINT( zwz(1,1) )
-
-
-            ! 2. Vertical mixing for each instable portion of the density profil
-            ! ------------------------------------------------------------------
-
-            IF( zwz(1,1) /= 0.e0 ) THEN         ! -->> the density profil is statically instable :
-               DO ji = 1, jpi
-                  IF( zwy(ji,1) /= 0.e0 ) THEN
+         !LB debug:
+         IF( lwp .AND. l_LB_debug ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'LOLO: entering tra_npc, kt, narea =', kt, narea
+         ENDIF
+         !LBdebug: Monitoring of 1 column subject to convection...
+         IF( l_LB_debug ) THEN
+            ! Location of 1 known convection spot to follow what's happening in the water column
+            ilc1 = 54 ;  jlc1 = 15 ; ! Labrador ORCA1 4x4 cpus:
+            nncpu = 15  ; ! the CPU domain contains the convection spot
+            !ilc1 = 14 ;  jlc1 = 13 ; ! Labrador ORCA1 8x8 cpus:
+            !nncpu = 54  ; ! the CPU domain contains the convection spot
+            klc1 =  mbkt(ilc1,jlc1) ! bottom of the ocean for debug point...          
+         ENDIF
+         !LBdebug.
+
+         CALL eos_rab( tsa, zab )         ! after alpha and beta
+         CALL bn2    ( tsa, zab, zn2 )    ! after Brunt-Vaisala
+        
+         inpcc = 0
+
+         DO jj = 2, jpjm1                 ! interior column only
+            DO ji = fs_2, fs_jpim1
+               !
+               IF( tmask(ji,jj,2) == 1 ) THEN      ! At least 2 ocean points
+                  !                                     ! consider one ocean column 
+                  zvts(:,jp_tem) = tsa(ji,jj,:,jp_tem)      ! temperature
+                  zvts(:,jp_sal) = tsa(ji,jj,:,jp_sal)      ! salinity
+
+                  zvab(:,jp_tem)  = zab(ji,jj,:,jp_tem)     ! Alpha 
+                  zvab(:,jp_sal)  = zab(ji,jj,:,jp_sal)     ! Beta  
+                  zvn2(:)         = zn2(ji,jj,:)            ! N^2 
+                 
+                  IF( l_LB_debug ) THEN                  !LB debug:
+                     lp_monitor_point = .FALSE.
+                     IF( ( ji == ilc1 ).AND.( jj == jlc1 ) ) lp_monitor_point = .TRUE.
+                     ! writing only if on CPU domain where conv region is:
+                     lp_monitor_point = (narea == nncpu).AND.lp_monitor_point 
+                     
+                     IF(lp_monitor_point) THEN
+                        WRITE(numout,*) '' ;WRITE(numout,*) '' ;
+                       WRITE(numout,'("Time step = ",i6.6," !!!")')  kt
+                        WRITE(numout,'(" *** BEFORE anything, N^2 for point ",i3,",",i3,":" )') ji,jj
+                        DO jk = 1, klc1
+                           WRITE(numout,*) jk, zvn2(jk)
+                        END DO
+                        WRITE(numout,*) ' '
+                     ENDIF
+                  ENDIF                                  !LB debug  end
+
+                  ikbot = mbkt(ji,jj)   ! ikbot: ocean bottom T-level
+                  ik = 1                ! because N2 is irrelevant at the surface level (will start at ik=2)
+                  ilayer = 0
+                  jiter  = 0
+                  l_column_treated = .FALSE.
+                 
+                  DO WHILE ( .NOT. l_column_treated )
                      !
-                     ikbot = mbkt(ji,jj)        ! ikbot: ocean bottom T-level
+                     jiter = jiter + 1
+                    
+                     IF( jiter >= 400 ) EXIT
+                    
+                     l_bottom_reached = .FALSE.
+
+                     DO WHILE ( .NOT. l_bottom_reached )
+
+                        ik = ik + 1
+                       
+                        !! Checking level ik for instability
+                        !! ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+                        IF( zvn2(ik) < 0. ) THEN ! Instability found!
+
+                           ikm  = ik              ! first level whith negative N2
+                           ilayer = ilayer + 1    ! yet another layer found....
+                           IF(jiter == 1) inpcc = inpcc + 1
+
+                           IF(l_LB_debug .AND. lp_monitor_point) &
+                              & WRITE(numout,*) 'Negative N2 at ik =', ikm, ' layer nb.', ilayer, &
+                              & ' inpcc =', inpcc
+
+                           !! Case we mix with upper regions where N2==0:
+                           !! All the points above ikup where N2 == 0 must also be mixed => we go
+                           !! upward to find a new ikup, where the layer doesn't have N2==0
+                           ikup = ikm
+                           DO jk = ikm, 2, -1
+                              ikup = ikup - 1
+                              IF( (zvn2(jk-1) > 0.).OR.(ikup == 1) ) EXIT
+                           END DO
+                          
+                           ! adjusting ikup if the upper part of the unstable column was neutral (N2=0)
+                           IF((zvn2(ikup+1) == 0.).AND.(ikup /= 1)) ikup = ikup+1 ;
+
+                          
+                           IF( lp_monitor_point )   WRITE(numout,*) ' => ikup is =', ikup, ' layer nb.', ilayer
+                          
+                           zsum_temp = 0._wp
+                           zsum_sali = 0._wp
+                           zsum_alfa = 0._wp
+                           zsum_beta = 0._wp
+                           zsum_z    = 0._wp
+                                                    
+                           DO jk = ikup, ikbot+1      ! Inside the instable (and overlying neutral) portion of the column
+                              !
+                              IF(l_LB_debug .AND. lp_monitor_point) WRITE(numout,*) '     -> summing for jk =', jk
+                              !
+                              zdz       = fse3t(ji,jj,jk)
+                              zsum_temp = zsum_temp + zvts(jk,jp_tem)*zdz
+                              zsum_sali = zsum_sali + zvts(jk,jp_sal)*zdz
+                              zsum_alfa = zsum_alfa + zvab(jk,jp_tem)*zdz
+                              zsum_beta = zsum_beta + zvab(jk,jp_sal)*zdz
+                              zsum_z    = zsum_z    + zdz
+                              !
+                              !! EXIT if we found the bottom of the unstable portion of the water column    
+                              IF( (zvn2(jk+1) > 0.).OR.(jk == ikbot ).OR.((jk==ikm).AND.(zvn2(jk+1) == 0.)) )   EXIT
+                           END DO
+                          
+                           !ik     = jk !LB remove?
+                           ikdown = jk ! for the current unstable layer, ikdown is the deepest point with a negative N2
+                          
+                           IF(l_LB_debug .AND. lp_monitor_point) &
+                              &    WRITE(numout,*) '  => ikdown =', ikdown, '  layer nb.', ilayer
+                          
+                           ! Mixing Temperature and salinity between ikup and ikdown:
+                           zta   = zsum_temp/zsum_z
+                           zsa   = zsum_sali/zsum_z
+                           zalfa = zsum_alfa/zsum_z
+                           zbeta = zsum_beta/zsum_z
+
+                           IF(l_LB_debug .AND. lp_monitor_point) THEN
+                              WRITE(numout,*) '  => Mean temp. in that portion =', zta
+                              WRITE(numout,*) '  => Mean sali. in that portion =', zsa
+                              WRITE(numout,*) '  => Mean Alpha in that portion =', zalfa
+                              WRITE(numout,*) '  => Mean Beta  in that portion =', zbeta
+                           ENDIF
+
+                           !! Homogenaizing the temperature, salinity, alpha and beta in this portion of the column
+                           DO jk = ikup, ikdown
+                              zvts(jk,jp_tem) = zta
+                              zvts(jk,jp_sal) = zsa
+                              zvab(jk,jp_tem) = zalfa
+                              zvab(jk,jp_sal) = zbeta
+                           END DO
+                           !
+                           !! Before updating N2, it is possible that another unstable
+                           !! layer exists underneath the one we just homogeneized!
+                           ik = ikdown
+                           ! 
+                        ENDIF  ! IF( zvn2(ik+1) < 0. ) THEN
+                        !
+                        IF( ik == ikbot ) l_bottom_reached = .TRUE.
+                        !
+                     END DO ! DO WHILE ( .NOT. l_bottom_reached )
+
+                     IF( ik /= ikbot )   STOP 'ERROR: tranpc.F90 => PROBLEM #1'
+                    
+                     ! ******* At this stage ik == ikbot ! *******
+                    
+                     IF( ilayer > 0 ) THEN
+                        !! least an unstable layer has been found
+                        !! Temperature, Salinity, Alpha and Beta have been homogenized in the unstable portion
+                        !! => Need to re-compute N2! will use Alpha and Beta!
+                        !
+                        DO jk = ikup+1, ikdown+1   ! we must go 1 point deeper than ikdown!     
+                           !! Doing exactly as in eosbn2.F90:
+                           !! * Except that we only are interested in the sign of N2 !!!
+                           !!   => just considering the vertical gradient of density
+                           zrw =   (fsdepw(ji,jj,jk  ) - fsdept(ji,jj,jk)) &
+                               & / (fsdept(ji,jj,jk-1) - fsdept(ji,jj,jk))
+                           zaw = zvab(jk,jp_tem) * (1._wp - zrw) + zvab(jk-1,jp_tem) * zrw
+                           zbw = zvab(jk,jp_sal) * (1._wp - zrw) + zvab(jk-1,jp_sal) * zrw
+                          
+                           !zvn2(jk) = grav*( zaw * ( zvts(jk-1,jp_tem) - zvts(jk,jp_tem) )     &
+                           !     &           - zbw * ( zvts(jk-1,jp_sal) - zvts(jk,jp_sal) )  )  &
+                           !     &       / fse3w(ji,jj,jk) * tmask(ji,jj,jk)
+                           zvn2(jk) = (  zaw * ( zvts(jk-1,jp_tem) - zvts(jk,jp_tem) )     &
+                                &      - zbw * ( zvts(jk-1,jp_sal) - zvts(jk,jp_sal) )  )  
+                        END DO
+
+                        IF(l_LB_debug .AND. lp_monitor_point) THEN
+                           WRITE(numout, '(" *** After iteration #",i3.3,", N^2 for point ",i3,",",i3,":" )') &
+                              & jiter, ji,jj
+                           DO jk = 1, klc1
+                              WRITE(numout,*) jk, zvn2(jk)
+                           END DO
+                           WRITE(numout,*) ' '
+                        ENDIF
+
+                        ik     = 1  ! starting again at the surface for the next iteration
+                        ilayer = 0
+                     ENDIF
                      !
-                     DO jiter = 1, jpk          ! vertical iteration
-                        !
-                        ! search of ikup : the first static instability from the sea surface
-                        !
-                        ik = 0
-220                     CONTINUE
-                        ik = ik + 1
-                        IF( ik >= ikbot ) GO TO 200
-                        zwx(ji,ik) = zrhop(ji,jj,ik) - zrhop(ji,jj,ik+1)
-                        IF( zwx(ji,ik) <= 0.e0 ) GO TO 220
-                        ikup = ik
-                        ! the density profil is instable below ikup
-                        ! ikdown : bottom of the instable portion of the density profil
-                        ! search of ikdown and vertical mixing from ikup to ikdown
-                        !
-                        ze3tot= fse3t(ji,jj,ikup)
-                        zta   = tsa  (ji,jj,ikup,jp_tem)
-                        zsa   = tsa  (ji,jj,ikup,jp_sal)
-                        zraua = zrhop(ji,jj,ikup)
-                        !
-                        DO jkdown = ikup+1, ikbot-1
-                           IF( zraua <= zrhop(ji,jj,jkdown) ) THEN
-                              ikdown = jkdown
-                              GO TO 240
-                           ENDIF
-                           ze3dwn =  fse3t(ji,jj,jkdown)
-                           ze3tot =  ze3tot + ze3dwn
-                           zta   = ( zta*(ze3tot-ze3dwn) + tsa(ji,jj,jkdown,jp_tem)*ze3dwn )/ze3tot
-                           zsa   = ( zsa*(ze3tot-ze3dwn) + tsa(ji,jj,jkdown,jp_sal)*ze3dwn )/ze3tot
-                           zraua = ( zraua*(ze3tot-ze3dwn) + zrhop(ji,jj,jkdown)*ze3dwn )/ze3tot
-                           inpci = inpci+1
-                        END DO
-                        ikdown = ikbot-1
-240                     CONTINUE
-                        !
-                        DO jkp = ikup, ikdown-1
-                           tsa  (ji,jj,jkp,jp_tem) = zta
-                           tsa  (ji,jj,jkp,jp_sal) = zsa
-                           zrhop(ji,jj,jkp       ) = zraua
-                        END DO
-                        IF (ikdown == ikbot-1 .AND. zraua >= zrhop(ji,jj,ikdown) ) THEN
-                           tsa  (ji,jj,jkp,jp_tem) = zta
-                           tsa  (ji,jj,jkp,jp_sal) = zsa
-                           zrhop(ji,jj,ikdown    ) = zraua
-                        ENDIF
-                     END DO
-                  ENDIF
-200               CONTINUE
-               END DO
-               ! <<-- no more static instability on slab jj
-            ENDIF
-            !                                             ! ===============
-         END DO                                           !   End of slab
-         !                                                ! ===============
-         ! 
-         IF( l_trdtra )   THEN         ! save the Non penetrative mixing trends for diagnostic
-            ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
-            ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
-            CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_npc, ztrdt )
-            CALL trd_tra( kt, 'TRA', jp_sal, jptra_trd_npc, ztrds )
+                     IF( ik >= ikbot ) THEN
+                        IF(l_LB_debug .AND. lp_monitor_point) WRITE(numout,*) '    --- exiting jiter loop ---'
+                        l_column_treated = .TRUE.
+                     ENDIF
+                     !
+                  END DO ! DO WHILE ( .NOT. l_column_treated )
+
+                  !! Updating tsa:
+                  tsa(ji,jj,:,jp_tem) = zvts(:,jp_tem)
+                  tsa(ji,jj,:,jp_sal) = zvts(:,jp_sal)
+
+                  !! lolo:  Should we update something else????
+                  !! => like alpha and beta?
+
+                  IF(l_LB_debug .AND. lp_monitor_point) WRITE(numout,*) ''
+
+               ENDIF ! IF( tmask(ji,jj,3) == 1 ) THEN
+
+            END DO ! ji
+         END DO ! jj
+         !
+         IF( l_trdtra ) THEN         ! send the Non penetrative mixing trends for diagnostic
+            z1_r2dt = 1._wp / (2._wp * rdt)
+            ztrdt(:,:,:) = ( tsa(:,:,:,jp_tem) - ztrdt(:,:,:) ) * z1_r2dt
+            ztrds(:,:,:) = ( tsa(:,:,:,jp_sal) - ztrds(:,:,:) ) * z1_r2dt
+            CALL trd_tra( kt, 'TRA', jp_tem, jptra_npc, ztrdt )
+            CALL trd_tra( kt, 'TRA', jp_sal, jptra_npc, ztrds )
             CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds )
          ENDIF
-      
-         ! Lateral boundary conditions on ( ta, sa )   ( Unchanged sign)
-         ! ------------------------------============
+         !
          CALL lbc_lnk( tsa(:,:,:,jp_tem), 'T', 1. )   ;   CALL lbc_lnk( tsa(:,:,:,jp_sal), 'T', 1. )
-      
-
-         !  2. non penetrative convective scheme statistics
-         !  -----------------------------------------------
-         IF( nn_npcp /= 0 .AND. MOD( kt, nn_npcp ) == 0 ) THEN
-            IF(lwp) WRITE(numout,*)' kt=',kt, ' number of statically instable',   &
-               &                   ' water column : ',inpcc, ' number of iteration : ',inpci
-         ENDIF
-         !
-      ENDIF
-      !
-      CALL wrk_dealloc(jpi, jpj, jpk, zrhop )
-      CALL wrk_dealloc(jpi, jpk, zwx, zwy, zwz )
+         !
+         IF(lwp) THEN
+            WRITE(numout,*) 'LOLO: exiting tra_npc, kt =', kt
+            WRITE(numout,*)' => number of statically instable water column : ',inpcc
+            WRITE(numout,*) '' ; WRITE(numout,*) ''
+         ENDIF
+         !
+         CALL wrk_dealloc(jpi, jpj, jpk, zn2 )
+         CALL wrk_dealloc(jpi, jpj, jpk, 2, zab )
+         CALL wrk_dealloc(jpk, zvn2 )
+         CALL wrk_dealloc(jpk, 2, zvts, zvab )
+         !
+      ENDIF   ! IF( MOD( kt, nn_npc ) == 0 ) THEN
       !
       IF( nn_timing == 1 )  CALL timing_stop('tra_npc')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tranxt.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tranxt.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/tranxt.F90	(revision 5075)
@@ -27,23 +27,25 @@
    USE dom_oce         ! ocean space and time domain variables 
    USE sbc_oce         ! surface boundary condition: ocean
-   USE zdf_oce         ! ???
+   USE zdf_oce         ! ocean vertical mixing
    USE domvvl          ! variable volume
    USE dynspg_oce      ! surface     pressure gradient variables
    USE dynhpg          ! hydrostatic pressure gradient 
-   USE trdmod_oce      ! ocean space and time domain variables 
-   USE trdtra          ! ocean active tracers trends 
-   USE phycst
-   USE bdy_oce
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
+   USE traqsr          ! penetrative solar radiation (needed for nksr)
+   USE phycst          ! physical constant
+   USE ldftra_oce      ! lateral physics on tracers
+   USE bdy_oce         ! BDY open boundary condition variables
    USE bdytra          ! open boundary condition (bdy_tra routine)
+   !
    USE in_out_manager  ! I/O manager
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
    USE prtctl          ! Print control
-   USE traqsr          ! penetrative solar radiation (needed for nksr)
+   USE wrk_nemo        ! Memory allocation
+   USE timing          ! Timing
 #if defined key_agrif
    USE agrif_opa_update
    USE agrif_opa_interp
 #endif
-   USE wrk_nemo        ! Memory allocation
-   USE timing          ! Timing
 
    IMPLICIT NONE
@@ -80,5 +82,5 @@
       !!             at the local domain   boundaries through lbc_lnk call, 
       !!             at the one-way open boundaries (lk_bdy=T), 
-      !!             at the AGRIF zoom     boundaries (lk_agrif=T)
+      !!             at the AGRIF zoom   boundaries (lk_agrif=T)
       !!
       !!              - Update lateral boundary conditions on AGRIF children
@@ -127,4 +129,8 @@
          ztrdt(:,:,:) = tsn(:,:,:,jp_tem) 
          ztrds(:,:,:) = tsn(:,:,:,jp_sal)
+         IF( ln_traldf_iso ) THEN              ! diagnose the "pure" Kz diffusive trend 
+            CALL trd_tra( kt, 'TRA', jp_tem, jptra_zdfp, ztrdt )
+            CALL trd_tra( kt, 'TRA', jp_sal, jptra_zdfp, ztrds )
+         ENDIF
       ENDIF
 
@@ -150,10 +156,10 @@
       IF( l_trdtra ) THEN      ! trend of the Asselin filter (tb filtered - tb)/dt     
          DO jk = 1, jpkm1
-            zfact = 1.e0_wp / r2dtra(jk)             
+            zfact = 1._wp / r2dtra(jk)             
             ztrdt(:,:,jk) = ( tsb(:,:,jk,jp_tem) - ztrdt(:,:,jk) ) * zfact
             ztrds(:,:,jk) = ( tsb(:,:,jk,jp_sal) - ztrds(:,:,jk) ) * zfact
          END DO
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_atf, ztrdt )
-         CALL trd_tra( kt, 'TRA', jp_sal, jptra_trd_atf, ztrds )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_atf, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_atf, ztrds )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds )
       END IF
@@ -163,6 +169,5 @@
          &                       tab3d_2=tsn(:,:,:,jp_sal), clinfo2=       ' Sn: ', mask2=tmask )
       !
-      !
-      IF( nn_timing == 1 )  CALL timing_stop('tra_nxt')
+      IF( nn_timing == 1 )   CALL timing_stop('tra_nxt')
       !
    END SUBROUTINE tra_nxt
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traqsr.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traqsr.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/traqsr.F90	(revision 5075)
@@ -21,6 +21,6 @@
    USE sbc_oce         ! surface boundary condition: ocean
    USE trc_oce         ! share SMS/Ocean variables
-   USE trdmod_oce      ! ocean variables trends
-   USE trdtra          ! ocean active tracers trends 
+   USE trd_oce        ! trends: ocean variables
+   USE trdtra         ! trends manager: tracers
    USE in_out_manager  ! I/O manager
    USE phycst          ! physical constants
@@ -129,4 +129,6 @@
       IF( kt == nit000 ) THEN                     ! Set the forcing field at nit000 - 1
          !                                        ! -----------------------------------
+         qsr_hc(:,:,:) = 0.e0
+         !
          IF( ln_rstart .AND.    &                    ! Restart: read in restart file
               & iom_varid( numror, 'qsr_hc_b', ldstop = .FALSE. ) > 0 ) THEN
@@ -167,6 +169,5 @@
                DO ji = 1, jpi
                   IF ( qsr(ji,jj) /= 0._wp ) THEN
-                     oatte(ji,jj) = ( qsr_hc(ji,jj,1) / ( r1_rau0_rcp * qsr(ji,jj) ) )
-                     iatte(ji,jj) = oatte(ji,jj)
+                     fraqsr_1lev(ji,jj) = ( qsr_hc(ji,jj,1) / ( r1_rau0_rcp * qsr(ji,jj) ) )
                   ENDIF
                END DO
@@ -239,6 +240,5 @@
                         zzc2 = zcoef  * EXP( - fse3t(ji,jj,1) * zekg(ji,jj) )
                         zzc3 = zcoef  * EXP( - fse3t(ji,jj,1) * zekr(ji,jj) )
-                        oatte(ji,jj) = 1.0 - ( zzc0 + zzc1 + zzc2  + zzc3  ) * tmask(ji,jj,2) 
-                        iatte(ji,jj) = 1.0 - ( zzc0 + zzc1 + zcoef + zcoef ) * tmask(ji,jj,2)
+                        fraqsr_1lev(ji,jj) = 1.0 - ( zzc0 + zzc1 + zzc2  + zzc3  ) * tmask(ji,jj,2) 
                      END DO
                   END DO
@@ -257,6 +257,5 @@
                ! clem: store attenuation coefficient of the first ocean level
                IF ( lk_lim3 .AND. ln_qsr_ice ) THEN
-                  oatte(:,:) = etot3(:,:,1) / r1_rau0_rcp
-                  iatte(:,:) = oatte(:,:)
+                  fraqsr_1lev(:,:) = etot3(:,:,1) / r1_rau0_rcp
                ENDIF
            ENDIF
@@ -285,6 +284,5 @@
                         zc0 = zz0 * EXP( -fsdepw(ji,jj,1)*xsi0r ) + zz1 * EXP( -fsdepw(ji,jj,1)*xsi1r )
                         zc1 = zz0 * EXP( -fsdepw(ji,jj,2)*xsi0r ) + zz1 * EXP( -fsdepw(ji,jj,2)*xsi1r )
-                        oatte(ji,jj) = ( zc0*tmask(ji,jj,1) - zc1*tmask(ji,jj,2) ) / r1_rau0_rcp
-                        iatte(ji,jj) = oatte(ji,jj)
+                        fraqsr_1lev(ji,jj) = ( zc0*tmask(ji,jj,1) - zc1*tmask(ji,jj,2) ) / r1_rau0_rcp
                      END DO
                   END DO
@@ -294,5 +292,6 @@
                   DO jj = 2, jpjm1
                      DO ji = fs_2, fs_jpim1   ! vector opt.
-                        qsr_hc(ji,jj,jk) =  etot3(ji,jj,jk) * qsr(ji,jj)
+                        ! (ISF) no light penetration below the ice shelves         
+                        qsr_hc(ji,jj,jk) =  etot3(ji,jj,jk) * qsr(ji,jj) * tmask(ji,jj,1)
                      END DO
                   END DO
@@ -300,6 +299,5 @@
                ! clem: store attenuation coefficient of the first ocean level
                IF ( lk_lim3 .AND. ln_qsr_ice ) THEN
-                  oatte(:,:) = etot3(:,:,1) / r1_rau0_rcp
-                  iatte(:,:) = oatte(:,:)
+                  fraqsr_1lev(:,:) = etot3(:,:,1) / r1_rau0_rcp
                ENDIF
                !
@@ -332,5 +330,5 @@
       IF( l_trdtra ) THEN     ! qsr tracers trends saved for diagnostics
          ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_qsr, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_qsr, ztrdt )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdt ) 
       ENDIF
@@ -382,8 +380,7 @@
       IF( nn_timing == 1 )  CALL timing_start('tra_qsr_init')
       !
-      ! clem init for oatte and iatte
+      ! Default value for fraqsr_1lev
       IF( .NOT. ln_rstart ) THEN
-         oatte(:,:) = 1._wp
-         iatte(:,:) = 1._wp
+         fraqsr_1lev(:,:) = 1._wp
       ENDIF
       !
@@ -520,5 +517,6 @@
                   !
                   DO jk = 1, nksr
-                     etot3(:,:,jk) = r1_rau0_rcp * ( zea(:,:,jk) - zea(:,:,jk+1) ) 
+                     ! (ISF) no light penetration below the ice shelves
+                     etot3(:,:,jk) = r1_rau0_rcp * ( zea(:,:,jk) - zea(:,:,jk+1) ) * tmask(:,:,1)
                   END DO
                   etot3(:,:,nksr+1:jpk) = 0.e0                ! below 400m set to zero
@@ -548,5 +546,5 @@
                         zc0 = zz0 * EXP( -fsdepw(ji,jj,jk  )*xsi0r ) + zz1 * EXP( -fsdepw(ji,jj,jk  )*xsi1r )
                         zc1 = zz0 * EXP( -fsdepw(ji,jj,jk+1)*xsi0r ) + zz1 * EXP( -fsdepw(ji,jj,jk+1)*xsi1r )
-                        etot3(ji,jj,jk) = (  zc0 * tmask(ji,jj,jk) - zc1 * tmask(ji,jj,jk+1)  ) 
+                        etot3(ji,jj,jk) = (  zc0 * tmask(ji,jj,jk) - zc1 * tmask(ji,jj,jk+1)  ) * tmask(ji,jj,1) 
                      END DO
                   END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trasbc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trasbc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trasbc.F90	(revision 5075)
@@ -18,10 +18,14 @@
    USE dom_oce         ! ocean space domain variables
    USE phycst          ! physical constant
+   USE sbcmod          ! ln_rnf  
+   USE sbcrnf          ! River runoff  
    USE traqsr          ! solar radiation penetration
-   USE trdmod_oce      ! ocean trends 
-   USE trdtra          ! ocean trends
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
+   !
    USE in_out_manager  ! I/O manager
    USE prtctl          ! Print control
    USE sbcrnf          ! River runoff  
+   USE sbcisf          ! Ice shelf   
    USE sbcmod          ! ln_rnf  
    USE iom
@@ -29,4 +33,5 @@
    USE wrk_nemo        ! Memory Allocation
    USE timing          ! Timing
+   USE eosbn2
 
    IMPLICIT NONE
@@ -39,5 +44,5 @@
 #  include "vectopt_loop_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! NEMO/OPA 3.7 , NEMO Consortium (2014)
    !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -91,5 +96,5 @@
       !!         where emp, the surface freshwater budget (evaporation minus
       !!         precipitation minus runoff) given in kg/m2/s is divided
-      !!         by rau0 = 1020 kg/m3 (density of sea water) to obtain m/s.    
+      !!         by rau0 (density of sea water) to obtain m/s.    
       !!         Note: even though Fwe does not appear explicitly for 
       !!         temperature in this routine, the heat carried by the water
@@ -107,10 +112,14 @@
       !! ** Action  : - Update the 1st level of (ta,sa) with the trend associated
       !!                with the tracer surface boundary condition 
-      !!              - save the trend it in ttrd ('key_trdtra')
+      !!              - send trends to trdtra module (l_trdtra=T)
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
       !!
       INTEGER  ::   ji, jj, jk, jn           ! dummy loop indices  
+      INTEGER  ::   ikt, ikb 
+      INTEGER  ::   nk_isf
       REAL(wp) ::   zfact, z1_e3t, zdep
+      REAL(wp) ::   zalpha, zhk
+      REAL(wp) ::  zt_frz, zpress
       REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztrdt, ztrds
       !!----------------------------------------------------------------------
@@ -124,5 +133,5 @@
       ENDIF
 
-      IF( l_trdtra )   THEN                    !* Save ta and sa trends
+      IF( l_trdtra ) THEN                    !* Save ta and sa trends
          CALL wrk_alloc( jpi, jpj, jpk, ztrdt, ztrds ) 
          ztrdt(:,:,:) = tsa(:,:,:,jp_tem)
@@ -137,5 +146,5 @@
 
       !----------------------------------------
-      !        EMP, EMPS and QNS effects
+      !        EMP, SFX and QNS effects
       !----------------------------------------
       !                                          Set before sbc tracer content fields
@@ -146,14 +155,14 @@
               & iom_varid( numror, 'sbc_hc_b', ldstop = .FALSE. ) > 0 ) THEN
             IF(lwp) WRITE(numout,*) '          nit000-1 surface tracer content forcing fields red in the restart file'
-            zfact = 0.5e0
+            zfact = 0.5_wp
             CALL iom_get( numror, jpdom_autoglo, 'sbc_hc_b', sbc_tsc_b(:,:,jp_tem) )   ! before heat content sbc trend
             CALL iom_get( numror, jpdom_autoglo, 'sbc_sc_b', sbc_tsc_b(:,:,jp_sal) )   ! before salt content sbc trend
          ELSE                                         ! No restart or restart not found: Euler forward time stepping
-            zfact = 1.e0
-            sbc_tsc_b(:,:,:) = 0.e0
+            zfact = 1._wp
+            sbc_tsc_b(:,:,:) = 0._wp
          ENDIF
       ELSE                                         ! Swap of forcing fields
          !                                         ! ----------------------
-         zfact = 0.5e0
+         zfact = 0.5_wp
          sbc_tsc_b(:,:,:) = sbc_tsc(:,:,:)
       ENDIF
@@ -182,6 +191,6 @@
             END DO
          END DO
-         CALL iom_put( "emp_x_sst", emp (:,:) * tsn(:,:,1,jp_tem) )                          ! c/d term on sst
-         CALL iom_put( "emp_x_sss", emp (:,:) * tsn(:,:,1,jp_sal) )                          ! c/d term on sss
+         IF( iom_use('emp_x_sst') )   CALL iom_put( "emp_x_sst", emp (:,:) * tsn(:,:,1,jp_tem) )   ! c/d term on sst
+         IF( iom_use('emp_x_sss') )   CALL iom_put( "emp_x_sss", emp (:,:) * tsn(:,:,1,jp_sal) )   ! c/d term on sss
       ENDIF
       ! Concentration dilution effect on (t,s) due to evapouration, precipitation and qns, but not river runoff  
@@ -205,4 +214,58 @@
       ENDIF
       !
+      !
+      !----------------------------------------
+      !       Ice Shelf effects (ISF)
+      !     tbl treated as in Losh (2008) JGR
+      !----------------------------------------
+      !
+      IF( nn_isf > 0 ) THEN
+         zfact = 0.5e0
+         DO jj = 2, jpj
+            DO ji = fs_2, fs_jpim1
+         
+               ikt = misfkt(ji,jj)
+               ikb = misfkb(ji,jj)
+   
+               ! level fully include in the ice shelf boundary layer
+               ! if isfdiv, we have to remove heat flux due to inflow at 0oC (as in rnf when you add rnf at sst)
+               ! sign - because fwf sign of evapo (rnf sign of precip)
+               DO jk = ikt, ikb - 1
+               ! compute tfreez for the temperature correction (we add water at freezing temperature)
+!                  zpress = grav*rau0*fsdept(ji,jj,jk)*1.e-04
+                  zt_frz = -1.9 !eos_fzp( tsn(ji,jj,jk,jp_sal), zpress )
+               ! compute trend
+                  tsa(ji,jj,jk,jp_tem) = tsa(ji,jj,jk,jp_tem)                                          &
+                     &           + zfact * (risf_tsc_b(ji,jj,jp_tem) + risf_tsc(ji,jj,jp_tem)          &
+                     &               - rdivisf * (fwfisf(ji,jj) + fwfisf_b(ji,jj)) * zt_frz * r1_rau0) &
+                     &           * r1_hisf_tbl(ji,jj)
+                  tsa(ji,jj,jk,jp_sal) = tsa(ji,jj,jk,jp_sal)                                          &
+                     &           + zfact * (risf_tsc_b(ji,jj,jp_sal) + risf_tsc(ji,jj,jp_sal)) * r1_hisf_tbl(ji,jj)
+               END DO
+   
+               ! level partially include in ice shelf boundary layer 
+               ! compute tfreez for the temperature correction (we add water at freezing temperature)
+!               zpress = grav*rau0*fsdept(ji,jj,ikb)*1.e-04
+               zt_frz = -1.9 !eos_fzp( tsn(ji,jj,ikb,jp_sal), zpress )
+               ! compute trend
+               tsa(ji,jj,ikb,jp_tem) = tsa(ji,jj,ikb,jp_tem)                                           &
+                  &              + zfact * (risf_tsc_b(ji,jj,jp_tem) + risf_tsc(ji,jj,jp_tem)          &
+                  &                  - rdivisf * (fwfisf(ji,jj) + fwfisf_b(ji,jj)) * zt_frz * r1_rau0) & 
+                  &              * r1_hisf_tbl(ji,jj) * ralpha(ji,jj)
+               tsa(ji,jj,ikb,jp_sal) = tsa(ji,jj,ikb,jp_sal)                                           &
+                  &              + zfact * (risf_tsc_b(ji,jj,jp_sal) + risf_tsc(ji,jj,jp_sal)) * r1_hisf_tbl(ji,jj) * ralpha(ji,jj) 
+            END DO
+         END DO
+         IF( lrst_oce ) THEN
+            IF(lwp) WRITE(numout,*)
+            IF(lwp) WRITE(numout,*) 'sbc : isf surface tracer content forcing fields written in ocean restart file ',   &
+               &                    'at it= ', kt,' date= ', ndastp
+            IF(lwp) WRITE(numout,*) '~~~~'
+            CALL iom_rstput( kt, nitrst, numrow, 'fwf_isf_b', fwfisf(:,:)          )
+            CALL iom_rstput( kt, nitrst, numrow, 'isf_hc_b' , risf_tsc(:,:,jp_tem) )
+            CALL iom_rstput( kt, nitrst, numrow, 'isf_sc_b' , risf_tsc(:,:,jp_sal) )
+         ENDIF
+      END IF
+      !
       !----------------------------------------
       !        River Runoff effects
@@ -226,9 +289,9 @@
       ENDIF
  
-      IF( l_trdtra )   THEN                      ! save the horizontal diffusive trends for further diagnostics
+      IF( l_trdtra )   THEN                      ! send trends for further diagnostics
          ztrdt(:,:,:) = tsa(:,:,:,jp_tem) - ztrdt(:,:,:)
          ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_nsr, ztrdt )
-         CALL trd_tra( kt, 'TRA', jp_sal, jptra_trd_nsr, ztrds )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_nsr, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_nsr, ztrds )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds ) 
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf.F90	(revision 5075)
@@ -19,11 +19,10 @@
    USE sbc_oce         ! surface boundary condition: ocean
    USE dynspg_oce
-
    USE trazdf_exp      ! vertical diffusion: explicit (tra_zdf_exp     routine)
    USE trazdf_imp      ! vertical diffusion: implicit (tra_zdf_imp     routine)
-
    USE ldftra_oce      ! ocean active tracers: lateral physics
-   USE trdmod_oce      ! ocean active tracers: lateral physics
-   USE trdtra      ! ocean tracers trends 
+   USE trd_oce         ! trends: ocean variables
+   USE trdtra          ! trends manager: tracers 
+   !
    USE in_out_manager  ! I/O manager
    USE prtctl          ! Print control
@@ -32,5 +31,4 @@
    USE wrk_nemo        ! Memory allocation
    USE timing          ! Timing
-
 
    IMPLICIT NONE
@@ -47,5 +45,5 @@
 #  include "vectopt_loop_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! NEMO/OPA 3.7 , NEMO Consortium (2014)
    !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -96,6 +94,8 @@
             ztrds(:,:,jk) = ( ( tsa(:,:,jk,jp_sal) - tsb(:,:,jk,jp_sal) ) / r2dtra(jk) ) - ztrds(:,:,jk)
          END DO
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_zdf, ztrdt )
-         CALL trd_tra( kt, 'TRA', jp_sal, jptra_trd_zdf, ztrds )
+         CALL lbc_lnk( ztrdt, 'T', 1. )
+         CALL lbc_lnk( ztrds, 'T', 1. )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_zdf, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_zdf, ztrds )
          CALL wrk_dealloc( jpi, jpj, jpk, ztrdt, ztrds )
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf_imp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf_imp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/trazdf_imp.F90	(revision 5075)
@@ -120,6 +120,10 @@
             ELSE                                            ;   zwt(:,:,2:jpk) = fsavs(:,:,2:jpk)
             ENDIF
-            zwt(:,:,1) = 0._wp
-            !
+            DO jj=1, jpj
+               DO ji=1, jpi
+                  zwt(ji,jj,1:mikt(ji,jj)) = 0._wp
+               END DO
+            END DO
+!
 #if defined key_ldfslp
             ! isoneutral diffusion: add the contribution 
@@ -180,11 +184,7 @@
             DO jj = 2, jpjm1
                DO ji = fs_2, fs_jpim1
-                  zwt(ji,jj,1) = zwd(ji,jj,1)
-               END DO
-            END DO
-            DO jk = 2, jpkm1
-               DO jj = 2, jpjm1
-                  DO ji = fs_2, fs_jpim1
-                    zwt(ji,jj,jk) = zwd(ji,jj,jk) - zwi(ji,jj,jk) * zws(ji,jj,jk-1) / zwt(ji,jj,jk-1)
+                  zwt(ji,jj,1:mikt(ji,jj)) = zwd(ji,jj,1:mikt(ji,jj))
+                  DO jk = mikt(ji,jj)+1, jpkm1
+                     zwt(ji,jj,jk) = zwd(ji,jj,jk) - zwi(ji,jj,jk) * zws(ji,jj,jk-1) / zwt(ji,jj,jk-1)
                   END DO
                END DO
@@ -196,12 +196,9 @@
          DO jj = 2, jpjm1
             DO ji = fs_2, fs_jpim1
-               ze3tb = ( 1. - r_vvl ) + r_vvl * fse3t_b(ji,jj,1)
-               ze3tn = ( 1. - r_vvl ) + r_vvl * fse3t(ji,jj,1)
-               pta(ji,jj,1,jn) = ze3tb * ptb(ji,jj,1,jn) + p2dt(1) * ze3tn * pta(ji,jj,1,jn)
-            END DO
-         END DO
-         DO jk = 2, jpkm1
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1
+               ze3tb = ( 1. - r_vvl ) + r_vvl * fse3t_b(ji,jj,mikt(ji,jj))
+               ze3tn = ( 1. - r_vvl ) + r_vvl * fse3t(ji,jj,mikt(ji,jj))
+               pta(ji,jj,mikt(ji,jj),jn) = ze3tb * ptb(ji,jj,mikt(ji,jj),jn)                     &
+                  &                      + p2dt(mikt(ji,jj)) * ze3tn * pta(ji,jj,mikt(ji,jj),jn)
+               DO jk = mikt(ji,jj)+1, jpkm1
                   ze3tb = ( 1. - r_vvl ) + r_vvl * fse3t_b(ji,jj,jk)
                   ze3tn = ( 1. - r_vvl ) + r_vvl * fse3t  (ji,jj,jk)
@@ -216,9 +213,5 @@
             DO ji = fs_2, fs_jpim1
                pta(ji,jj,jpkm1,jn) = pta(ji,jj,jpkm1,jn) / zwt(ji,jj,jpkm1) * tmask(ji,jj,jpkm1)
-            END DO
-         END DO
-         DO jk = jpk-2, 1, -1
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1
+               DO jk = jpk-2, mikt(ji,jj), -1
                   pta(ji,jj,jk,jn) = ( pta(ji,jj,jk,jn) - zws(ji,jj,jk) * pta(ji,jj,jk+1,jn) )   &
                      &             / zwt(ji,jj,jk) * tmask(ji,jj,jk)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/zpshde.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/zpshde.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRA/zpshde.F90	(revision 5075)
@@ -40,5 +40,6 @@
 
    SUBROUTINE zps_hde( kt, kjpt, pta, pgtu, pgtv,   &
-                                 prd, pgru, pgrv    )
+      &                          prd, pgru, pgrv, pmru, pmrv, pgzu, pgzv, pge3ru, pge3rv,  &
+      &                   sgtu, sgtv, sgru, sgrv, smru, smrv, sgzu, sgzv, sge3ru, sge3rv )
       !!----------------------------------------------------------------------
       !!                     ***  ROUTINE zps_hde  ***
@@ -74,46 +75,58 @@
       !!          Idem for di(s) and dj(s)          
       !!
-      !!      For rho, we call eos_insitu_2d which will compute rd~(t~,s~) at 
-      !!      the good depth zh from interpolated T and S for the different
-      !!      formulation of the equation of state (eos).
+      !!      For rho, we call eos which will compute rd~(t~,s~) at the right
+      !!      depth zh from interpolated T and S for the different formulations
+      !!      of the equation of state (eos).
       !!      Gradient formulation for rho :
-      !!          di(rho) = rd~ - rd(i,j,k) or rd(i+1,j,k) - rd~
+      !!          di(rho) = rd~ - rd(i,j,k)   or   rd(i+1,j,k) - rd~
       !!
-      !! ** Action  : - pgtu, pgtv: horizontal gradient of tracer at u- & v-points
-      !!              - pgru, pgrv: horizontal gradient of rho (if present) at u- & v-points 
+      !! ** Action  : compute for top and bottom interfaces
+      !!              - pgtu, pgtv, sgtu, sgtv: horizontal gradient of tracer at u- & v-points
+      !!              - pgru, pgrv, sgru, sgtv: horizontal gradient of rho (if present) at u- & v-points
+      !!              - pmru, pmrv, smru, smrv: horizontal sum of rho at u- & v- point (used in dynhpg with vvl)
+      !!              - pgzu, pgzv, sgzu, sgzv: horizontal gradient of z at u- and v- point (used in dynhpg with vvl)
+      !!              - pge3ru, pge3rv, sge3ru, sge3rv: horizontal gradient of rho weighted by local e3w at u- & v-points 
       !!----------------------------------------------------------------------
-      !
       INTEGER                              , INTENT(in   )           ::  kt          ! ocean time-step index
       INTEGER                              , INTENT(in   )           ::  kjpt        ! number of tracers
       REAL(wp), DIMENSION(jpi,jpj,jpk,kjpt), INTENT(in   )           ::  pta         ! 4D tracers fields
       REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(  out)           ::  pgtu, pgtv  ! hor. grad. of ptra at u- & v-pts 
+      REAL(wp), DIMENSION(jpi,jpj,    kjpt), INTENT(  out)           ::  sgtu, sgtv  ! hor. grad. of stra at u- & v-pts (ISF)
       REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(in   ), OPTIONAL ::  prd         ! 3D density anomaly fields
-      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pgru, pgrv  ! hor. grad. of prd at u- & v-pts 
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pgru, pgrv      ! hor. grad of prd at u- & v-pts (bottom)
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pmru, pmrv      ! hor. sum  of prd at u- & v-pts (bottom)
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pgzu, pgzv      ! hor. grad of z   at u- & v-pts (bottom)
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  pge3ru, pge3rv  ! hor. grad of prd weighted by local e3w at u- & v-pts (bottom)
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  sgru, sgrv      ! hor. grad of prd at u- & v-pts (top)
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  smru, smrv      ! hor. sum  of prd at u- & v-pts (top)
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  sgzu, sgzv      ! hor. grad of z   at u- & v-pts (top)
+      REAL(wp), DIMENSION(jpi,jpj         ), INTENT(  out), OPTIONAL ::  sge3ru, sge3rv  ! hor. grad of prd weighted by local e3w at u- & v-pts (top)
       !
       INTEGER  ::   ji, jj, jn      ! Dummy loop indices
-      INTEGER  ::   iku, ikv, ikum1, ikvm1   ! partial step level (ocean bottom level) at u- and v-points
-      REAL(wp) ::  ze3wu, ze3wv, zmaxu, zmaxv  ! temporary scalars
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::  zri, zrj, zhi, zhj
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::  zti, ztj    ! interpolated value of tracer
+      INTEGER  ::   iku, ikv, ikum1, ikvm1,ikup1, ikvp1   ! partial step level (ocean bottom level) at u- and v-points
+      REAL(wp) ::  ze3wu, ze3wv, zmaxu, zmaxv, zdzwu, zdzwv, zdzwuip1, zdzwvjp1  ! temporary scalars
+      REAL(wp), DIMENSION(jpi,jpj)      ::  zri, zrj, zhi, zhj   ! NB: 3rd dim=1 to use eos
+      REAL(wp), DIMENSION(jpi,jpj,kjpt) ::  zti, ztj             ! 
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start( 'zps_hde')
       !
-      CALL wrk_alloc( jpi, jpj,       zri, zrj, zhi, zhj ) 
-      CALL wrk_alloc( jpi, jpj, kjpt, zti, ztj           ) 
+      pgtu(:,:,:)=0.0_wp ; pgtv(:,:,:)=0.0_wp ;
+      sgtu(:,:,:)=0.0_wp ; sgtv(:,:,:)=0.0_wp ;
+      zti (:,:,:)=0.0_wp ; ztj (:,:,:)=0.0_wp ;
+      zhi (:,:  )=0.0_wp ; zhj (:,:  )=0.0_wp ;
       !
       DO jn = 1, kjpt      !==   Interpolation of tracers at the last ocean level   ==!
          !
-# if defined key_vectopt_loop
-         jj = 1
-         DO ji = 1, jpij-jpi   ! vector opt. (forced unrolled)
-# else
-         DO jj = 1, jpjm1
-            DO ji = 1, jpim1
-# endif
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
                iku = mbku(ji,jj)   ;   ikum1 = MAX( iku - 1 , 1 )    ! last and before last ocean level at u- & v-points
                ikv = mbkv(ji,jj)   ;   ikvm1 = MAX( ikv - 1 , 1 )    ! if level first is a p-step, ik.m1=1
-               ze3wu = fse3w(ji+1,jj  ,iku) - fse3w(ji,jj,iku)
-               ze3wv = fse3w(ji  ,jj+1,ikv) - fse3w(ji,jj,ikv)
+               ! (ISF) case partial step top and bottom in adjacent cell in vertical
+               ! cannot used e3w because if 2 cell water column, we have ps at top and bottom
+               ! in this case e3w(i,j) - e3w(i,j+1) is not the distance between Tj~ and Tj
+               ! the only common depth between cells (i,j) and (i,j+1) is gdepw_0
+               ze3wu  = (gdept_0(ji+1,jj,iku) - gdepw_0(ji+1,jj,iku)) - (gdept_0(ji,jj,iku) - gdepw_0(ji,jj,iku))
+               ze3wv  = (gdept_0(ji,jj+1,ikv) - gdepw_0(ji,jj+1,ikv)) - (gdept_0(ji,jj,ikv) - gdepw_0(ji,jj,ikv))
                !
                ! i- direction
@@ -121,13 +134,13 @@
                   zmaxu =  ze3wu / fse3w(ji+1,jj,iku)
                   ! interpolated values of tracers
-                  zti(ji,jj,jn) = pta(ji+1,jj,iku,jn) + zmaxu * ( pta(ji+1,jj,ikum1,jn) - pta(ji+1,jj,iku,jn) )
+                  zti (ji,jj,jn) = pta(ji+1,jj,iku,jn) + zmaxu * ( pta(ji+1,jj,ikum1,jn) - pta(ji+1,jj,iku,jn) )
                   ! gradient of  tracers
-                  pgtu(ji,jj,jn) = umask(ji,jj,1) * ( zti(ji,jj,jn) - pta(ji,jj,iku,jn) )
+                  pgtu(ji,jj,jn) = umask(ji,jj,iku) * ( zti(ji,jj,jn) - pta(ji,jj,iku,jn) )
                ELSE                           ! case 2
                   zmaxu = -ze3wu / fse3w(ji,jj,iku)
                   ! interpolated values of tracers
-                  zti(ji,jj,jn) = pta(ji,jj,iku,jn) + zmaxu * ( pta(ji,jj,ikum1,jn) - pta(ji,jj,iku,jn) )
-                  ! gradient of tracers
-                  pgtu(ji,jj,jn) = umask(ji,jj,1) * ( pta(ji+1,jj,iku,jn) - zti(ji,jj,jn) )
+                  zti (ji,jj,jn) = pta(ji,jj,iku,jn) + zmaxu * ( pta(ji,jj,ikum1,jn) - pta(ji,jj,iku,jn) )
+                  ! gradient of tracers
+                  pgtu(ji,jj,jn) = umask(ji,jj,iku) * ( pta(ji+1,jj,iku,jn) - zti(ji,jj,jn) )
                ENDIF
                !
@@ -136,17 +149,15 @@
                   zmaxv =  ze3wv / fse3w(ji,jj+1,ikv)
                   ! interpolated values of tracers
-                  ztj(ji,jj,jn) = pta(ji,jj+1,ikv,jn) + zmaxv * ( pta(ji,jj+1,ikvm1,jn) - pta(ji,jj+1,ikv,jn) )
-                  ! gradient of tracers
-                  pgtv(ji,jj,jn) = vmask(ji,jj,1) * ( ztj(ji,jj,jn) - pta(ji,jj,ikv,jn) )
+                  ztj (ji,jj,jn) = pta(ji,jj+1,ikv,jn) + zmaxv * ( pta(ji,jj+1,ikvm1,jn) - pta(ji,jj+1,ikv,jn) )
+                  ! gradient of tracers
+                  pgtv(ji,jj,jn) = vmask(ji,jj,ikv) * ( ztj(ji,jj,jn) - pta(ji,jj,ikv,jn) )
                ELSE                           ! case 2
                   zmaxv =  -ze3wv / fse3w(ji,jj,ikv)
                   ! interpolated values of tracers
-                  ztj(ji,jj,jn) = pta(ji,jj,ikv,jn) + zmaxv * ( pta(ji,jj,ikvm1,jn) - pta(ji,jj,ikv,jn) )
-                  ! gradient of tracers
-                  pgtv(ji,jj,jn) = vmask(ji,jj,1) * ( pta(ji,jj+1,ikv,jn) - ztj(ji,jj,jn) )
-               ENDIF
-# if ! defined key_vectopt_loop
-            END DO
-# endif
+                  ztj (ji,jj,jn) = pta(ji,jj,ikv,jn) + zmaxv * ( pta(ji,jj,ikvm1,jn) - pta(ji,jj,ikv,jn) )
+                  ! gradient of tracers
+                  pgtv(ji,jj,jn) = vmask(ji,jj,ikv) * ( pta(ji,jj+1,ikv,jn) - ztj(ji,jj,jn) )
+               ENDIF
+            END DO
          END DO
          CALL lbc_lnk( pgtu(:,:,jn), 'U', -1. )   ;   CALL lbc_lnk( pgtv(:,:,jn), 'V', -1. )   ! Lateral boundary cond.
@@ -156,26 +167,24 @@
       ! horizontal derivative of density anomalies (rd)
       IF( PRESENT( prd ) ) THEN         ! depth of the partial step level
-# if defined key_vectopt_loop
-         jj = 1
-         DO ji = 1, jpij-jpi   ! vector opt. (forced unrolled)
-# else
-         DO jj = 1, jpjm1
-            DO ji = 1, jpim1
-# endif
+         pgru(:,:)=0.0_wp   ; pgrv(:,:)=0.0_wp ; 
+         pgzu(:,:)=0.0_wp   ; pgzv(:,:)=0.0_wp ;
+         pmru(:,:)=0.0_wp   ; pmru(:,:)=0.0_wp ;
+         pge3ru(:,:)=0.0_wp ; pge3rv(:,:)=0.0_wp ;
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
                iku = mbku(ji,jj)
                ikv = mbkv(ji,jj)
-               ze3wu  = fse3w(ji+1,jj  ,iku) - fse3w(ji,jj,iku)
-               ze3wv  = fse3w(ji  ,jj+1,ikv) - fse3w(ji,jj,ikv)
-               IF( ze3wu >= 0._wp ) THEN   ;   zhi(ji,jj) = fsdept(ji  ,jj,iku)     ! i-direction: case 1
-               ELSE                        ;   zhi(ji,jj) = fsdept(ji+1,jj,iku)     ! -     -      case 2
-               ENDIF
-               IF( ze3wv >= 0._wp ) THEN   ;   zhj(ji,jj) = fsdept(ji,jj  ,ikv)     ! j-direction: case 1
-               ELSE                        ;   zhj(ji,jj) = fsdept(ji,jj+1,ikv)     ! -     -      case 2
-               ENDIF
-# if ! defined key_vectopt_loop
-            END DO
-# endif
-         END DO
-
+               ze3wu  = (gdept_0(ji+1,jj,iku) - gdepw_0(ji+1,jj,iku)) - (gdept_0(ji,jj,iku) - gdepw_0(ji,jj,iku))
+               ze3wv  = (gdept_0(ji,jj+1,ikv) - gdepw_0(ji,jj+1,ikv)) - (gdept_0(ji,jj,ikv) - gdepw_0(ji,jj,ikv))
+
+               IF( ze3wu >= 0._wp ) THEN   ;   zhi(ji,jj) = fsdept(ji+1,jj,iku) - ze3wu     ! i-direction: case 1
+               ELSE                        ;   zhi(ji,jj) = fsdept(ji  ,jj,iku) + ze3wu    ! -     -      case 2
+               ENDIF
+               IF( ze3wv >= 0._wp ) THEN   ;   zhj(ji,jj) = fsdept(ji,jj+1,ikv) - ze3wv    ! j-direction: case 1
+               ELSE                        ;   zhj(ji,jj) = fsdept(ji,jj  ,ikv) + ze3wv    ! -     -      case 2
+               ENDIF
+            END DO
+         END DO
+         
          ! Compute interpolated rd from zti, ztj for the 2 cases at the depth of the partial
          ! step and store it in  zri, zrj for each  case
@@ -184,31 +193,170 @@
 
          ! Gradient of density at the last level 
-# if defined key_vectopt_loop
-         jj = 1
-         DO ji = 1, jpij-jpi   ! vector opt. (forced unrolled)
-# else
-         DO jj = 1, jpjm1
-            DO ji = 1, jpim1
-# endif
-               iku = mbku(ji,jj)
-               ikv = mbkv(ji,jj)
-               ze3wu  = fse3w(ji+1,jj  ,iku) - fse3w(ji,jj,iku)
-               ze3wv  = fse3w(ji  ,jj+1,ikv) - fse3w(ji,jj,ikv)
-               IF( ze3wu >= 0._wp ) THEN   ;   pgru(ji,jj) = umask(ji,jj,1) * ( zri(ji  ,jj) - prd(ji,jj,iku) )   ! i: 1
-               ELSE                        ;   pgru(ji,jj) = umask(ji,jj,1) * ( prd(ji+1,jj,iku) - zri(ji,jj) )   ! i: 2
-               ENDIF
-               IF( ze3wv >= 0._wp ) THEN   ;   pgrv(ji,jj) = vmask(ji,jj,1) * ( zrj(ji,jj  ) - prd(ji,jj,ikv) )   ! j: 1
-               ELSE                        ;   pgrv(ji,jj) = vmask(ji,jj,1) * ( prd(ji,jj+1,ikv) - zrj(ji,jj) )   ! j: 2
-               ENDIF
-# if ! defined key_vectopt_loop
-            END DO
-# endif
-         END DO
-         CALL lbc_lnk( pgru , 'U', -1. )   ;   CALL lbc_lnk( pgrv , 'V', -1. )   ! Lateral boundary conditions
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               iku = mbku(ji,jj) ; ikum1 = MAX( iku - 1 , 1 )    ! last and before last ocean level at u- & v-points
+               ikv = mbkv(ji,jj) ; ikvm1 = MAX( ikv - 1 , 1 )    ! last and before last ocean level at u- & v-points
+               ze3wu  = (gdept_0(ji+1,jj,iku) - gdepw_0(ji+1,jj,iku)) - (gdept_0(ji,jj,iku) - gdepw_0(ji,jj,iku))
+               ze3wv  = (gdept_0(ji,jj+1,ikv) - gdepw_0(ji,jj+1,ikv)) - (gdept_0(ji,jj,ikv) - gdepw_0(ji,jj,ikv))
+               IF( ze3wu >= 0._wp ) THEN 
+                  pgzu(ji,jj) = (fsde3w(ji+1,jj,iku) - ze3wu) - fsde3w(ji,jj,iku)
+                  pgru(ji,jj) = umask(ji,jj,iku) * ( zri(ji  ,jj) - prd(ji,jj,iku) )   ! i: 1
+                  pmru(ji,jj) = umask(ji,jj,iku) * ( zri(ji  ,jj) + prd(ji,jj,iku) )   ! i: 1 
+                  pge3ru(ji,jj) = umask(ji,jj,iku)                                                                  &
+                                * ( (fse3w(ji+1,jj,iku) - ze3wu )* ( zri(ji  ,jj    ) + prd(ji+1,jj,ikum1) + 2._wp) &
+                                   - fse3w(ji  ,jj,iku)          * ( prd(ji  ,jj,iku) + prd(ji  ,jj,ikum1) + 2._wp) )  ! j: 2
+               ELSE  
+                  pgzu(ji,jj) = fsde3w(ji+1,jj,iku) - (fsde3w(ji,jj,iku) + ze3wu)
+                  pgru(ji,jj) = umask(ji,jj,iku) * ( prd(ji+1,jj,iku) - zri(ji,jj) )   ! i: 2
+                  pmru(ji,jj) = umask(ji,jj,iku) * ( prd(ji+1,jj,iku) + zri(ji,jj) )   ! i: 2
+                  pge3ru(ji,jj) = umask(ji,jj,iku)                                                                  &
+                                * (  fse3w(ji+1,jj,iku)          * ( prd(ji+1,jj,iku) + prd(ji+1,jj,ikum1) + 2._wp) &
+                                   -(fse3w(ji  ,jj,iku) + ze3wu) * ( zri(ji  ,jj    ) + prd(ji  ,jj,ikum1) + 2._wp) )  ! j: 2
+               ENDIF
+               IF( ze3wv >= 0._wp ) THEN
+                  pgzv(ji,jj) = (fsde3w(ji,jj+1,ikv) - ze3wv) - fsde3w(ji,jj,ikv) 
+                  pgrv(ji,jj) = vmask(ji,jj,ikv) * ( zrj(ji,jj  ) - prd(ji,jj,ikv) )   ! j: 1
+                  pmrv(ji,jj) = vmask(ji,jj,ikv) * ( zrj(ji,jj  ) + prd(ji,jj,ikv) )   ! j: 1
+                  pge3rv(ji,jj) = vmask(ji,jj,ikv)                                                                  &
+                                * ( (fse3w(ji,jj+1,ikv) - ze3wv )* ( zrj(ji,jj      ) + prd(ji,jj+1,ikvm1) + 2._wp) &
+                                   - fse3w(ji,jj  ,ikv)          * ( prd(ji,jj  ,ikv) + prd(ji,jj  ,ikvm1) + 2._wp) )  ! j: 2
+               ELSE 
+                  pgzv(ji,jj) = fsde3w(ji,jj+1,ikv) - (fsde3w(ji,jj,ikv) + ze3wv)
+                  pgrv(ji,jj) = vmask(ji,jj,ikv) * ( prd(ji,jj+1,ikv) - zrj(ji,jj) )   ! j: 2
+                  pmrv(ji,jj) = vmask(ji,jj,ikv) * ( prd(ji,jj+1,ikv) + zrj(ji,jj) )   ! j: 2
+                  pge3rv(ji,jj) = vmask(ji,jj,ikv)                                                                  &
+                                * (  fse3w(ji,jj+1,ikv)          * ( prd(ji,jj+1,ikv) + prd(ji,jj+1,ikvm1) + 2._wp) &
+                                   -(fse3w(ji,jj  ,ikv) + ze3wv) * ( zrj(ji,jj      ) + prd(ji,jj  ,ikvm1) + 2._wp) )  ! j: 2
+               ENDIF
+            END DO
+         END DO
+         CALL lbc_lnk( pgru   , 'U', -1. )   ;   CALL lbc_lnk( pgrv   , 'V', -1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( pmru   , 'U',  1. )   ;   CALL lbc_lnk( pmrv   , 'V',  1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( pgzu   , 'U', -1. )   ;   CALL lbc_lnk( pgzv   , 'V', -1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( pge3ru , 'U', -1. )   ;   CALL lbc_lnk( pge3rv , 'V', -1. )   ! Lateral boundary conditions
          !
       END IF
-      !
-      CALL wrk_dealloc( jpi, jpj,       zri, zrj, zhi, zhj ) 
-      CALL wrk_dealloc( jpi, jpj, kjpt, zti, ztj           ) 
+         ! (ISH)  compute grui and gruvi
+      DO jn = 1, kjpt      !==   Interpolation of tracers at the last ocean level   ==!            !
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               iku = miku(ji,jj)   ;  ikup1 = miku(ji,jj) + 1
+               ikv = mikv(ji,jj)   ;  ikvp1 = mikv(ji,jj) + 1
+               !
+               ! (ISF) case partial step top and bottom in adjacent cell in vertical
+               ! cannot used e3w because if 2 cell water column, we have ps at top and bottom
+               ! in this case e3w(i,j) - e3w(i,j+1) is not the distance between Tj~ and Tj
+               ! the only common depth between cells (i,j) and (i,j+1) is gdepw_0
+               ze3wu  = (gdepw_0(ji+1,jj,iku+1) - gdept_0(ji+1,jj,iku)) - (gdepw_0(ji,jj,iku+1) - gdept_0(ji,jj,iku)) 
+               ze3wv  = (gdepw_0(ji,jj+1,ikv+1) - gdept_0(ji,jj+1,ikv)) - (gdepw_0(ji,jj,ikv+1) - gdept_0(ji,jj,ikv))
+               ! i- direction
+               IF( ze3wu >= 0._wp ) THEN      ! case 1
+                  zmaxu = ze3wu / fse3w(ji+1,jj,iku+1)
+                  ! interpolated values of tracers
+                  zti(ji,jj,jn) = pta(ji+1,jj,iku,jn) + zmaxu * ( pta(ji+1,jj,iku+1,jn) - pta(ji+1,jj,iku,jn) )
+                  ! gradient of tracers
+                  sgtu(ji,jj,jn) = umask(ji,jj,iku) * ( zti(ji,jj,jn) - pta(ji,jj,iku,jn) )
+               ELSE                           ! case 2
+                  zmaxu = - ze3wu / fse3w(ji,jj,iku+1)
+                  ! interpolated values of tracers
+                  zti(ji,jj,jn) = pta(ji,jj,iku,jn) + zmaxu * ( pta(ji,jj,iku+1,jn) - pta(ji,jj,iku,jn) )
+                  ! gradient of  tracers
+                  sgtu(ji,jj,jn) = umask(ji,jj,iku) * ( pta(ji+1,jj,iku,jn) - zti(ji,jj,jn) )
+               ENDIF
+               !
+               ! j- direction
+               IF( ze3wv >= 0._wp ) THEN      ! case 1
+                  zmaxv =  ze3wv / fse3w(ji,jj+1,ikv+1)
+                  ! interpolated values of tracers
+                  ztj(ji,jj,jn) = pta(ji,jj+1,ikv,jn) + zmaxv * ( pta(ji,jj+1,ikv+1,jn) - pta(ji,jj+1,ikv,jn) )
+                  ! gradient of tracers
+                  sgtv(ji,jj,jn) = vmask(ji,jj,ikv) * ( ztj(ji,jj,jn) - pta(ji,jj,ikv,jn) )
+               ELSE                           ! case 2
+                  zmaxv =  - ze3wv / fse3w(ji,jj,ikv+1)
+                  ! interpolated values of tracers
+                  ztj(ji,jj,jn) = pta(ji,jj,ikv,jn) + zmaxv * ( pta(ji,jj,ikv+1,jn) - pta(ji,jj,ikv,jn) )
+                  ! gradient of tracers
+                  sgtv(ji,jj,jn) = vmask(ji,jj,ikv) * ( pta(ji,jj+1,ikv,jn) - ztj(ji,jj,jn) )
+               ENDIF
+            END DO!!
+         END DO!!
+         CALL lbc_lnk( sgtu(:,:,jn), 'U', -1. )   ;   CALL lbc_lnk( sgtv(:,:,jn), 'V', -1. )   ! Lateral boundary cond.
+         !
+      END DO
+
+      ! horizontal derivative of density anomalies (rd)
+      IF( PRESENT( prd ) ) THEN         ! depth of the partial step level
+         sgru(:,:)  =0.0_wp ; sgrv(:,:)  =0.0_wp ;
+         sgzu(:,:)  =0.0_wp ; sgzv(:,:)  =0.0_wp ;
+         smru(:,:)  =0.0_wp ; smru(:,:)  =0.0_wp ;
+         sge3ru(:,:)=0.0_wp ; sge3rv(:,:)=0.0_wp ;
+
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               iku = miku(ji,jj)
+               ikv = mikv(ji,jj)
+               ze3wu  = (gdepw_0(ji+1,jj,iku+1) - gdept_0(ji+1,jj,iku)) - (gdepw_0(ji,jj,iku+1) - gdept_0(ji,jj,iku))
+               ze3wv  = (gdepw_0(ji,jj+1,ikv+1) - gdept_0(ji,jj+1,ikv)) - (gdepw_0(ji,jj,ikv+1) - gdept_0(ji,jj,ikv))
+
+               IF( ze3wu >= 0._wp ) THEN   ;   zhi(ji,jj) = fsdept(ji+1,jj,iku) + ze3wu    ! i-direction: case 1
+               ELSE                        ;   zhi(ji,jj) = fsdept(ji  ,jj,iku) - ze3wu    ! -     -      case 2
+               ENDIF
+               IF( ze3wv >= 0._wp ) THEN   ;   zhj(ji,jj) = fsdept(ji,jj+1,ikv) + ze3wv    ! j-direction: case 1
+               ELSE                        ;   zhj(ji,jj) = fsdept(ji,jj  ,ikv) - ze3wv    ! -     -      case 2
+               ENDIF
+            END DO
+         END DO
+
+         ! Compute interpolated rd from zti, ztj for the 2 cases at the depth of the partial
+         ! step and store it in  zri, zrj for each  case
+         CALL eos( zti, zhi, zri )  
+         CALL eos( ztj, zhj, zrj )
+
+         ! Gradient of density at the last level 
+         DO jj = 1, jpjm1
+            DO ji = 1, jpim1
+               iku = miku(ji,jj) ; ikup1 = miku(ji,jj) + 1
+               ikv = mikv(ji,jj) ; ikvp1 = mikv(ji,jj) + 1
+               ze3wu  = (gdepw_0(ji+1,jj,iku+1) - gdept_0(ji+1,jj,iku)) - (gdepw_0(ji,jj,iku+1) - gdept_0(ji,jj,iku))
+               ze3wv  = (gdepw_0(ji,jj+1,ikv+1) - gdept_0(ji,jj+1,ikv)) - (gdepw_0(ji,jj,ikv+1) - gdept_0(ji,jj,ikv))
+               IF( ze3wu >= 0._wp ) THEN
+                 sgzu  (ji,jj) = (fsde3w(ji+1,jj,iku) + ze3wu) - fsde3w(ji,jj,iku)
+                 sgru  (ji,jj) = umask(ji,jj,iku)   * ( zri(ji,jj) - prd(ji,jj,iku) )          ! i: 1
+                 smru  (ji,jj) = umask(ji,jj,iku)   * ( zri(ji,jj) + prd(ji,jj,iku) )          ! i: 1 
+                 sge3ru(ji,jj) = umask(ji,jj,iku+1)                                                                  &
+                                * ( (fse3w(ji+1,jj,iku+1) - ze3wu) * (zri(ji,jj    ) + prd(ji+1,jj,iku+1) + 2._wp)   &
+                                   - fse3w(ji  ,jj,iku+1)          * (prd(ji,jj,iku) + prd(ji  ,jj,iku+1) + 2._wp)   ) ! i: 1
+               ELSE
+                 sgzu  (ji,jj) = fsde3w(ji+1,jj,iku) - (fsde3w(ji,jj,iku) - ze3wu)
+                 sgru  (ji,jj) = umask(ji,jj,iku)   * ( prd(ji+1,jj,iku) - zri(ji,jj) )      ! i: 2
+                 smru  (ji,jj) = umask(ji,jj,iku)   * ( prd(ji+1,jj,iku) + zri(ji,jj) )      ! i: 2
+                 sge3ru(ji,jj) = umask(ji,jj,iku+1)                                                                   &
+                                * (  fse3w(ji+1,jj,iku+1)          * (prd(ji+1,jj,iku) + prd(ji+1,jj,iku+1) + 2._wp)  &
+                                   -(fse3w(ji  ,jj,iku+1) + ze3wu) * (zri(ji,jj      ) + prd(ji  ,jj,iku+1) + 2._wp)  )     ! i: 2
+               ENDIF
+               IF( ze3wv >= 0._wp ) THEN
+                 sgzv  (ji,jj) = (fsde3w(ji,jj+1,ikv) + ze3wv) - fsde3w(ji,jj,ikv) 
+                 sgrv  (ji,jj) = vmask(ji,jj,ikv)   * ( zrj(ji,jj  ) - prd(ji,jj,ikv) )        ! j: 1
+                 smrv  (ji,jj) = vmask(ji,jj,ikv)   * ( zrj(ji,jj  ) + prd(ji,jj,ikv) )        ! j: 1
+                 sge3rv(ji,jj) = vmask(ji,jj,ikv+1)                                                                  & 
+                                * ( (fse3w(ji,jj+1,ikv+1) - ze3wv) * ( zrj(ji,jj    ) + prd(ji,jj+1,ikv+1) + 2._wp)  &
+                                   - fse3w(ji,jj  ,ikv+1)          * ( prd(ji,jj,ikv) + prd(ji,jj  ,ikv+1) + 2._wp)  ) ! j: 1
+                                  ! + 2 due to the formulation in density and not in anomalie in hpg sco
+               ELSE
+                 sgzv  (ji,jj) = fsde3w(ji,jj+1,ikv) - (fsde3w(ji,jj,ikv) - ze3wv)
+                 sgrv  (ji,jj) = vmask(ji,jj,ikv)   * ( prd(ji,jj+1,ikv) - zrj(ji,jj) )     ! j: 2
+                 smrv  (ji,jj) = vmask(ji,jj,ikv)   * ( prd(ji,jj+1,ikv) + zrj(ji,jj) )     ! j: 2
+                 sge3rv(ji,jj) = vmask(ji,jj,ikv+1)                                                                   &
+                                * (  fse3w(ji,jj+1,ikv+1)          * ( prd(ji,jj+1,ikv) + prd(ji,jj+1,ikv+1) + 2._wp) &
+                                   -(fse3w(ji,jj  ,ikv+1) + ze3wv) * ( zrj(ji,jj      ) + prd(ji,jj  ,ikv+1) + 2._wp) )  ! j: 2
+               ENDIF
+            END DO
+         END DO
+         CALL lbc_lnk( sgru   , 'U', -1. )   ;   CALL lbc_lnk( sgrv   , 'V', -1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( smru   , 'U',  1. )   ;   CALL lbc_lnk( smrv   , 'V',  1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( sgzu   , 'U', -1. )   ;   CALL lbc_lnk( sgzv   , 'V', -1. )   ! Lateral boundary conditions
+         CALL lbc_lnk( sge3ru , 'U', -1. )   ;   CALL lbc_lnk( sge3rv , 'V', -1. )   ! Lateral boundary conditions
+         !
+      END IF  
       !
       IF( nn_timing == 1 )  CALL timing_stop( 'zps_hde')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trd_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trd_oce.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trd_oce.F90	(revision 5075)
@@ -0,0 +1,81 @@
+MODULE trd_oce
+   !!======================================================================
+   !!                   ***  MODULE trd_oce  ***
+   !! Ocean trends :   set tracer and momentum trend variables
+   !!======================================================================
+   !! History :  1.0  !  2004-08  (C. Talandier) Original code
+   !!----------------------------------------------------------------------
+   USE par_oce                 ! ocean parameters
+   USE trdmxl_oce              ! ocean active mixed layer tracers trends variables
+   USE trdvor_oce              ! ocean vorticity trends variables
+
+   IMPLICIT NONE
+   PUBLIC
+
+   !                                                   !!* Namelist namtrd:  diagnostics on dynamics/tracer trends *
+   LOGICAL , PUBLIC  ::   ln_dyn_trd   = .FALSE.        !: (T) 3D momentum             trends or (F) not
+   LOGICAL , PUBLIC  ::   ln_tra_trd   = .FALSE.        !: (T) 3D tracer               trends or (F) not
+   LOGICAL , PUBLIC  ::   ln_KE_trd    = .FALSE.        !: (T) 3D Kinetic   Energy     trends or (F) not
+   LOGICAL , PUBLIC  ::   ln_PE_trd    = .FALSE.        !: (T) 3D Potential Energy     trends or (F) not
+   LOGICAL , PUBLIC  ::   ln_vor_trd   = .FALSE.        !: (T) 3D barotropic vorticity trends or (F) not
+   LOGICAL , PUBLIC  ::   ln_glo_trd   = .FALSE.        !: (T) global domain averaged diag for T, T^2, KE, and PE
+   LOGICAL , PUBLIC  ::   ln_dyn_mxl   = .FALSE.        !: (T) 2D tracer   trends averaged over the mixed layer 
+   LOGICAL , PUBLIC  ::   ln_tra_mxl   = .FALSE.        !: (T) 2D momentum trends averaged over the mixed layer 
+   INTEGER , PUBLIC  ::   nn_trd       = 10             !: time step frequency for ln_glo_trd=T only
+
+   LOGICAL , PUBLIC ::   l_trdtra        !: tracers  trend flag (set from namelist in trdini)
+   LOGICAL , PUBLIC ::   l_trddyn        !: momentum trend flag (set from namelist in trdini)
+   
+# if ( defined key_trdtrc && defined key_iomput )  ||  defined key_trdmxl_trc
+   LOGICAL , PUBLIC ::   l_trdtrc = .TRUE.        !: tracers  trend flag
+# else
+   LOGICAL , PUBLIC ::   l_trdtrc = .FALSE.       !: tracers  trend flag
+# endif
+   !                                                  !!!* Active tracers trends indexes
+   INTEGER, PUBLIC, PARAMETER ::   jptot_tra  = 14     !: Total trend nb: change it when adding/removing one indice below
+   !                               ===============     !  
+   INTEGER, PUBLIC, PARAMETER ::   jptra_xad  =  1     !: x- horizontal advection
+   INTEGER, PUBLIC, PARAMETER ::   jptra_yad  =  2     !: y- horizontal advection
+   INTEGER, PUBLIC, PARAMETER ::   jptra_zad  =  3     !: z- vertical   advection
+   INTEGER, PUBLIC, PARAMETER ::   jptra_sad  =  4     !: z- vertical   advection
+   INTEGER, PUBLIC, PARAMETER ::   jptra_ldf  =  5     !: lateral       diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_zdf  =  6     !: vertical      diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jptra_zdfp =  7     !: "PURE" vert.  diffusion (ln_traldf_iso=T)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_bbc  =  8     !: Bottom Boundary Condition (geoth. heating) 
+   INTEGER, PUBLIC, PARAMETER ::   jptra_bbl  =  9     !: Bottom Boundary Layer (diffusive and/or advective)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_npc  = 10     !: non-penetrative convection treatment
+   INTEGER, PUBLIC, PARAMETER ::   jptra_dmp  = 11     !: internal restoring (damping)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_qsr  = 12     !: penetrative solar radiation
+   INTEGER, PUBLIC, PARAMETER ::   jptra_nsr  = 13     !: non solar radiation / C/D on salinity  (+runoff if ln_rnf=T)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_atf  = 14     !: Asselin time filter
+   !
+   !                                                  !!!* Passive tracers trends indices (use if "key_top" defined)
+   INTEGER, PUBLIC, PARAMETER ::   jptra_sms  = 15     !: sources m. sinks
+   INTEGER, PUBLIC, PARAMETER ::   jptra_radn = 16     !: corr. trn<0 in trcrad
+   INTEGER, PUBLIC, PARAMETER ::   jptra_radb = 17     !: corr. trb<0 in trcrad (like atf)
+   !
+   !                                                  !!!* Momentum trends indices
+   INTEGER, PUBLIC, PARAMETER ::   jptot_dyn  = 15     !: Total trend nb: change it when adding/removing one indice below
+   !                               ===============     !  
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_hpg  =  1     !: hydrostatic pressure gradient 
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_spg  =  2     !: surface     pressure gradient
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_keg  =  3     !: kinetic energy gradient  or horizontal advection
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_rvo  =  4     !: relative  vorticity      or metric term
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_pvo  =  5     !: planetary vorticity
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_zad  =  6     !: vertical advection
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_ldf  =  7     !: horizontal diffusion   
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_zdf  =  8     !: vertical   diffusion
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_bfr  =  9     !: bottom  stress 
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_atf  = 10     !: Asselin time filter
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_tau  = 11     !: surface stress
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_bfri = 12     !: implicit bottom friction (ln_bfrimp=.TRUE.)
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_ken  = 13     !: use for calculation of KE
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_spgflt  = 14  !: filter contribution to surface pressure gradient (spg_flt)
+   INTEGER, PUBLIC, PARAMETER ::   jpdyn_spgexp  = 15  !: explicit contribution to surface pressure gradient (spg_flt)
+   !
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: trd_oce.F90 3318 2012-02-25 15:50:01Z gm $
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!======================================================================
+END MODULE trd_oce
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trddyn.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trddyn.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trddyn.F90	(revision 5075)
@@ -0,0 +1,182 @@
+MODULE trddyn
+   !!======================================================================
+   !!                       ***  MODULE  trddyn  ***
+   !! Ocean diagnostics:  ocean dynamic trends
+   !!=====================================================================
+   !! History :  3.5  !  2012-02  (G. Madec) creation from trdmod: split DYN and TRA trends
+   !!                                        and manage  3D trends output for U, V, and KE
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trd_dyn       : manage the type of momentum trend diagnostics (3D I/O, domain averaged, KE)
+   !!   trd_dyn_iom   : output 3D momentum and/or tracer trends using IOM
+   !!   trd_dyn_init  : initialization step
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE zdf_oce        ! ocean vertical physics variables
+   USE trd_oce        ! trends: ocean variables
+   USE zdfbfr         ! bottom friction
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE phycst         ! physical constants
+   USE trdken         ! trends: Kinetic ENergy 
+   USE trdglo         ! trends: global domain averaged
+   USE trdvor         ! trends: vertical averaged vorticity 
+   USE trdmxl         ! trends: mixed layer averaged 
+   USE in_out_manager ! I/O manager
+   USE lbclnk         ! lateral boundary condition 
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE wrk_nemo       ! Memory allocation
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trd_dyn        ! called by all dynXX modules
+
+   !! * Substitutions
+#  include "domzgr_substitute.h90"
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: trddyn.F90 3325 2012-03-12 14:44:43Z gm $
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trd_dyn( putrd, pvtrd, ktrd, kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mod  ***
+      !! 
+      !! ** Purpose :   Dispatch momentum trend computation, e.g. 3D output, 
+      !!              integral constraints, barotropic vorticity, kinetic enrgy, 
+      !!              and/or mixed layer budget.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   putrd, pvtrd   ! U and V trends 
+      INTEGER                   , INTENT(in   ) ::   ktrd           ! trend index
+      INTEGER                   , INTENT(in   ) ::   kt             ! time step
+      !!----------------------------------------------------------------------
+      !
+      putrd(:,:,:) = putrd(:,:,:) * umask(:,:,:)                       ! mask the trends
+      pvtrd(:,:,:) = pvtrd(:,:,:) * vmask(:,:,:)
+      !
+
+!!gm NB : here a lbc_lnk should probably be added
+
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !   3D output of momentum and/or tracers trends using IOM interface
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( ln_dyn_trd )   CALL trd_dyn_iom( putrd, pvtrd, ktrd, kt )
+         
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !  Integral Constraints Properties for momentum and/or tracers trends
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( ln_glo_trd )   CALL trd_glo( putrd, pvtrd, ktrd, 'DYN', kt )
+
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !  Kinetic Energy trends
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      IF( ln_KE_trd  )   CALL trd_ken( putrd, pvtrd, ktrd, kt )
+
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      !  Vorticity trends
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      IF( ln_vor_trd )   CALL trd_vor( putrd, pvtrd, ktrd, kt )
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      !  Mixed layer trends for active tracers
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+!!gm      IF( ln_dyn_mxl )   CALL trd_mxl_dyn   
+      !
+   END SUBROUTINE trd_dyn
+
+
+   SUBROUTINE trd_dyn_iom( putrd, pvtrd, ktrd, kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_dyn_iom  ***
+      !! 
+      !! ** Purpose :   output 3D trends using IOM
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   putrd, pvtrd   ! U and V trends
+      INTEGER                   , INTENT(in   ) ::   ktrd           ! trend index
+      INTEGER                   , INTENT(in   ) ::   kt             ! time step
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      INTEGER ::   ikbu, ikbv   ! local integers
+      REAL(wp), POINTER, DIMENSION(:,:)   ::   z2dx, z2dy   ! 2D workspace 
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   z3dx, z3dy   ! 3D workspace 
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE( ktrd )
+      CASE( jpdyn_hpg )   ;   CALL iom_put( "utrd_hpg", putrd )    ! hydrostatic pressure gradient
+                              CALL iom_put( "vtrd_hpg", pvtrd )
+      CASE( jpdyn_spg )   ;   CALL iom_put( "utrd_spg", putrd )    ! surface pressure gradient
+                              CALL iom_put( "vtrd_spg", pvtrd )
+      CASE( jpdyn_spgexp );   CALL iom_put( "utrd_spgexp", putrd ) ! surface pressure gradient (explicit)
+                              CALL iom_put( "vtrd_spgexp", pvtrd )
+      CASE( jpdyn_spgflt );   CALL iom_put( "utrd_spgflt", putrd ) ! surface pressure gradient (filtered)
+                              CALL iom_put( "vtrd_spgflt", pvtrd )
+      CASE( jpdyn_pvo )   ;   CALL iom_put( "utrd_pvo", putrd )    ! planetary vorticity
+                              CALL iom_put( "vtrd_pvo", pvtrd )
+      CASE( jpdyn_rvo )   ;   CALL iom_put( "utrd_rvo", putrd )    ! relative  vorticity     (or metric term)
+                              CALL iom_put( "vtrd_rvo", pvtrd )
+      CASE( jpdyn_keg )   ;   CALL iom_put( "utrd_keg", putrd )    ! Kinetic Energy gradient (or had)
+                              CALL iom_put( "vtrd_keg", pvtrd )
+                              CALL wrk_alloc( jpi, jpj, jpk, z3dx, z3dy )
+                              z3dx(:,:,:) = 0._wp                  ! U.dxU & V.dyV (approximation)
+                              z3dy(:,:,:) = 0._wp
+                              DO jk = 1, jpkm1					   ! no mask as un,vn are masked
+                                 DO jj = 2, jpjm1
+                                    DO ji = 2, jpim1
+                                       z3dx(ji,jj,jk) = un(ji,jj,jk) * ( un(ji+1,jj,jk) - un(ji-1,jj,jk) ) / ( 2._wp * e1u(ji,jj) )
+                                       z3dy(ji,jj,jk) = vn(ji,jj,jk) * ( vn(ji,jj+1,jk) - vn(ji,jj-1,jk) ) / ( 2._wp * e2v(ji,jj) )
+                                    END DO
+                                 END DO
+                              END DO
+                              CALL lbc_lnk( z3dx, 'U', -1. )
+                              CALL lbc_lnk( z3dy, 'V', -1. )
+                              CALL iom_put( "utrd_udx", z3dx  )
+                              CALL iom_put( "vtrd_vdy", z3dy  )
+                              CALL wrk_dealloc( jpi, jpj, jpk, z3dx, z3dy )
+      CASE( jpdyn_zad )   ;   CALL iom_put( "utrd_zad", putrd )    ! vertical   advection
+                              CALL iom_put( "vtrd_zad", pvtrd )
+      CASE( jpdyn_ldf )   ;   CALL iom_put( "utrd_ldf", putrd )    ! lateral diffusion
+                              CALL iom_put( "vtrd_ldf", pvtrd )
+      CASE( jpdyn_zdf )   ;   CALL iom_put( "utrd_zdf", putrd )    ! vertical diffusion 
+                              CALL iom_put( "vtrd_zdf", pvtrd )
+                              !                                    ! wind stress trends
+                              CALL wrk_alloc( jpi, jpj, z2dx, z2dy )
+                              z2dx(:,:) = ( utau_b(:,:) + utau(:,:) ) / ( fse3u(:,:,1) * rau0 )
+                              z2dy(:,:) = ( vtau_b(:,:) + vtau(:,:) ) / ( fse3v(:,:,1) * rau0 )
+                              CALL iom_put( "utrd_tau", z2dx )
+                              CALL iom_put( "vtrd_tau", z2dy )
+                              CALL wrk_dealloc( jpi, jpj, z2dx, z2dy )
+      CASE( jpdyn_bfr )       ! called if ln_bfrimp=T
+                              CALL iom_put( "utrd_bfr", putrd )    ! bottom friction (explicit case)
+                              CALL iom_put( "vtrd_bfr", pvtrd )
+      CASE( jpdyn_atf )   ;   CALL iom_put( "utrd_atf", putrd )        ! asselin filter trends 
+                              CALL iom_put( "vtrd_atf", pvtrd )
+      CASE( jpdyn_bfri )  ;   IF( ln_bfrimp ) THEN                     ! bottom friction (implicit case)
+                              	CALL wrk_alloc( jpi, jpj, jpk, z3dx, z3dy )
+                              	z3dx(:,:,:) = 0._wp   ;   z3dy(:,:,:) = 0._wp  ! after velocity known (now filed at this stage)
+                              	DO jk = 1, jpkm1
+                                    DO jj = 2, jpjm1
+                                       DO ji = 2, jpim1
+                              	         ikbu = mbku(ji,jj)          ! deepest ocean u- & v-levels
+                                          ikbv = mbkv(ji,jj)
+                                          z3dx(ji,jj,jk) = bfrua(ji,jj) * un(ji,jj,ikbu) / fse3u(ji,jj,ikbu)
+                                          z3dy(ji,jj,jk) = bfrva(ji,jj) * vn(ji,jj,ikbv) / fse3v(ji,jj,ikbv)
+                              	      END DO
+                              	   END DO
+                              	END DO
+                              	CALL lbc_lnk( z3dx, 'U', -1. ) ; CALL lbc_lnk( z3dy, 'V', -1. )
+                              	CALL iom_put( "utrd_bfri", z3dx )
+                              	CALL iom_put( "vtrd_bfri", z3dy )
+                              	CALL wrk_dealloc( jpi, jpj, jpk, z3dx, z3dy )
+         					      ENDIF
+      END SELECT
+      !
+   END SUBROUTINE trd_dyn_iom
+
+   !!======================================================================
+END MODULE trddyn
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdglo.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdglo.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdglo.F90	(revision 5075)
@@ -0,0 +1,564 @@
+MODULE trdglo
+   !!======================================================================
+   !!                       ***  MODULE  trdglo  ***
+   !! Ocean diagnostics:  global domain averaged tracer and momentum trends
+   !!=====================================================================
+   !! History :  1.0  !  2004-08 (C. Talandier) New trends organization
+   !!            3.5  !  2012-02 (G. Madec)  add 3D tracer zdf trend output using iom
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trd_glo      : domain averaged budget of trends (including kinetic energy and T^2 trends)
+   !!   glo_dyn_wri  : print dynamic trends in ocean.output file
+   !!   glo_tra_wri  : print global T & T^2 trends in ocean.output file
+   !!   trd_glo_init : initialization step
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain variables
+   USE sbc_oce         ! surface boundary condition: ocean
+   USE trd_oce         ! trends: ocean variables
+   USE phycst          ! physical constants
+   USE ldftra_oce      ! ocean active tracers: lateral physics
+   USE ldfdyn_oce      ! ocean dynamics: lateral physics
+   USE zdf_oce         ! ocean vertical physics
+   USE zdfbfr          ! bottom friction
+   USE zdfddm          ! ocean vertical physics: double diffusion
+   USE eosbn2          ! equation of state
+   USE phycst          ! physical constants
+   USE lib_mpp         ! distibuted memory computing library
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O manager library
+   USE wrk_nemo        ! Memory allocation
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trd_glo       ! called by trdtra and trddyn modules
+   PUBLIC   trd_glo_init  ! called by trdini module
+
+   !                     !!! Variables used for diagnostics
+   REAL(wp) ::   tvolt    ! volume of the whole ocean computed at t-points
+   REAL(wp) ::   tvolu    ! volume of the whole ocean computed at u-points
+   REAL(wp) ::   tvolv    ! volume of the whole ocean computed at v-points
+   REAL(wp) ::   rpktrd   ! potential to kinetic energy conversion
+   REAL(wp) ::   peke     ! conversion potential energy - kinetic energy trend
+
+   !                     !!! domain averaged trends
+   REAL(wp), DIMENSION(jptot_tra) ::   tmo, smo   ! temperature and salinity trends 
+   REAL(wp), DIMENSION(jptot_tra) ::   t2 , s2    ! T^2 and S^2 trends 
+   REAL(wp), DIMENSION(jptot_dyn) ::   umo, vmo   ! momentum trends 
+   REAL(wp), DIMENSION(jptot_dyn) ::   hke        ! kinetic energy trends (u^2+v^2) 
+
+   !! * Substitutions
+#  include "domzgr_substitute.h90"
+#  include "vectopt_loop_substitute.h90"
+#  include "zdfddm_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: trdglo.F90 3325 2012-03-12 14:44:43Z gm $
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trd_glo( ptrdx, ptrdy, ktrd, ctype, kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_glo  ***
+      !! 
+      !! ** Purpose :   compute and print global domain averaged trends for 
+      !!              T, T^2, momentum, KE, and KE<->PE
+      !!
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdx   ! Temperature or U trend 
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdy   ! Salinity    or V trend
+      INTEGER                   , INTENT(in   ) ::   ktrd    ! tracer trend index
+      CHARACTER(len=3)          , INTENT(in   ) ::   ctype   ! momentum or tracers trends type (='DYN'/'TRA')
+      INTEGER                   , INTENT(in   ) ::   kt      ! time step
+      !!
+      INTEGER ::   ji, jj, jk      ! dummy loop indices
+      INTEGER ::   ikbu, ikbv      ! local integers
+      REAL(wp)::   zvm, zvt, zvs, z1_2rau0   ! local scalars
+      REAL(wp), POINTER, DIMENSION(:,:)  :: ztswu, ztswv, z2dx, z2dy   ! 2D workspace 
+      !!----------------------------------------------------------------------
+
+      CALL wrk_alloc( jpi, jpj, ztswu, ztswv, z2dx, z2dy )
+
+      IF( MOD(kt,nn_trd) == 0 .OR. kt == nit000 .OR. kt == nitend ) THEN
+         !
+      	SELECT CASE( ctype )
+      	!
+      	CASE( 'TRA' )          !==  Tracers (T & S)  ==!
+      	   DO jk = 1, jpkm1       ! global sum of mask volume trend and trend*T (including interior mask)
+      	      DO jj = 1, jpj
+      	         DO ji = 1, jpi        
+      	            zvm = e1e2t(ji,jj) * fse3t(ji,jj,jk) * tmask(ji,jj,jk) * tmask_i(ji,jj)
+      	            zvt = ptrdx(ji,jj,jk) * zvm
+      	            zvs = ptrdy(ji,jj,jk) * zvm
+         	         tmo(ktrd) = tmo(ktrd) + zvt   
+         	         smo(ktrd) = smo(ktrd) + zvs
+         	         t2 (ktrd) = t2(ktrd)  + zvt * tsn(ji,jj,jk,jp_tem)
+         	         s2 (ktrd) = s2(ktrd)  + zvs * tsn(ji,jj,jk,jp_sal)
+                  END DO
+               END DO
+            END DO
+            !                       ! linear free surface: diagnose advective flux trough the fixed k=1 w-surface
+            IF( .NOT.lk_vvl .AND. ktrd == jptra_zad ) THEN  
+               tmo(jptra_sad) = SUM( wn(:,:,1) * tsn(:,:,1,jp_tem) * e1e2t(:,:) )
+               smo(jptra_sad) = SUM( wn(:,:,1) * tsn(:,:,1,jp_sal) * e1e2t(:,:)  )
+               t2 (jptra_sad) = SUM( wn(:,:,1) * tsn(:,:,1,jp_tem) * tsn(:,:,1,jp_tem) * e1e2t(:,:)  )
+               s2 (jptra_sad) = SUM( wn(:,:,1) * tsn(:,:,1,jp_sal) * tsn(:,:,1,jp_sal) * e1e2t(:,:)  )
+            ENDIF
+            !
+            IF( ktrd == jptra_atf ) THEN     ! last trend (asselin time filter)
+               ! 
+               CALL glo_tra_wri( kt )             ! print the results in ocean.output
+               !                
+	            tmo(:) = 0._wp                     ! prepare the next time step (domain averaged array reset to zero)
+   	         smo(:) = 0._wp
+               t2 (:) = 0._wp
+               s2 (:) = 0._wp
+               !
+            ENDIF
+            !
+         CASE( 'DYN' )          !==  Momentum and KE  ==!        
+            DO jk = 1, jpkm1
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpim1
+                     zvt = ptrdx(ji,jj,jk) * tmask_i(ji+1,jj  ) * tmask_i(ji,jj) * umask(ji,jj,jk)   &
+                        &                  * e1u    (ji  ,jj  ) * e2u    (ji,jj) * fse3u(ji,jj,jk)
+                     zvs = ptrdy(ji,jj,jk) * tmask_i(ji  ,jj+1) * tmask_i(ji,jj) * vmask(ji,jj,jk)   &
+                        &                  * e1v    (ji  ,jj  ) * e2v    (ji,jj) * fse3u(ji,jj,jk)
+                     umo(ktrd) = umo(ktrd) + zvt
+                     vmo(ktrd) = vmo(ktrd) + zvs
+                     hke(ktrd) = hke(ktrd) + un(ji,jj,jk) * zvt + vn(ji,jj,jk) * zvs
+                  END DO
+               END DO
+            END DO
+            !                 
+            IF( ktrd == jpdyn_zdf ) THEN      ! zdf trend: compute separately the surface forcing trend
+               z1_2rau0 = 0.5_wp / rau0
+               DO jj = 1, jpjm1
+                  DO ji = 1, jpim1
+                     zvt = ( utau_b(ji,jj) + utau(ji,jj) ) * tmask_i(ji+1,jj  ) * tmask_i(ji,jj) * umask(ji,jj,jk)   &
+                        &                       * z1_2rau0 * e1u    (ji  ,jj  ) * e2u    (ji,jj)
+                     zvs = ( vtau_b(ji,jj) + vtau(ji,jj) ) * tmask_i(ji  ,jj+1) * tmask_i(ji,jj) * vmask(ji,jj,jk)   &
+                        &                       * z1_2rau0 * e1v    (ji  ,jj  ) * e2v    (ji,jj) * fse3u(ji,jj,jk)
+                     umo(jpdyn_tau) = umo(jpdyn_tau) + zvt
+                     vmo(jpdyn_tau) = vmo(jpdyn_tau) + zvs
+                     hke(jpdyn_tau) = hke(jpdyn_tau) + un(ji,jj,1) * zvt + vn(ji,jj,1) * zvs
+                  END DO
+               END DO
+            ENDIF
+            !                       
+            IF( ktrd == jpdyn_atf ) THEN     ! last trend (asselin time filter)
+               !
+               IF( ln_bfrimp ) THEN                   ! implicit bfr case: compute separately the bottom friction 
+                  z1_2rau0 = 0.5_wp / rau0
+                  DO jj = 1, jpjm1
+                     DO ji = 1, jpim1
+                        ikbu = mbku(ji,jj)                  ! deepest ocean u- & v-levels
+                        ikbv = mbkv(ji,jj)
+                        zvt = bfrua(ji,jj) * un(ji,jj,ikbu) * e1u(ji,jj) * e2v(ji,jj)
+                        zvs = bfrva(ji,jj) * vn(ji,jj,ikbv) * e1v(ji,jj) * e2v(ji,jj)
+                        umo(jpdyn_bfri) = umo(jpdyn_bfri) + zvt
+                        vmo(jpdyn_bfri) = vmo(jpdyn_bfri) + zvs
+                        hke(jpdyn_bfri) = hke(jpdyn_bfri) + un(ji,jj,ikbu) * zvt + vn(ji,jj,ikbv) * zvs
+                     END DO
+                  END DO
+               ENDIF
+               ! 
+               CALL glo_dyn_wri( kt )                 ! print the results in ocean.output
+               !                
+               umo(:) = 0._wp                         ! reset for the next time step
+               vmo(:) = 0._wp
+               hke(:) = 0._wp
+               !
+            ENDIF
+            !
+         END SELECT
+         !
+      ENDIF
+      !
+      CALL wrk_dealloc( jpi, jpj, ztswu, ztswv, z2dx, z2dy )
+      !
+   END SUBROUTINE trd_glo
+
+
+   SUBROUTINE glo_dyn_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE glo_dyn_wri  ***
+      !! 
+      !! ** Purpose :  write global averaged U, KE, PE<->KE trends in ocean.output 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      REAL(wp) ::   zcof         ! local scalar
+      REAL(wp), POINTER, DIMENSION(:,:,:)  ::  zkx, zky, zkz, zkepe  
+      !!----------------------------------------------------------------------
+
+      CALL wrk_alloc( jpi, jpj, jpk, zkx, zky, zkz, zkepe )
+
+      ! I. Momentum trends
+      ! -------------------
+
+      IF( MOD( kt, nn_trd ) == 0 .OR. kt == nit000 .OR. kt == nitend ) THEN
+
+         ! I.1 Conversion potential energy - kinetic energy
+         ! --------------------------------------------------
+         ! c a u t i o n here, trends are computed at kt+1 (now , but after the swap)
+         zkx  (:,:,:) = 0._wp
+         zky  (:,:,:) = 0._wp
+         zkz  (:,:,:) = 0._wp
+         zkepe(:,:,:) = 0._wp
+   
+         CALL eos( tsn, rhd, rhop )       ! now potential density
+
+         zcof = 0.5_wp / rau0             ! Density flux at w-point
+         zkz(:,:,1) = 0._wp
+         DO jk = 2, jpk
+            zkz(:,:,jk) = zcof * e1e2t(:,:) * wn(:,:,jk) * ( rhop(:,:,jk) + rhop(:,:,jk-1) ) * tmask_i(:,:)
+         END DO
+         
+         zcof   = 0.5_wp / rau0           ! Density flux at u and v-points
+         DO jk = 1, jpkm1
+            DO jj = 1, jpjm1
+               DO ji = 1, jpim1
+                  zkx(ji,jj,jk) = zcof * e2u(ji,jj) * fse3u(ji,jj,jk) * un(ji,jj,jk) * ( rhop(ji,jj,jk) + rhop(ji+1,jj,jk) )
+                  zky(ji,jj,jk) = zcof * e1v(ji,jj) * fse3v(ji,jj,jk) * vn(ji,jj,jk) * ( rhop(ji,jj,jk) + rhop(ji,jj+1,jk) )
+               END DO
+            END DO
+         END DO
+         
+         DO jk = 1, jpkm1                 ! Density flux divergence at t-point
+            DO jj = 2, jpjm1
+               DO ji = 2, jpim1
+                  zkepe(ji,jj,jk) = - (  zkz(ji,jj,jk) - zkz(ji  ,jj  ,jk+1)               &
+                     &                 + zkx(ji,jj,jk) - zkx(ji-1,jj  ,jk  )               &
+                     &                 + zky(ji,jj,jk) - zky(ji  ,jj-1,jk  )   )           &
+                     &              / ( e1e2t(ji,jj) * fse3t(ji,jj,jk) ) * tmask(ji,jj,jk) * tmask_i(ji,jj)
+               END DO
+            END DO
+         END DO
+
+         ! I.2 Basin averaged kinetic energy trend
+         ! ----------------------------------------
+         peke = 0._wp
+         DO jk = 1, jpkm1
+            peke = peke + SUM( zkepe(:,:,jk) * fsdept(:,:,jk) * e1e2t(:,:) * fse3t(:,:,jk) )
+         END DO
+         peke = grav * peke
+
+         ! I.3 Sums over the global domain
+         ! ---------------------------------
+         IF( lk_mpp ) THEN
+            CALL mpp_sum( peke )
+            CALL mpp_sum( umo , jptot_dyn )
+            CALL mpp_sum( vmo , jptot_dyn )
+            CALL mpp_sum( hke , jptot_dyn )
+         ENDIF
+
+         ! I.2 Print dynamic trends in the ocean.output file
+         ! --------------------------------------------------
+
+         IF(lwp) THEN
+            WRITE (numout,*)
+            WRITE (numout,*)
+            WRITE (numout,9500) kt
+            WRITE (numout,9501) umo(jpdyn_hpg) / tvolu, vmo(jpdyn_hpg) / tvolv
+            WRITE (numout,9502) umo(jpdyn_keg) / tvolu, vmo(jpdyn_keg) / tvolv
+            WRITE (numout,9503) umo(jpdyn_rvo) / tvolu, vmo(jpdyn_rvo) / tvolv
+            WRITE (numout,9504) umo(jpdyn_pvo) / tvolu, vmo(jpdyn_pvo) / tvolv
+            WRITE (numout,9505) umo(jpdyn_zad) / tvolu, vmo(jpdyn_zad) / tvolv
+            WRITE (numout,9506) umo(jpdyn_ldf) / tvolu, vmo(jpdyn_ldf) / tvolv
+            WRITE (numout,9507) umo(jpdyn_zdf) / tvolu, vmo(jpdyn_zdf) / tvolv
+            WRITE (numout,9508) umo(jpdyn_spg) / tvolu, vmo(jpdyn_spg) / tvolv
+            WRITE (numout,9509) umo(jpdyn_bfr) / tvolu, vmo(jpdyn_bfr) / tvolv
+            WRITE (numout,9510) umo(jpdyn_atf) / tvolu, vmo(jpdyn_atf) / tvolv
+            WRITE (numout,9511)
+            WRITE (numout,9512)                                                 &
+            &     (  umo(jpdyn_hpg) + umo(jpdyn_keg) + umo(jpdyn_rvo) + umo(jpdyn_pvo)   &
+            &      + umo(jpdyn_zad) + umo(jpdyn_ldf) + umo(jpdyn_zdf) + umo(jpdyn_spg)   &
+            &      + umo(jpdyn_bfr) + umo(jpdyn_atf) ) / tvolu,   &
+            &     (  vmo(jpdyn_hpg) + vmo(jpdyn_keg) + vmo(jpdyn_rvo) + vmo(jpdyn_pvo)   &
+            &      + vmo(jpdyn_zad) + vmo(jpdyn_ldf) + vmo(jpdyn_zdf) + vmo(jpdyn_spg)   &
+            &      + vmo(jpdyn_bfr) + vmo(jpdyn_atf) ) / tvolv
+            WRITE (numout,9513) umo(jpdyn_tau) / tvolu, vmo(jpdyn_tau) / tvolv
+            IF( ln_bfrimp )   WRITE (numout,9514) umo(jpdyn_bfri) / tvolu, vmo(jpdyn_bfri) / tvolv
+         ENDIF
+
+ 9500    FORMAT(' momentum trend at it= ', i6, ' :', /' ==============================')
+ 9501    FORMAT(' hydro pressure gradient    u= ', e20.13, '    v= ', e20.13)
+ 9502    FORMAT(' ke gradient                u= ', e20.13, '    v= ', e20.13)
+ 9503    FORMAT(' relative vorticity term    u= ', e20.13, '    v= ', e20.13)
+ 9504    FORMAT(' planetary vorticity term   u= ', e20.13, '    v= ', e20.13)
+ 9505    FORMAT(' vertical advection         u= ', e20.13, '    v= ', e20.13)
+ 9506    FORMAT(' horizontal diffusion       u= ', e20.13, '    v= ', e20.13)
+ 9507    FORMAT(' vertical diffusion         u= ', e20.13, '    v= ', e20.13)
+ 9508    FORMAT(' surface pressure gradient  u= ', e20.13, '    v= ', e20.13)
+ 9509    FORMAT(' explicit bottom friction   u= ', e20.13, '    v= ', e20.13)
+ 9510    FORMAT(' Asselin time filter        u= ', e20.13, '    v= ', e20.13)
+ 9511    FORMAT(' -----------------------------------------------------------------------------')
+ 9512    FORMAT(' total trend                u= ', e20.13, '    v= ', e20.13)
+ 9513    FORMAT(' incl. surface wind stress  u= ', e20.13, '    v= ', e20.13)
+ 9514    FORMAT('       bottom stress        u= ', e20.13, '    v= ', e20.13)
+
+         IF(lwp) THEN
+            WRITE (numout,*)
+            WRITE (numout,*)
+            WRITE (numout,9520) kt
+            WRITE (numout,9521) hke(jpdyn_hpg) / tvolt
+            WRITE (numout,9522) hke(jpdyn_keg) / tvolt
+            WRITE (numout,9523) hke(jpdyn_rvo) / tvolt
+            WRITE (numout,9524) hke(jpdyn_pvo) / tvolt
+            WRITE (numout,9525) hke(jpdyn_zad) / tvolt
+            WRITE (numout,9526) hke(jpdyn_ldf) / tvolt
+            WRITE (numout,9527) hke(jpdyn_zdf) / tvolt
+            WRITE (numout,9528) hke(jpdyn_spg) / tvolt
+            WRITE (numout,9529) hke(jpdyn_bfr) / tvolt
+            WRITE (numout,9530) hke(jpdyn_atf) / tvolt
+            WRITE (numout,9531)
+            WRITE (numout,9532)   &
+            &     (  hke(jpdyn_hpg) + hke(jpdyn_keg) + hke(jpdyn_rvo) + hke(jpdyn_pvo)   &
+            &      + hke(jpdyn_zad) + hke(jpdyn_ldf) + hke(jpdyn_zdf) + hke(jpdyn_spg)   &
+            &      + hke(jpdyn_bfr) + hke(jpdyn_atf) ) / tvolt
+            WRITE (numout,9533) hke(jpdyn_tau) / tvolt
+            IF( ln_bfrimp )   WRITE (numout,9534) hke(jpdyn_bfri) / tvolt
+         ENDIF
+
+ 9520    FORMAT(' kinetic energy trend at it= ', i6, ' :', /' ====================================')
+ 9521    FORMAT(' hydro pressure gradient   u2= ', e20.13)
+ 9522    FORMAT(' ke gradient               u2= ', e20.13)
+ 9523    FORMAT(' relative vorticity term   u2= ', e20.13)
+ 9524    FORMAT(' planetary vorticity term  u2= ', e20.13)
+ 9525    FORMAT(' vertical advection        u2= ', e20.13)
+ 9526    FORMAT(' horizontal diffusion      u2= ', e20.13)
+ 9527    FORMAT(' vertical diffusion        u2= ', e20.13)
+ 9528    FORMAT(' surface pressure gradient u2= ', e20.13)
+ 9529    FORMAT(' explicit bottom friction  u2= ', e20.13)
+ 9530    FORMAT(' Asselin time filter       u2= ', e20.13)
+ 9531    FORMAT(' --------------------------------------------------')
+ 9532    FORMAT(' total trend               u2= ', e20.13)
+ 9533    FORMAT(' incl. surface wind stress u2= ', e20.13)
+ 9534    FORMAT('       bottom stress       u2= ', e20.13)
+
+         IF(lwp) THEN
+            WRITE (numout,*)
+            WRITE (numout,*)
+            WRITE (numout,9540) kt
+            WRITE (numout,9541) ( hke(jpdyn_keg) + hke(jpdyn_rvo) + hke(jpdyn_zad) ) / tvolt
+            WRITE (numout,9542) ( hke(jpdyn_keg) + hke(jpdyn_zad) ) / tvolt
+            WRITE (numout,9543) ( hke(jpdyn_pvo) ) / tvolt
+            WRITE (numout,9544) ( hke(jpdyn_rvo) ) / tvolt
+            WRITE (numout,9545) ( hke(jpdyn_spg) ) / tvolt
+            WRITE (numout,9546) ( hke(jpdyn_ldf) ) / tvolt
+            WRITE (numout,9547) ( hke(jpdyn_zdf) ) / tvolt
+            WRITE (numout,9548) ( hke(jpdyn_hpg) ) / tvolt, rpktrd / tvolt
+            WRITE (numout,*)
+            WRITE (numout,*)
+         ENDIF
+
+ 9540    FORMAT(' energetic consistency at it= ', i6, ' :', /' =========================================')
+ 9541    FORMAT(' 0 = non linear term (true if KE conserved)                : ', e20.13)
+ 9542    FORMAT(' 0 = ke gradient + vertical advection                      : ', e20.13)
+ 9543    FORMAT(' 0 = coriolis term  (true if KE conserving scheme)         : ', e20.13)
+ 9544    FORMAT(' 0 = vorticity term (true if KE conserving scheme)         : ', e20.13)
+ 9545    FORMAT(' 0 = surface pressure gradient  ???                        : ', e20.13)
+ 9546    FORMAT(' 0 < horizontal diffusion                                  : ', e20.13)
+ 9547    FORMAT(' 0 < vertical diffusion                                    : ', e20.13)
+ 9548    FORMAT(' pressure gradient u2 = - 1/rau0 u.dz(rhop)                : ', e20.13, '  u.dz(rhop) =', e20.13)
+         !
+         ! Save potential to kinetic energy conversion for next time step
+         rpktrd = peke
+         !
+      ENDIF
+      !
+      CALL wrk_dealloc( jpi, jpj, jpk, zkx, zky, zkz, zkepe )
+      !
+   END SUBROUTINE glo_dyn_wri
+
+
+   SUBROUTINE glo_tra_wri( kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE glo_tra_wri  ***
+      !! 
+      !! ** Purpose :  write global domain averaged of T and T^2 trends in ocean.output 
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER  ::   jk   ! loop indices
+      !!----------------------------------------------------------------------
+
+      ! I. Tracers trends
+      ! -----------------
+
+      IF( MOD(kt,nn_trd) == 0 .OR. kt == nit000 .OR. kt == nitend ) THEN
+
+         ! I.1 Sums over the global domain
+         ! -------------------------------
+         IF( lk_mpp ) THEN
+            CALL mpp_sum( tmo, jptot_tra )   
+            CALL mpp_sum( smo, jptot_tra )
+            CALL mpp_sum( t2 , jptot_tra )
+            CALL mpp_sum( s2 , jptot_tra )
+         ENDIF
+
+         ! I.2 Print tracers trends in the ocean.output file
+         ! --------------------------------------------------
+         
+         IF(lwp) THEN
+            WRITE (numout,*)
+            WRITE (numout,*)
+            WRITE (numout,9400) kt
+            WRITE (numout,9401)  tmo(jptra_xad) / tvolt, smo(jptra_xad) / tvolt
+            WRITE (numout,9411)  tmo(jptra_yad) / tvolt, smo(jptra_yad) / tvolt
+            WRITE (numout,9402)  tmo(jptra_zad) / tvolt, smo(jptra_zad) / tvolt
+            WRITE (numout,9403)  tmo(jptra_ldf) / tvolt, smo(jptra_ldf) / tvolt
+            WRITE (numout,9404)  tmo(jptra_zdf) / tvolt, smo(jptra_zdf) / tvolt
+            WRITE (numout,9405)  tmo(jptra_npc) / tvolt, smo(jptra_npc) / tvolt
+            WRITE (numout,9406)  tmo(jptra_dmp) / tvolt, smo(jptra_dmp) / tvolt
+            WRITE (numout,9407)  tmo(jptra_qsr) / tvolt
+            WRITE (numout,9408)  tmo(jptra_nsr) / tvolt, smo(jptra_nsr) / tvolt
+            WRITE (numout,9409) 
+            WRITE (numout,9410) (  tmo(jptra_xad) + tmo(jptra_yad) + tmo(jptra_zad) + tmo(jptra_ldf) + tmo(jptra_zdf)   &
+            &                    + tmo(jptra_npc) + tmo(jptra_dmp) + tmo(jptra_qsr) + tmo(jptra_nsr) ) / tvolt,   &
+            &                   (  smo(jptra_xad) + smo(jptra_yad) + smo(jptra_zad) + smo(jptra_ldf) + smo(jptra_zdf)   &
+            &                    + smo(jptra_npc) + smo(jptra_dmp)                   + smo(jptra_nsr) ) / tvolt
+         ENDIF
+
+9400     FORMAT(' tracer trend at it= ',i6,' :     temperature',   &
+              '              salinity',/' ============================')
+9401     FORMAT(' zonal      advection        ',e20.13,'     ',e20.13)
+9411     FORMAT(' meridional advection        ',e20.13,'     ',e20.13)
+9402     FORMAT(' vertical advection          ',e20.13,'     ',e20.13)
+9403     FORMAT(' horizontal diffusion        ',e20.13,'     ',e20.13)
+9404     FORMAT(' vertical diffusion          ',e20.13,'     ',e20.13)
+9405     FORMAT(' static instability mixing   ',e20.13,'     ',e20.13)
+9406     FORMAT(' damping term                ',e20.13,'     ',e20.13)
+9407     FORMAT(' penetrative qsr             ',e20.13)
+9408     FORMAT(' non solar radiation         ',e20.13,'     ',e20.13)
+9409     FORMAT(' -------------------------------------------------------------------------')
+9410     FORMAT(' total trend                 ',e20.13,'     ',e20.13)
+
+
+         IF(lwp) THEN
+            WRITE (numout,*)
+            WRITE (numout,*)
+            WRITE (numout,9420) kt
+            WRITE (numout,9421)   t2(jptra_xad) / tvolt, s2(jptra_xad) / tvolt
+            WRITE (numout,9431)   t2(jptra_yad) / tvolt, s2(jptra_yad) / tvolt
+            WRITE (numout,9422)   t2(jptra_zad) / tvolt, s2(jptra_zad) / tvolt
+            WRITE (numout,9423)   t2(jptra_ldf) / tvolt, s2(jptra_ldf) / tvolt
+            WRITE (numout,9424)   t2(jptra_zdf) / tvolt, s2(jptra_zdf) / tvolt
+            WRITE (numout,9425)   t2(jptra_npc) / tvolt, s2(jptra_npc) / tvolt
+            WRITE (numout,9426)   t2(jptra_dmp) / tvolt, s2(jptra_dmp) / tvolt
+            WRITE (numout,9427)   t2(jptra_qsr) / tvolt
+            WRITE (numout,9428)   t2(jptra_nsr) / tvolt, s2(jptra_nsr) / tvolt
+            WRITE (numout,9429)
+            WRITE (numout,9430) (  t2(jptra_xad) + t2(jptra_yad) + t2(jptra_zad) + t2(jptra_ldf) + t2(jptra_zdf)   &
+            &                    + t2(jptra_npc) + t2(jptra_dmp) + t2(jptra_qsr) + t2(jptra_nsr) ) / tvolt,   &
+            &                   (  s2(jptra_xad) + s2(jptra_yad) + s2(jptra_zad) + s2(jptra_ldf) + s2(jptra_zdf)   &
+            &                    + s2(jptra_npc) + s2(jptra_dmp)                  + s2(jptra_nsr) ) / tvolt
+         ENDIF
+
+9420     FORMAT(' tracer**2 trend at it= ', i6, ' :      temperature',   &
+            '               salinity', /, ' ===============================')
+9421     FORMAT(' zonal      advection      * t   ', e20.13, '     ', e20.13)
+9431     FORMAT(' meridional advection      * t   ', e20.13, '     ', e20.13)
+9422     FORMAT(' vertical advection        * t   ', e20.13, '     ', e20.13)
+9423     FORMAT(' horizontal diffusion      * t   ', e20.13, '     ', e20.13)
+9424     FORMAT(' vertical diffusion        * t   ', e20.13, '     ', e20.13)
+9425     FORMAT(' static instability mixing * t   ', e20.13, '     ', e20.13)
+9426     FORMAT(' damping term              * t   ', e20.13, '     ', e20.13)
+9427     FORMAT(' penetrative qsr           * t   ', e20.13)
+9428     FORMAT(' non solar radiation       * t   ', e20.13, '     ', e20.13)
+9429     FORMAT(' -----------------------------------------------------------------------------')
+9430     FORMAT(' total trend                *t = ', e20.13, '  *s = ', e20.13)
+
+
+         IF(lwp) THEN
+            WRITE (numout,*)
+            WRITE (numout,*)
+            WRITE (numout,9440) kt
+            WRITE (numout,9441) ( tmo(jptra_xad)+tmo(jptra_yad)+tmo(jptra_zad) )/tvolt,   &
+            &                   ( smo(jptra_xad)+smo(jptra_yad)+smo(jptra_zad) )/tvolt
+            WRITE (numout,9442)   tmo(jptra_sad)/tvolt,  smo(jptra_sad)/tvolt
+            WRITE (numout,9443)   tmo(jptra_ldf)/tvolt,  smo(jptra_ldf)/tvolt
+            WRITE (numout,9444)   tmo(jptra_zdf)/tvolt,  smo(jptra_zdf)/tvolt
+            WRITE (numout,9445)   tmo(jptra_npc)/tvolt,  smo(jptra_npc)/tvolt
+            WRITE (numout,9446) ( t2(jptra_xad)+t2(jptra_yad)+t2(jptra_zad) )/tvolt,    &
+            &                   ( s2(jptra_xad)+s2(jptra_yad)+s2(jptra_zad) )/tvolt
+            WRITE (numout,9447)   t2(jptra_ldf)/tvolt,   s2(jptra_ldf)/tvolt
+            WRITE (numout,9448)   t2(jptra_zdf)/tvolt,   s2(jptra_zdf)/tvolt
+            WRITE (numout,9449)   t2(jptra_npc)/tvolt,   s2(jptra_npc)/tvolt
+         ENDIF
+
+9440     FORMAT(' tracer consistency at it= ',i6,   &
+            ' :         temperature','                salinity',/,   &
+            ' ==================================')
+9441     FORMAT(' 0 = horizontal+vertical advection +    ',e20.13,'       ',e20.13)
+9442     FORMAT('     1st lev vertical advection         ',e20.13,'       ',e20.13)
+9443     FORMAT(' 0 = horizontal diffusion               ',e20.13,'       ',e20.13)
+9444     FORMAT(' 0 = vertical diffusion                 ',e20.13,'       ',e20.13)
+9445     FORMAT(' 0 = static instability mixing          ',e20.13,'       ',e20.13)
+9446     FORMAT(' 0 = horizontal+vertical advection * t  ',e20.13,'       ',e20.13)
+9447     FORMAT(' 0 > horizontal diffusion          * t  ',e20.13,'       ',e20.13)
+9448     FORMAT(' 0 > vertical diffusion            * t  ',e20.13,'       ',e20.13)
+9449     FORMAT(' 0 > static instability mixing     * t  ',e20.13,'       ',e20.13)
+         !
+      ENDIF
+      !
+   END SUBROUTINE glo_tra_wri
+
+
+   SUBROUTINE trd_glo_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_glo_init  ***
+      !! 
+      !! ** Purpose :   Read the namtrd namelist
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trd_glo_init : integral constraints properties trends'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+
+      ! Total volume at t-points:
+      tvolt = 0._wp
+      DO jk = 1, jpkm1
+         tvolt = tvolt + SUM( e1e2t(:,:) * fse3t(:,:,jk) * tmask(:,:,jk) * tmask_i(:,:) )
+      END DO
+      IF( lk_mpp )   CALL mpp_sum( tvolt )   ! sum over the global domain
+
+      IF(lwp) WRITE(numout,*) '                total ocean volume at T-point   tvolt = ',tvolt
+
+      ! Initialization of potential to kinetic energy conversion
+      rpktrd = 0._wp
+
+      ! Total volume at u-, v- points:
+!!gm :  bug?  je suis quasi sur que le produit des tmask_i ne correspond pas exactement au umask_i et vmask_i !
+      tvolu = 0._wp
+      tvolv = 0._wp
+
+      DO jk = 1, jpk
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               tvolu = tvolu + e1u(ji,jj) * e2u(ji,jj) * fse3u(ji,jj,jk) * tmask_i(ji+1,jj  ) * tmask_i(ji,jj) * umask(ji,jj,jk)
+               tvolv = tvolv + e1v(ji,jj) * e2v(ji,jj) * fse3v(ji,jj,jk) * tmask_i(ji  ,jj+1) * tmask_i(ji,jj) * vmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      IF( lk_mpp )   CALL mpp_sum( tvolu )   ! sums over the global domain
+      IF( lk_mpp )   CALL mpp_sum( tvolv )
+
+      IF(lwp) THEN
+         WRITE(numout,*) '                total ocean volume at U-point   tvolu = ',tvolu
+         WRITE(numout,*) '                total ocean volume at V-point   tvolv = ',tvolv
+      ENDIF
+      !
+   END SUBROUTINE trd_glo_init
+
+   !!======================================================================
+END MODULE trdglo
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdicp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdicp.F90	(revision 5074)
+++ 	(revision )
@@ -1,607 +1,0 @@
-MODULE trdicp
-   !!======================================================================
-   !!                       ***  MODULE  trdicp  ***
-   !! Ocean diagnostics:  ocean tracers and dynamic trends
-   !!=====================================================================
-   !! History :  1.0  !  2004-08 (C. Talandier) New trends organization
-   !!----------------------------------------------------------------------
-#if  defined key_trdtra   ||   defined key_trddyn   ||   defined key_esopa
-   !!----------------------------------------------------------------------
-   !!   'key_trdtra'  or                  active tracers trends diagnostics
-   !!   'key_trddyn'                            momentum trends diagnostics
-   !!----------------------------------------------------------------------
-   !!   trd_icp          : compute the basin averaged properties for tra/dyn 
-   !!   trd_dwr          : print dynmaic trends in ocean.output file
-   !!   trd_twr          : print tracers trends in ocean.output file
-   !!   trd_icp_init     : initialization step
-   !!----------------------------------------------------------------------
-   USE oce             ! ocean dynamics and tracers variables
-   USE dom_oce         ! ocean space and time domain variables
-   USE trdmod_oce      ! ocean variables trends
-   USE ldftra_oce      ! ocean active tracers: lateral physics
-   USE ldfdyn_oce      ! ocean dynamics: lateral physics
-   USE zdf_oce         ! ocean vertical physics
-   USE in_out_manager  ! I/O manager
-   USE lib_mpp         ! distibuted memory computing library
-   USE eosbn2          ! equation of state
-   USE phycst          ! physical constants
-   USE wrk_nemo        ! Memory allocation
-
-
-   IMPLICIT NONE
-   PRIVATE
-
-   INTERFACE trd_icp
-      MODULE PROCEDURE trd_2d, trd_3d
-   END INTERFACE
-
-   PUBLIC   trd_icp       ! called by trdmod.F90
-   PUBLIC   trd_dwr       ! called by step.F90
-   PUBLIC   trd_twr       ! called by step.F90
-   PUBLIC   trd_icp_init  ! called by opa.F90
-
-   !! * Substitutions
-#  include "domzgr_substitute.h90"
-#  include "vectopt_loop_substitute.h90"
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$
-   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-CONTAINS
-
-   SUBROUTINE trd_2d( ptrd2dx, ptrd2dy, ktrd , ctype )
-      !!---------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_2d  ***
-      !! 
-      !! ** Purpose : verify the basin averaged properties of tracers and/or
-      !!              momentum equations at every time step frequency nn_trd.
-      !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   ptrd2dx   ! Temperature or U trend 
-      REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   ptrd2dy   ! Salinity    or V trend
-      INTEGER                     , INTENT(in   ) ::   ktrd      ! tracer trend index
-      CHARACTER(len=3)            , INTENT(in   ) ::   ctype     ! momentum ('DYN') or tracers ('TRA') trends
-      !!
-      INTEGER ::   ji, jj   ! loop indices
-      !!----------------------------------------------------------------------
-
-      SELECT CASE( ctype )    !==  Mask trends  ==!
-      !
-      CASE( 'DYN' )                    ! Momentum
-         DO jj = 1, jpjm1
-            DO ji = 1, jpim1
-               ptrd2dx(ji,jj) = ptrd2dx(ji,jj) * tmask_i(ji+1,jj  ) * tmask_i(ji,jj) * umask(ji,jj,1)
-               ptrd2dy(ji,jj) = ptrd2dy(ji,jj) * tmask_i(ji  ,jj+1) * tmask_i(ji,jj) * vmask(ji,jj,1)
-            END DO
-         END DO
-         ptrd2dx(jpi, : ) = 0._wp      ;      ptrd2dy(jpi, : ) = 0._wp
-         ptrd2dx( : ,jpj) = 0._wp      ;      ptrd2dy( : ,jpj) = 0._wp
-         !
-      CASE( 'TRA' )                    ! Tracers
-         ptrd2dx(:,:) = ptrd2dx(:,:) * tmask_i(:,:)
-         ptrd2dy(:,:) = ptrd2dy(:,:) * tmask_i(:,:)
-         !
-      END SELECT
-      
-      SELECT CASE( ctype )    !==  Basin averaged tracer/momentum trends  ==!
-      !
-      CASE( 'DYN' )                    ! Momentum
-         umo(ktrd) = 0._wp
-         vmo(ktrd) = 0._wp
-         !
-         SELECT CASE( ktrd )
-         CASE( jpdyn_trd_swf )         ! surface forcing
-            umo(ktrd) = SUM( ptrd2dx(:,:) * e1u(:,:) * e2u(:,:) * fse3u(:,:,1) )
-            vmo(ktrd) = SUM( ptrd2dy(:,:) * e1v(:,:) * e2v(:,:) * fse3v(:,:,1) )
-         END SELECT
-         !
-      CASE( 'TRA' )              ! Tracers
-         tmo(ktrd) = SUM( ptrd2dx(:,:) * e1e2t(:,:) * fse3t(:,:,1) )
-         smo(ktrd) = SUM( ptrd2dy(:,:) * e1e2t(:,:) * fse3t(:,:,1) )
-      END SELECT
-      
-      SELECT CASE( ctype )    !==  Basin averaged tracer/momentum square trends  ==!   (now field)
-      !
-      CASE( 'DYN' )              ! Momentum
-         hke(ktrd) = SUM(   un(:,:,1) * ptrd2dx(:,:) * e1u(:,:) * e2u(:,:) * fse3u(:,:,1)   &
-            &             + vn(:,:,1) * ptrd2dy(:,:) * e1v(:,:) * e2v(:,:) * fse3v(:,:,1)   )
-         !
-      CASE( 'TRA' )              ! Tracers
-         t2(ktrd) = SUM( ptrd2dx(:,:) * e1e2t(:,:) * fse3t(:,:,1) * tsn(:,:,1,jp_tem) )
-         s2(ktrd) = SUM( ptrd2dy(:,:) * e1e2t(:,:) * fse3t(:,:,1) * tsn(:,:,1,jp_sal) )
-         !      
-      END SELECT
-      !
-   END SUBROUTINE trd_2d
-
-
-   SUBROUTINE trd_3d( ptrd3dx, ptrd3dy, ktrd, ctype )
-      !!---------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_3d  ***
-      !! 
-      !! ** Purpose : verify the basin averaged properties of tracers and/or
-      !!              momentum equations at every time step frequency nn_trd.
-      !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   ptrd3dx   ! Temperature or U trend 
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(inout) ::   ptrd3dy   ! Salinity    or V trend
-      INTEGER,                          INTENT(in   ) ::   ktrd      ! momentum or tracer trend index
-      CHARACTER(len=3),                 INTENT(in   ) ::   ctype     ! momentum ('DYN') or tracers ('TRA') trends
-      !!
-      INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      !!----------------------------------------------------------------------
-
-      SELECT CASE( ctype )    !==  Mask the trends  ==!
-      !
-      CASE( 'DYN' )              ! Momentum        
-         DO jk = 1, jpkm1
-            DO jj = 1, jpjm1
-               DO ji = 1, jpim1
-                  ptrd3dx(ji,jj,jk) = ptrd3dx(ji,jj,jk) * tmask_i(ji+1,jj  ) * tmask_i(ji,jj) * umask(ji,jj,jk)
-                  ptrd3dy(ji,jj,jk) = ptrd3dy(ji,jj,jk) * tmask_i(ji  ,jj+1) * tmask_i(ji,jj) * vmask(ji,jj,jk)
-               END DO
-            END DO
-         END DO
-         ptrd3dx(jpi, : ,:) = 0._wp      ;      ptrd3dy(jpi, : ,:) = 0._wp
-         ptrd3dx( : ,jpj,:) = 0._wp      ;      ptrd3dy( : ,jpj,:) = 0._wp
-         !
-      CASE( 'TRA' )              ! Tracers
-         DO jk = 1, jpkm1
-            ptrd3dx(:,:,jk) = ptrd3dx(:,:,jk) * tmask(:,:,jk) * tmask_i(:,:)
-            ptrd3dy(:,:,jk) = ptrd3dy(:,:,jk) * tmask(:,:,jk) * tmask_i(:,:)
-         END DO
-         !
-      END SELECT   
-
-      SELECT CASE( ctype )    !==  Basin averaged tracer/momentum trends  ==!
-      !
-      CASE( 'DYN' )              ! Momentum
-         umo(ktrd) = 0._wp
-         vmo(ktrd) = 0._wp
-         DO jk = 1, jpkm1
-            umo(ktrd) = umo(ktrd) + SUM( ptrd3dx(:,:,jk) * e1u(:,:) * e2u(:,:) * fse3u(:,:,jk) )
-            vmo(ktrd) = vmo(ktrd) + SUM( ptrd3dy(:,:,jk) * e1v(:,:) * e2v(:,:) * fse3v(:,:,jk) )
-         END DO
-         !
-      CASE( 'TRA' )              ! Tracers
-         tmo(ktrd) = 0._wp
-         smo(ktrd) = 0._wp
-         DO jk = 1, jpkm1
-            tmo(ktrd) = tmo(ktrd) + SUM( ptrd3dx(:,:,jk) * e1e2t(:,:) * fse3t(:,:,jk) )
-            smo(ktrd) = smo(ktrd) + SUM( ptrd3dy(:,:,jk) * e1e2t(:,:) * fse3t(:,:,jk) )
-         END DO
-         !
-      END SELECT
-
-      SELECT CASE( ctype )    !==  Basin averaged tracer/momentum square trends  ==!   (now field)
-      !
-      CASE( 'DYN' )              ! Momentum
-         hke(ktrd) = 0._wp
-         DO jk = 1, jpkm1
-            hke(ktrd) = hke(ktrd) + SUM(   un(:,:,jk) * ptrd3dx(:,:,jk) * e1u(:,:) * e2u(:,:) * fse3u(:,:,jk)   &
-               &                         + vn(:,:,jk) * ptrd3dy(:,:,jk) * e1v(:,:) * e2v(:,:) * fse3v(:,:,jk)   )
-         END DO
-         !
-      CASE( 'TRA' )              ! Tracers
-         t2(ktrd) = 0._wp
-         s2(ktrd) = 0._wp
-         DO jk = 1, jpkm1
-            t2(ktrd) = t2(ktrd) + SUM( ptrd3dx(:,:,jk) * tsn(:,:,jk,jp_tem) * e1e2t(:,:) * fse3t(:,:,jk) )
-            s2(ktrd) = s2(ktrd) + SUM( ptrd3dy(:,:,jk) * tsn(:,:,jk,jp_sal) * e1e2t(:,:) * fse3t(:,:,jk) )
-         END DO
-         !
-      END SELECT
-      !
-   END SUBROUTINE trd_3d
-
-
-   SUBROUTINE trd_icp_init
-      !!---------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_icp_init  ***
-      !! 
-      !! ** Purpose :   Read the namtrd namelist
-      !!----------------------------------------------------------------------
-      INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      !!----------------------------------------------------------------------
-
-      IF(lwp) THEN
-         WRITE(numout,*)
-         WRITE(numout,*) 'trd_icp_init : integral constraints properties trends'
-         WRITE(numout,*) '~~~~~~~~~~~~~'
-      ENDIF
-
-      ! Total volume at t-points:
-      tvolt = 0._wp
-      DO jk = 1, jpkm1
-         tvolt = tvolt + SUM( e1e2t(:,:) * fse3t(:,:,jk) * tmask(:,:,jk) * tmask_i(:,:) )
-      END DO
-      IF( lk_mpp )   CALL mpp_sum( tvolt )   ! sum over the global domain
-
-      IF(lwp) WRITE(numout,*) '                total ocean volume at T-point   tvolt = ',tvolt
-
-#if  defined key_trddyn
-      ! Initialization of potential to kinetic energy conversion
-      rpktrd = 0._wp
-
-      ! Total volume at u-, v- points:
-      tvolu = 0._wp
-      tvolv = 0._wp
-      DO jk = 1, jpk
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1   ! vector opt.
-               tvolu = tvolu + e1u(ji,jj) * e2u(ji,jj) * fse3u(ji,jj,jk) * tmask_i(ji+1,jj  ) * tmask_i(ji,jj) * umask(ji,jj,jk)
-               tvolv = tvolv + e1v(ji,jj) * e2v(ji,jj) * fse3v(ji,jj,jk) * tmask_i(ji  ,jj+1) * tmask_i(ji,jj) * vmask(ji,jj,jk)
-            END DO
-         END DO
-      END DO
-      IF( lk_mpp )   CALL mpp_sum( tvolu )   ! sums over the global domain
-      IF( lk_mpp )   CALL mpp_sum( tvolv )
-
-      IF(lwp) THEN
-         WRITE(numout,*) '                total ocean volume at U-point   tvolu = ',tvolu
-         WRITE(numout,*) '                total ocean volume at V-point   tvolv = ',tvolv
-      ENDIF
-#endif
-      !
-   END SUBROUTINE trd_icp_init
-
-
-   SUBROUTINE trd_dwr( kt )
-      !!---------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_dwr  ***
-      !! 
-      !! ** Purpose :  write dynamic trends in ocean.output 
-      !!----------------------------------------------------------------------
-      !
-      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
-      !
-      INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      REAL(wp) ::   zcof         ! local scalar
-      REAL(wp), POINTER, DIMENSION(:,:,:)  ::  zkx, zky, zkz, zkepe  
-      !!----------------------------------------------------------------------
-
-      CALL wrk_alloc( jpi, jpj, jpk, zkx, zky, zkz, zkepe )
-
-      ! I. Momentum trends
-      ! -------------------
-
-      IF( MOD(kt,nn_trd) == 0 .OR. kt == nit000 .OR. kt == nitend ) THEN
-
-         ! I.1 Conversion potential energy - kinetic energy
-         ! --------------------------------------------------
-         ! c a u t i o n here, trends are computed at kt+1 (now , but after the swap)
-         zkx  (:,:,:) = 0._wp
-         zky  (:,:,:) = 0._wp
-         zkz  (:,:,:) = 0._wp
-         zkepe(:,:,:) = 0._wp
-   
-         CALL eos( tsn, rhd, rhop, fsdept_n(:,:,:) )       ! now potential and in situ densities
-
-         zcof = 0.5_wp / rau0             ! Density flux at w-point
-         zkz(:,:,1) = 0._wp
-         DO jk = 2, jpk
-            zkz(:,:,jk) = e1e2t(:,:) * wn(:,:,jk) * ( rhop(:,:,jk) + rhop(:,:,jk-1) ) * tmask_i(:,:)
-         END DO
-         
-         zcof   = 0.5_wp / rau0           ! Density flux at u and v-points
-         DO jk = 1, jpkm1
-            DO jj = 1, jpjm1
-               DO ji = 1, jpim1
-                  zkx(ji,jj,jk) = zcof * e2u(ji,jj) * fse3u(ji,jj,jk) * un(ji,jj,jk) * ( rhop(ji,jj,jk) + rhop(ji+1,jj,jk) )
-                  zky(ji,jj,jk) = zcof * e1v(ji,jj) * fse3v(ji,jj,jk) * vn(ji,jj,jk) * ( rhop(ji,jj,jk) + rhop(ji,jj+1,jk) )
-               END DO
-            END DO
-         END DO
-         
-         DO jk = 1, jpkm1                 ! Density flux divergence at t-point
-            DO jj = 2, jpjm1
-               DO ji = 2, jpim1
-                  zkepe(ji,jj,jk) = - (  zkz(ji,jj,jk) - zkz(ji  ,jj  ,jk+1)               &
-                     &                 + zkx(ji,jj,jk) - zkx(ji-1,jj  ,jk  )               &
-                     &                 + zky(ji,jj,jk) - zky(ji  ,jj-1,jk  )   )           &
-                     &              / ( e1e2t(ji,jj) * fse3t(ji,jj,jk) ) * tmask(ji,jj,jk) * tmask_i(ji,jj)
-               END DO
-            END DO
-         END DO
-
-         ! I.2 Basin averaged kinetic energy trend
-         ! ----------------------------------------
-         peke = 0._wp
-         DO jk = 1, jpkm1
-            peke = peke + SUM( zkepe(:,:,jk) * fsdept(:,:,jk) * e1e2t(:,:) * fse3t(:,:,jk) )
-         END DO
-         peke = grav * peke
-
-         ! I.3 Sums over the global domain
-         ! ---------------------------------
-         IF( lk_mpp ) THEN
-            CALL mpp_sum( peke )
-            CALL mpp_sum( umo , jptot_dyn )
-            CALL mpp_sum( vmo , jptot_dyn )
-            CALL mpp_sum( hke , jptot_dyn )
-         ENDIF
-
-         ! I.2 Print dynamic trends in the ocean.output file
-         ! --------------------------------------------------
-
-         IF(lwp) THEN
-            WRITE (numout,*)
-            WRITE (numout,*)
-            WRITE (numout,9500) kt
-            WRITE (numout,9501) umo(jpicpd_hpg) / tvolu, vmo(jpicpd_hpg) / tvolv
-            WRITE (numout,9502) umo(jpicpd_keg) / tvolu, vmo(jpicpd_keg) / tvolv
-            WRITE (numout,9503) umo(jpicpd_rvo) / tvolu, vmo(jpicpd_rvo) / tvolv
-            WRITE (numout,9504) umo(jpicpd_pvo) / tvolu, vmo(jpicpd_pvo) / tvolv
-            WRITE (numout,9505) umo(jpicpd_ldf) / tvolu, vmo(jpicpd_ldf) / tvolv
-            WRITE (numout,9506) umo(jpicpd_had) / tvolu, vmo(jpicpd_had) / tvolv
-            WRITE (numout,9507) umo(jpicpd_zad) / tvolu, vmo(jpicpd_zad) / tvolv
-            WRITE (numout,9508) umo(jpicpd_zdf) / tvolu, vmo(jpicpd_zdf) / tvolv
-            WRITE (numout,9509) umo(jpicpd_spg) / tvolu, vmo(jpicpd_spg) / tvolv
-            WRITE (numout,9510) umo(jpicpd_swf) / tvolu, vmo(jpicpd_swf) / tvolv
-            WRITE (numout,9511) umo(jpicpd_dat) / tvolu, vmo(jpicpd_dat) / tvolv
-            WRITE (numout,9512) umo(jpicpd_bfr) / tvolu, vmo(jpicpd_bfr) / tvolv
-            WRITE (numout,9513)
-            WRITE (numout,9514)                                                 &
-            &     (  umo(jpicpd_hpg) + umo(jpicpd_keg) + umo(jpicpd_rvo) + umo(jpicpd_pvo) + umo(jpicpd_ldf)   &
-            &      + umo(jpicpd_had) + umo(jpicpd_zad) + umo(jpicpd_zdf) + umo(jpicpd_spg) + umo(jpicpd_dat)   &
-            &      + umo(jpicpd_swf) + umo(jpicpd_bfr) ) / tvolu,   &
-            &     (  vmo(jpicpd_hpg) + vmo(jpicpd_keg) + vmo(jpicpd_rvo) + vmo(jpicpd_pvo) + vmo(jpicpd_ldf)   &
-            &      + vmo(jpicpd_had) + vmo(jpicpd_zad) + vmo(jpicpd_zdf) + vmo(jpicpd_spg) + vmo(jpicpd_dat)   &
-            &      + vmo(jpicpd_swf) + vmo(jpicpd_bfr) ) / tvolv
-         ENDIF
-
- 9500    FORMAT(' momentum trend at it= ', i6, ' :', /' ==============================')
- 9501    FORMAT(' pressure gradient          u= ', e20.13, '    v= ', e20.13)
- 9502    FORMAT(' ke gradient                u= ', e20.13, '    v= ', e20.13)
- 9503    FORMAT(' relative vorticity term    u= ', e20.13, '    v= ', e20.13)
- 9504    FORMAT(' coriolis term              u= ', e20.13, '    v= ', e20.13)
- 9505    FORMAT(' horizontal diffusion       u= ', e20.13, '    v= ', e20.13)
- 9506    FORMAT(' horizontal advection       u= ', e20.13, '    v= ', e20.13)
- 9507    FORMAT(' vertical advection         u= ', e20.13, '    v= ', e20.13)
- 9508    FORMAT(' vertical diffusion         u= ', e20.13, '    v= ', e20.13)
- 9509    FORMAT(' surface pressure gradient  u= ', e20.13, '    v= ', e20.13)
- 9510    FORMAT(' surface wind forcing       u= ', e20.13, '    v= ', e20.13)
- 9511    FORMAT(' dampimg term               u= ', e20.13, '    v= ', e20.13)
- 9512    FORMAT(' bottom flux                u= ', e20.13, '    v= ', e20.13)
- 9513    FORMAT(' -----------------------------------------------------------------------------')
- 9514    FORMAT(' total trend                u= ', e20.13, '    v= ', e20.13)
-
-         IF(lwp) THEN
-            WRITE (numout,*)
-            WRITE (numout,*)
-            WRITE (numout,9520) kt
-            WRITE (numout,9521) hke(jpicpd_hpg) / tvolt
-            WRITE (numout,9522) hke(jpicpd_keg) / tvolt
-            WRITE (numout,9523) hke(jpicpd_rvo) / tvolt
-            WRITE (numout,9524) hke(jpicpd_pvo) / tvolt
-            WRITE (numout,9525) hke(jpicpd_ldf) / tvolt
-            WRITE (numout,9526) hke(jpicpd_had) / tvolt
-            WRITE (numout,9527) hke(jpicpd_zad) / tvolt
-            WRITE (numout,9528) hke(jpicpd_zdf) / tvolt
-            WRITE (numout,9529) hke(jpicpd_spg) / tvolt
-            WRITE (numout,9530) hke(jpicpd_swf) / tvolt
-            WRITE (numout,9531) hke(jpicpd_dat) / tvolt
-            WRITE (numout,9532) hke(jpicpd_bfr) / tvolt
-            WRITE (numout,9533)
-            WRITE (numout,9534)   &
-            &     (  hke(jpicpd_hpg) + hke(jpicpd_keg) + hke(jpicpd_rvo) + hke(jpicpd_pvo) + hke(jpicpd_ldf)   &
-            &      + hke(jpicpd_had) + hke(jpicpd_zad) + hke(jpicpd_zdf) + hke(jpicpd_spg) + hke(jpicpd_dat)   &
-            &      + hke(jpicpd_swf) + hke(jpicpd_bfr) ) / tvolt
-         ENDIF
-
- 9520    FORMAT(' kinetic energy trend at it= ', i6, ' :', /' ====================================')
- 9521    FORMAT(' pressure gradient         u2= ', e20.13)
- 9522    FORMAT(' ke gradient               u2= ', e20.13)
- 9523    FORMAT(' relative vorticity term   u2= ', e20.13)
- 9524    FORMAT(' coriolis term             u2= ', e20.13)
- 9525    FORMAT(' horizontal diffusion      u2= ', e20.13)
- 9526    FORMAT(' horizontal advection      u2= ', e20.13)
- 9527    FORMAT(' vertical advection        u2= ', e20.13)
- 9528    FORMAT(' vertical diffusion        u2= ', e20.13)
- 9529    FORMAT(' surface pressure gradient u2= ', e20.13)
- 9530    FORMAT(' surface wind forcing      u2= ', e20.13)
- 9531    FORMAT(' dampimg term              u2= ', e20.13)
- 9532    FORMAT(' bottom flux               u2= ', e20.13)
- 9533    FORMAT(' --------------------------------------------------')
- 9534    FORMAT(' total trend               u2= ', e20.13)
-
-         IF(lwp) THEN
-            WRITE (numout,*)
-            WRITE (numout,*)
-            WRITE (numout,9540) kt
-            WRITE (numout,9541) ( hke(jpicpd_keg) + hke(jpicpd_rvo) + hke(jpicpd_had) + hke(jpicpd_zad) ) / tvolt
-            WRITE (numout,9542) ( hke(jpicpd_keg) + hke(jpicpd_had) + hke(jpicpd_zad) ) / tvolt
-            WRITE (numout,9543) ( hke(jpicpd_pvo) ) / tvolt
-            WRITE (numout,9544) ( hke(jpicpd_rvo) ) / tvolt
-            WRITE (numout,9545) ( hke(jpicpd_spg) ) / tvolt
-            WRITE (numout,9546) ( hke(jpicpd_ldf) ) / tvolt
-            WRITE (numout,9547) ( hke(jpicpd_zdf) ) / tvolt
-            WRITE (numout,9548) ( hke(jpicpd_hpg) ) / tvolt, rpktrd / tvolt
-            WRITE (numout,*)
-            WRITE (numout,*)
-         ENDIF
-
- 9540    FORMAT(' energetic consistency at it= ', i6, ' :', /' =========================================')
- 9541    FORMAT(' 0 = non linear term(true if key_vorenergy or key_combined): ', e20.13)
- 9542    FORMAT(' 0 = ke gradient + horizontal + vertical advection         : ', e20.13)
- 9543    FORMAT(' 0 = coriolis term  (true if key_vorenergy or key_combined): ', e20.13)
- 9544    FORMAT(' 0 = uh.( rot(u) x uh ) (true if enstrophy conser.)        : ', e20.13)
- 9545    FORMAT(' 0 = surface pressure gradient                             : ', e20.13)
- 9546    FORMAT(' 0 > horizontal diffusion                                  : ', e20.13)
- 9547    FORMAT(' 0 > vertical diffusion                                    : ', e20.13)
- 9548    FORMAT(' pressure gradient u2 = - 1/rau0 u.dz(rhop)                : ', e20.13, '  u.dz(rhop) =', e20.13)
-         !
-         ! Save potential to kinetic energy conversion for next time step
-         rpktrd = peke
-         !
-      ENDIF
-      !
-      CALL wrk_dealloc( jpi, jpj, jpk, zkx, zky, zkz, zkepe )
-      !
-   END SUBROUTINE trd_dwr
-
-
-   SUBROUTINE trd_twr( kt )
-      !!---------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_twr  ***
-      !! 
-      !! ** Purpose :  write active tracers trends in ocean.output 
-      !!----------------------------------------------------------------------
-      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
-      !!----------------------------------------------------------------------
-
-      ! I. Tracers trends
-      ! -----------------
-
-      IF( MOD(kt,nn_trd) == 0 .OR. kt == nit000 .OR. kt == nitend ) THEN
-
-         ! I.1 Sums over the global domain
-         ! -------------------------------
-         IF( lk_mpp ) THEN
-            CALL mpp_sum( tmo, jptot_tra )   
-            CALL mpp_sum( smo, jptot_tra )
-            CALL mpp_sum( t2 , jptot_tra )
-            CALL mpp_sum( s2 , jptot_tra )
-         ENDIF
-
-         ! I.2 Print tracers trends in the ocean.output file
-         ! --------------------------------------------------
-         
-         IF(lwp) THEN
-            WRITE (numout,*)
-            WRITE (numout,*)
-            WRITE (numout,9400) kt
-            WRITE (numout,9401)  tmo(jpicpt_xad) / tvolt, smo(jpicpt_xad) / tvolt
-            WRITE (numout,9411)  tmo(jpicpt_yad) / tvolt, smo(jpicpt_yad) / tvolt
-            WRITE (numout,9402)  tmo(jpicpt_zad) / tvolt, smo(jpicpt_zad) / tvolt
-            WRITE (numout,9403)  tmo(jpicpt_ldf) / tvolt, smo(jpicpt_ldf) / tvolt
-            WRITE (numout,9404)  tmo(jpicpt_zdf) / tvolt, smo(jpicpt_zdf) / tvolt
-            WRITE (numout,9405)  tmo(jpicpt_npc) / tvolt, smo(jpicpt_npc) / tvolt
-            WRITE (numout,9406)  tmo(jpicpt_dmp) / tvolt, smo(jpicpt_dmp) / tvolt
-            WRITE (numout,9407)  tmo(jpicpt_qsr) / tvolt
-            WRITE (numout,9408)  tmo(jpicpt_nsr) / tvolt, smo(jpicpt_nsr) / tvolt
-            WRITE (numout,9409) 
-            WRITE (numout,9410) (  tmo(jpicpt_xad) + tmo(jpicpt_yad) + tmo(jpicpt_zad) + tmo(jpicpt_ldf) + tmo(jpicpt_zdf)   &
-            &                    + tmo(jpicpt_npc) + tmo(jpicpt_dmp) + tmo(jpicpt_qsr) + tmo(jpicpt_nsr) ) / tvolt,   &
-            &                   (  smo(jpicpt_xad) + smo(jpicpt_yad) + smo(jpicpt_zad) + smo(jpicpt_ldf) + smo(jpicpt_zdf)   &
-            &                    + smo(jpicpt_npc) + smo(jpicpt_dmp)                   + smo(jpicpt_nsr) ) / tvolt
-         ENDIF
-
-9400     FORMAT(' tracer trend at it= ',i6,' :     temperature',   &
-              '              salinity',/' ============================')
-9401     FORMAT(' zonal      advection        ',e20.13,'     ',e20.13)
-9411     FORMAT(' meridional advection        ',e20.13,'     ',e20.13)
-9402     FORMAT(' vertical advection          ',e20.13,'     ',e20.13)
-9403     FORMAT(' horizontal diffusion        ',e20.13,'     ',e20.13)
-9404     FORMAT(' vertical diffusion          ',e20.13,'     ',e20.13)
-9405     FORMAT(' static instability mixing   ',e20.13,'     ',e20.13)
-9406     FORMAT(' damping term                ',e20.13,'     ',e20.13)
-9407     FORMAT(' penetrative qsr             ',e20.13)
-9408     FORMAT(' non solar radiation         ',e20.13,'     ',e20.13)
-9409     FORMAT(' -------------------------------------------------------------------------')
-9410     FORMAT(' total trend                 ',e20.13,'     ',e20.13)
-
-
-         IF(lwp) THEN
-            WRITE (numout,*)
-            WRITE (numout,*)
-            WRITE (numout,9420) kt
-            WRITE (numout,9421)   t2(jpicpt_xad) / tvolt, s2(jpicpt_xad) / tvolt
-            WRITE (numout,9431)   t2(jpicpt_yad) / tvolt, s2(jpicpt_yad) / tvolt
-            WRITE (numout,9422)   t2(jpicpt_zad) / tvolt, s2(jpicpt_zad) / tvolt
-            WRITE (numout,9423)   t2(jpicpt_ldf) / tvolt, s2(jpicpt_ldf) / tvolt
-            WRITE (numout,9424)   t2(jpicpt_zdf) / tvolt, s2(jpicpt_zdf) / tvolt
-            WRITE (numout,9425)   t2(jpicpt_npc) / tvolt, s2(jpicpt_npc) / tvolt
-            WRITE (numout,9426)   t2(jpicpt_dmp) / tvolt, s2(jpicpt_dmp) / tvolt
-            WRITE (numout,9427)   t2(jpicpt_qsr) / tvolt
-            WRITE (numout,9428)   t2(jpicpt_nsr) / tvolt, s2(jpicpt_nsr) / tvolt
-            WRITE (numout,9429)
-            WRITE (numout,9430) (  t2(jpicpt_xad) + t2(jpicpt_yad) + t2(jpicpt_zad) + t2(jpicpt_ldf) + t2(jpicpt_zdf)   &
-            &                    + t2(jpicpt_npc) + t2(jpicpt_dmp) + t2(jpicpt_qsr) + t2(jpicpt_nsr) ) / tvolt,   &
-            &                   (  s2(jpicpt_xad) + s2(jpicpt_yad) + s2(jpicpt_zad) + s2(jpicpt_ldf) + s2(jpicpt_zdf)   &
-            &                    + s2(jpicpt_npc) + s2(jpicpt_dmp)                  + s2(jpicpt_nsr) ) / tvolt
-         ENDIF
-
-9420     FORMAT(' tracer**2 trend at it= ', i6, ' :      temperature',   &
-            '               salinity', /, ' ===============================')
-9421     FORMAT(' zonal      advection      * t   ', e20.13, '     ', e20.13)
-9431     FORMAT(' meridional advection      * t   ', e20.13, '     ', e20.13)
-9422     FORMAT(' vertical advection        * t   ', e20.13, '     ', e20.13)
-9423     FORMAT(' horizontal diffusion      * t   ', e20.13, '     ', e20.13)
-9424     FORMAT(' vertical diffusion        * t   ', e20.13, '     ', e20.13)
-9425     FORMAT(' static instability mixing * t   ', e20.13, '     ', e20.13)
-9426     FORMAT(' damping term              * t   ', e20.13, '     ', e20.13)
-9427     FORMAT(' penetrative qsr           * t   ', e20.13)
-9428     FORMAT(' non solar radiation       * t   ', e20.13, '     ', e20.13)
-9429     FORMAT(' -----------------------------------------------------------------------------')
-9430     FORMAT(' total trend                *t = ', e20.13, '  *s = ', e20.13)
-
-
-         IF(lwp) THEN
-            WRITE (numout,*)
-            WRITE (numout,*)
-            WRITE (numout,9440) kt
-            WRITE (numout,9441) ( tmo(jpicpt_xad)+tmo(jpicpt_yad)+tmo(jpicpt_zad) )/tvolt,   &
-            &                   ( smo(jpicpt_xad)+smo(jpicpt_yad)+smo(jpicpt_zad) )/tvolt
-            WRITE (numout,9442)   tmo(jpicpt_zl1)/tvolt,  smo(jpicpt_zl1)/tvolt
-            WRITE (numout,9443)   tmo(jpicpt_ldf)/tvolt,  smo(jpicpt_ldf)/tvolt
-            WRITE (numout,9444)   tmo(jpicpt_zdf)/tvolt,  smo(jpicpt_zdf)/tvolt
-            WRITE (numout,9445)   tmo(jpicpt_npc)/tvolt,  smo(jpicpt_npc)/tvolt
-            WRITE (numout,9446) ( t2(jpicpt_xad)+t2(jpicpt_yad)+t2(jpicpt_zad) )/tvolt,    &
-            &                   ( s2(jpicpt_xad)+s2(jpicpt_yad)+s2(jpicpt_zad) )/tvolt
-            WRITE (numout,9447)   t2(jpicpt_ldf)/tvolt,   s2(jpicpt_ldf)/tvolt
-            WRITE (numout,9448)   t2(jpicpt_zdf)/tvolt,   s2(jpicpt_zdf)/tvolt
-            WRITE (numout,9449)   t2(jpicpt_npc)/tvolt,   s2(jpicpt_npc)/tvolt
-         ENDIF
-
-9440     FORMAT(' tracer consistency at it= ',i6,   &
-            ' :         temperature','                salinity',/,   &
-            ' ==================================')
-9441     FORMAT(' 0 = horizontal+vertical advection +    ',e20.13,'       ',e20.13)
-9442     FORMAT('     1st lev vertical advection         ',e20.13,'       ',e20.13)
-9443     FORMAT(' 0 = horizontal diffusion               ',e20.13,'       ',e20.13)
-9444     FORMAT(' 0 = vertical diffusion                 ',e20.13,'       ',e20.13)
-9445     FORMAT(' 0 = static instability mixing          ',e20.13,'       ',e20.13)
-9446     FORMAT(' 0 = horizontal+vertical advection * t  ',e20.13,'       ',e20.13)
-9447     FORMAT(' 0 > horizontal diffusion          * t  ',e20.13,'       ',e20.13)
-9448     FORMAT(' 0 > vertical diffusion            * t  ',e20.13,'       ',e20.13)
-9449     FORMAT(' 0 > static instability mixing     * t  ',e20.13,'       ',e20.13)
-         !
-      ENDIF
-      !
-   END SUBROUTINE trd_twr
-
-#   else
-   !!----------------------------------------------------------------------
-   !!   Default case :                                         Empty module
-   !!----------------------------------------------------------------------
-   INTERFACE trd_icp
-      MODULE PROCEDURE trd_2d, trd_3d
-   END INTERFACE
-
-CONTAINS
-   SUBROUTINE trd_2d( ptrd2dx, ptrd2dy, ktrd , ctype )       ! Empty routine
-      REAL, DIMENSION(:,:) ::   ptrd2dx, ptrd2dy
-      INTEGER                     , INTENT(in   ) ::   ktrd         ! tracer trend index
-      CHARACTER(len=3)            , INTENT(in   ) ::   ctype        ! momentum ('DYN') or tracers ('TRA') trends
-      WRITE(*,*) 'trd_2d: You should not have seen this print! error ?', &
-          &       ptrd2dx(1,1), ptrd2dy(1,1), ktrd, ctype
-   END SUBROUTINE trd_2d
-   SUBROUTINE trd_3d( ptrd3dx, ptrd3dy, ktrd , ctype )       ! Empty routine
-      REAL, DIMENSION(:,:,:) ::   ptrd3dx, ptrd3dy
-      INTEGER                     , INTENT(in   ) ::   ktrd         ! tracer trend index
-      CHARACTER(len=3)            , INTENT(in   ) ::   ctype        ! momentum ('DYN') or tracers ('TRA') trends
-      WRITE(*,*) 'trd_3d: You should not have seen this print! error ?', &
-          &       ptrd3dx(1,1,1), ptrd3dy(1,1,1), ktrd, ctype
-   END SUBROUTINE trd_3d
-   SUBROUTINE trd_icp_init               ! Empty routine
-   END SUBROUTINE trd_icp_init
-   SUBROUTINE trd_dwr( kt )          ! Empty routine
-      WRITE(*,*) 'trd_dwr: You should not have seen this print! error ?', kt
-   END SUBROUTINE trd_dwr
-   SUBROUTINE trd_twr( kt )          ! Empty routine
-      WRITE(*,*) 'trd_twr: You should not have seen this print! error ?', kt
-   END SUBROUTINE trd_twr
-#endif
-
-   !!======================================================================
-END MODULE trdicp
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdicp_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdicp_oce.F90	(revision 5074)
+++ 	(revision )
@@ -1,90 +1,0 @@
-MODULE trdicp_oce
-   !!======================================================================
-   !!                   ***  MODULE trdicp_oce  ***
-   !! Ocean trends :   set tracer and momentum trend variables
-   !!======================================================================
-
-   !!----------------------------------------------------------------------
-   !!   'key_trdtra'   or                         tracer trends diagnostics
-   !!   'key_trddyn'                            momentum trends diagnostics
-   !!----------------------------------------------------------------------
-   USE par_oce                 ! ocean parameters
-
-   IMPLICIT NONE
-   PUBLIC
-
-#if  defined key_trdtra   &&   defined key_trddyn    ||   defined key_esopa
-   LOGICAL, PARAMETER ::   lk_trdtra = .TRUE.    !: tracers  trend flag
-   LOGICAL, PARAMETER ::   lk_trddyn = .TRUE.    !: momentum trend flag
-#elif  defined key_trdtra
-   LOGICAL, PARAMETER ::   lk_trdtra = .TRUE.    !: tracers  trend flag
-   LOGICAL, PARAMETER ::   lk_trddyn = .FALSE.   !: momentum trend flag
-#elif  defined key_trddyn
-   LOGICAL, PARAMETER ::   lk_trdtra = .FALSE.   !: tracers  trend flag
-   LOGICAL, PARAMETER ::   lk_trddyn = .TRUE.    !: momentum trend flag
-#else
-   LOGICAL, PARAMETER ::   lk_trdtra = .FALSE.   !: tracers  trend flag
-   LOGICAL, PARAMETER ::   lk_trddyn = .FALSE.   !: momentum trend flag
-#endif
-
-   !                                        !!! => tracer trends indexes <=
-   INTEGER, PARAMETER ::   jpicpt_xad =  1   !: x- horizontal advection
-   INTEGER, PARAMETER ::   jpicpt_yad =  2   !: y- horizontal advection
-   INTEGER, PARAMETER ::   jpicpt_zad =  3   !: z- vertical   advection
-   INTEGER, PARAMETER ::   jpicpt_ldf =  4   !: lateral       diffusion
-   INTEGER, PARAMETER ::   jpicpt_zdf =  5   !: vertical diffusion (Kz)
-   INTEGER, PARAMETER ::   jpicpt_bbc =  6   !: Bottom Boundary Condition (geoth. flux) 
-   INTEGER, PARAMETER ::   jpicpt_bbl =  7   !: Bottom Boundary Layer (diffusive/convective)
-   INTEGER, PARAMETER ::   jpicpt_npc =  8   !: static instability mixing
-   INTEGER, PARAMETER ::   jpicpt_dmp =  9   !: damping
-   INTEGER, PARAMETER ::   jpicpt_qsr = 10   !: penetrative solar radiation
-   INTEGER, PARAMETER ::   jpicpt_nsr = 11   !: non solar radiation
-   INTEGER, PARAMETER ::   jpicpt_zl1 = 12   !: first level vertical flux
-
-   !                                        !!! => Total tracer trends indexes <=
-   INTEGER, PARAMETER ::   jptot_tra  = 12   !: change it when adding/removing one indice above
-   
-   !                                        !!! => dynamic trends indexes <=
-   INTEGER, PARAMETER ::   jpicpd_hpg =  1   !: hydrostatic pressure gradient 
-   INTEGER, PARAMETER ::   jpicpd_keg =  2   !: kinetic energy gradient
-   INTEGER, PARAMETER ::   jpicpd_rvo =  3   !: relative vorticity
-   INTEGER, PARAMETER ::   jpicpd_pvo =  4   !: planetary vorticity
-   INTEGER, PARAMETER ::   jpicpd_ldf =  5   !: lateral diffusion
-   INTEGER, PARAMETER ::   jpicpd_had =  6   !: horizontal advection
-   INTEGER, PARAMETER ::   jpicpd_zad =  7   !: vertical advection
-   INTEGER, PARAMETER ::   jpicpd_zdf =  8   !: vertical diffusion
-   INTEGER, PARAMETER ::   jpicpd_spg =  9   !: surface pressure gradient
-   INTEGER, PARAMETER ::   jpicpd_dat = 10   !: damping term
-   INTEGER, PARAMETER ::   jpicpd_swf = 11   !: surface wind forcing
-   INTEGER, PARAMETER ::   jpicpd_bfr = 12   !: bottom friction 
-
-   !                                        !!! => Total dynamic trends indexes <=
-   INTEGER, PARAMETER ::   jptot_dyn  = 12   !: change it when adding/removing one indice above
-   
-#if   defined key_trdtra   ||   defined key_trddyn   ||   defined key_esopa
-
-   !! Variables used for diagnostics
-   !!---------------------------------------------------------------------
-   REAL(wp) ::   tvolt        !: volume of the whole ocean computed at t-points
-   REAL(wp) ::   tvolu        !: volume of the whole ocean computed at u-points
-   REAL(wp) ::   tvolv        !: volume of the whole ocean computed at v-points
-
-   !! Tracers trends diagnostics variables
-   !!---------------------------------------------------------------------
-   REAL(wp), DIMENSION(jptot_tra) ::   tmo, smo         !: tracers trends average 
-   REAL(wp), DIMENSION(jptot_tra) ::   t2, s2           !: tracers square trends average 
-   
-   !! Momentum trends diagnostics variables
-   !!---------------------------------------------------------------------
-   REAL(wp), DIMENSION(jptot_dyn) ::   umo, vmo         !: momentum trends average 
-   REAL(wp), DIMENSION(jptot_dyn) ::   hke              !: momentum square trends average 
-   REAL(wp) ::   rpktrd   !: potential to kinetic energy conversion
-   REAL(wp) ::   peke     !: conversion potential energy - kinetic energy trend
-
-#endif
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$ 
-   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
-   !!======================================================================
-END MODULE trdicp_oce
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdini.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdini.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdini.F90	(revision 5075)
@@ -0,0 +1,108 @@
+MODULE trdini
+   !!======================================================================
+   !!                       ***  MODULE  trdini  ***
+   !! Ocean diagnostics:  ocean tracers and dynamic trends
+   !!=====================================================================
+   !! History :   3.5  !  2012-02  (G. Madec) add 3D trends output for T, S, U, V, PE and KE
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trd_init      : initialization step
+   !!----------------------------------------------------------------------
+   USE dom_oce        ! ocean domain
+   USE trd_oce        ! trends: ocean variables
+   USE trdken         ! trends: 3D kinetic   energy
+   USE trdpen         ! trends: 3D potential energy
+   USE trdglo         ! trends: global domain averaged tracers and dynamics
+   USE trdmxl         ! trends: mixed layer averaged trends (tracer only)
+   USE trdvor         ! trends: vertical averaged vorticity 
+   USE in_out_manager ! I/O manager
+   USE lib_mpp        ! MPP library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trd_init   ! called by nemogcm.F90 module
+
+   !! * Substitutions
+#  include "domzgr_substitute.h90"
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: trdini.F90 3329 2012-03-16 12:22:15Z gm $
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trd_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_init  ***
+      !! 
+      !! ** Purpose :   Initialization of trend diagnostics
+      !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! local integer
+      !!
+      NAMELIST/namtrd/ ln_dyn_trd, ln_KE_trd, ln_vor_trd, ln_dyn_mxl,   &
+         &             ln_tra_trd, ln_PE_trd, ln_glo_trd, ln_tra_mxl, nn_trd 
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namtrd in reference namelist : trends diagnostic
+      READ  ( numnam_ref, namtrd, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namtrd in reference namelist', lwp )
+      !
+      REWIND( numnam_cfg )              ! Namelist namtrd in configuration namelist : trends diagnostic
+      READ  ( numnam_cfg, namtrd, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namtrd in configuration namelist', lwp )
+      IF(lwm) WRITE( numond, namtrd )
+      !
+      IF(lwp) THEN                  ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) ' trd_init : Momentum/Tracers trends'
+         WRITE(numout,*) ' ~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namtrd : set trends parameters'
+         WRITE(numout,*) '      global domain averaged dyn & tra trends   ln_glo_trd  = ', ln_glo_trd
+         WRITE(numout,*) '      U & V trends: 3D output                   ln_dyn_trd  = ', ln_dyn_trd
+         WRITE(numout,*) '      U & V trends: Mixed Layer averaged        ln_dyn_mxl  = ', ln_dyn_mxl
+         WRITE(numout,*) '      T & S trends: 3D output                   ln_tra_trd  = ', ln_tra_trd
+         WRITE(numout,*) '      T & S trends: Mixed Layer averaged        ln_tra_mxl  = ', ln_tra_mxl
+         WRITE(numout,*) '      Kinetic   Energy trends                   ln_KE_trd   = ', ln_KE_trd
+         WRITE(numout,*) '      Potential Energy trends                   ln_PE_trd   = ', ln_PE_trd
+         WRITE(numout,*) '      Barotropic vorticity trends               ln_vor_trd  = ', ln_vor_trd
+         !
+         WRITE(numout,*) '      frequency of trends diagnostics (glo)     nn_trd      = ', nn_trd
+      ENDIF
+      !
+      !                             ! trend extraction flags  
+      l_trdtra = .FALSE.                                                       ! tracers  
+      IF ( ln_tra_trd .OR. ln_PE_trd .OR. ln_tra_mxl .OR.   &
+         & ln_glo_trd                                       )   l_trdtra = .TRUE. 
+      !
+      l_trddyn = .FALSE.                                                       ! momentum
+      IF ( ln_dyn_trd .OR. ln_KE_trd .OR. ln_dyn_mxl .OR.   &
+         & ln_vor_trd .OR. ln_glo_trd                       )   l_trddyn = .TRUE.
+      !
+
+!!gm check the stop below      
+      IF( ln_dyn_mxl )   CALL ctl_stop( 'ML diag on momentum are not yet coded we stop' )
+      !
+
+!!gm end
+      IF( ln_tra_mxl .OR. ln_vor_trd )   CALL ctl_stop( 'ML tracer and Barotropic vorticity diags are still using old IOIPSL' )
+!!gm end
+      !
+      IF( lk_vvl .AND. ( l_trdtra .OR. l_trddyn ) )  CALL ctl_stop( 'trend diagnostics with variable volume not validated' )
+      
+!!gm  : Potential BUG : 3D output only for vector invariant form!  add a ctl_stop or code the flux form case
+!!gm  : bug/pb for vertical advection of tracer in vvl case: add T.dt[eta] in the output... 
+
+      !                             ! diagnostic initialization  
+      IF( ln_glo_trd )   CALL trd_glo_init      ! global domain averaged trends
+      IF( ln_tra_mxl )   CALL trd_mxl_init      ! mixed-layer          trends  
+      IF( ln_vor_trd )   CALL trd_vor_init      ! barotropic vorticity trends
+      IF( ln_KE_trd  )   CALL trd_ken_init      ! 3D Kinetic    energy trends
+      IF( ln_PE_trd  )   CALL trd_pen_init      ! 3D Potential  energy trends
+      !
+   END SUBROUTINE trd_init
+
+   !!======================================================================
+END MODULE trdini
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdken.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdken.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdken.F90	(revision 5075)
@@ -0,0 +1,281 @@
+MODULE trdken
+   !!======================================================================
+   !!                       ***  MODULE  trdken  ***
+   !! Ocean diagnostics:  compute and output 3D kinetic energy trends
+   !!=====================================================================
+   !! History :  3.5  !  2012-02  (G. Madec) original code
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trd_ken       : compute and output 3D Kinetic energy trends using IOM
+   !!   trd_ken_init  : initialisation
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean space and time domain variables
+   USE zdf_oce        ! ocean vertical physics variables
+   USE trd_oce        ! trends: ocean variables
+!!gm   USE dynhpg          ! hydrostatic pressure gradient   
+   USE zdfbfr         ! bottom friction
+   USE ldftra_oce     ! ocean active tracers lateral physics
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE phycst         ! physical constants
+   USE trdvor         ! ocean vorticity trends 
+   USE trdglo         ! trends:global domain averaged
+   USE trdmxl         ! ocean active mixed layer tracers trends 
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE wrk_nemo       ! Memory allocation
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trd_ken       ! called by trddyn module
+   PUBLIC   trd_ken_init  ! called by trdini module
+
+   INTEGER ::   nkstp       ! current time step 
+
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   bu, bv   ! volume of u- and v-boxes
+   REAL(wp), ALLOCATABLE, DIMENSION(:,:,:) ::   r1_bt    ! inverse of t-box volume
+
+   !! * Substitutions
+#  include "domzgr_substitute.h90"
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: trdken.F90 3329 2012-03-16 12:22:15Z gm $
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_ken_alloc()
+      !!---------------------------------------------------------------------
+      !!                  ***  FUNCTION trd_ken_alloc  ***
+      !!---------------------------------------------------------------------
+      ALLOCATE( bu(jpi,jpj,jpk) , bv(jpi,jpj,jpk) , r1_bt(jpi,jpj,jpk) , STAT= trd_ken_alloc )
+      !
+      IF( lk_mpp             )   CALL mpp_sum ( trd_ken_alloc )
+      IF( trd_ken_alloc /= 0 )   CALL ctl_warn('trd_ken_alloc: failed to allocate arrays')
+   END FUNCTION trd_ken_alloc
+
+
+   SUBROUTINE trd_ken( putrd, pvtrd, ktrd, kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_ken  ***
+      !! 
+      !! ** Purpose :   output 3D Kinetic Energy trends using IOM
+      !!
+      !! ** Method  : - apply lbc to the input masked velocity trends 
+      !!              - compute the associated KE trend:
+      !!          zke = 0.5 * (  mi-1[ un * putrd * bu ] + mj-1[ vn * pvtrd * bv]  ) / bt
+      !!      where bu, bv, bt are the volume of u-, v- and t-boxes. 
+      !!              - vertical diffusion case (jpdyn_zdf): 
+      !!          diagnose separately the KE trend associated with wind stress
+      !!              - bottom friction case (jpdyn_bfr):
+      !!          explicit case (ln_bfrimp=F): bottom trend put in the 1st level 
+      !!                                       of putrd, pvtrd
+      !
+      !
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   putrd, pvtrd   ! U and V masked trends
+      INTEGER                   , INTENT(in   ) ::   ktrd           ! trend index
+      INTEGER                   , INTENT(in   ) ::   kt             ! time step
+      !
+      INTEGER ::   ji, jj, jk       ! dummy loop indices
+      INTEGER ::   ikbu  , ikbv     ! local integers
+      INTEGER ::   ikbum1, ikbvm1   !   -       -
+      REAL(wp), POINTER, DIMENSION(:,:)   ::   z2dx, z2dy, zke2d   ! 2D workspace 
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   zke                 ! 3D workspace 
+      !!----------------------------------------------------------------------
+      !
+      CALL wrk_alloc( jpi, jpj, jpk, zke )
+      !
+      CALL lbc_lnk( putrd, 'U', -1. )   ;   CALL lbc_lnk( pvtrd, 'V', -1. )      ! lateral boundary conditions
+      !
+      IF ( lk_vvl .AND. kt /= nkstp ) THEN   ! Variable volume: set box volume at the 1st call of kt time step
+         nkstp = kt
+         DO jk = 1, jpkm1
+            bu   (:,:,jk) =  e1u(:,:) * e2u(:,:) * fse3u_n(:,:,jk)
+            bv   (:,:,jk) =  e1v(:,:) * e2v(:,:) * fse3v_n(:,:,jk)
+            r1_bt(:,:,jk) = 1._wp / ( e1e2t(:,:) * fse3t_n(:,:,jk) ) * tmask(:,:,jk)
+         END DO
+      ENDIF
+      !
+      zke(:,:,jpk) = 0._wp
+      zke(1,:, : ) = 0._wp
+      zke(:,1, : ) = 0._wp
+      DO jk = 1, jpkm1
+         DO jj = 2, jpj
+            DO ji = 2, jpi
+               zke(ji,jj,jk) = 0.5_wp * rau0 *( un(ji  ,jj,jk) * putrd(ji  ,jj,jk) * bu(ji  ,jj,jk)  &
+                  &                           + un(ji-1,jj,jk) * putrd(ji-1,jj,jk) * bu(ji-1,jj,jk)  &
+                  &                           + vn(ji,jj  ,jk) * pvtrd(ji,jj  ,jk) * bv(ji,jj  ,jk)  &
+                  &                           + vn(ji,jj-1,jk) * pvtrd(ji,jj-1,jk) * bv(ji,jj-1,jk)  ) * r1_bt(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      SELECT CASE( ktrd )
+      	CASE( jpdyn_hpg )   ;   CALL iom_put( "ketrd_hpg", zke )    ! hydrostatic pressure gradient
+      	CASE( jpdyn_spg )   ;   CALL iom_put( "ketrd_spg", zke )    ! surface pressure gradient
+      	CASE( jpdyn_spgexp );   CALL iom_put( "ketrd_spgexp", zke ) ! surface pressure gradient (explicit)
+      	CASE( jpdyn_spgflt );   CALL iom_put( "ketrd_spgflt", zke ) ! surface pressure gradient (filter)
+      	CASE( jpdyn_pvo )   ;   CALL iom_put( "ketrd_pvo", zke )    ! planetary vorticity
+      	CASE( jpdyn_rvo )   ;   CALL iom_put( "ketrd_rvo", zke )    ! relative  vorticity     (or metric term)
+      	CASE( jpdyn_keg )   ;   CALL iom_put( "ketrd_keg", zke )    ! Kinetic Energy gradient (or had)
+      	CASE( jpdyn_zad )   ;   CALL iom_put( "ketrd_zad", zke )    ! vertical   advection
+      	CASE( jpdyn_ldf )   ;   CALL iom_put( "ketrd_ldf", zke )    ! lateral diffusion
+      	CASE( jpdyn_zdf )   ;   CALL iom_put( "ketrd_zdf", zke )    ! vertical diffusion 
+                                 !                                   ! wind stress trends
+                              	CALL wrk_alloc( jpi, jpj, z2dx, z2dy, zke2d )
+         						z2dx(:,:) = un(:,:,1) * ( utau_b(:,:) + utau(:,:) ) * e1u(:,:) * e2u(:,:) * umask(:,:,1)
+         						z2dy(:,:) = vn(:,:,1) * ( vtau_b(:,:) + vtau(:,:) ) * e1v(:,:) * e2v(:,:) * vmask(:,:,1)
+         						zke2d(1,:) = 0._wp   ;   zke2d(:,1) = 0._wp
+         						DO jj = 2, jpj
+            					   DO ji = 2, jpi
+               						zke2d(ji,jj) = 0.5_wp * (   z2dx(ji,jj) + z2dx(ji-1,jj)   &
+                  					&                         + z2dy(ji,jj) + z2dy(ji,jj-1)   ) * r1_bt(ji,jj,1)
+            					   END DO
+         						END DO
+                              	CALL iom_put( "ketrd_tau", zke2d )
+                              	CALL wrk_dealloc( jpi, jpj     , z2dx, z2dy, zke2d )
+      	CASE( jpdyn_bfr )   ;   CALL iom_put( "ketrd_bfr", zke )    ! bottom friction (explicit case) 
+!!gm TO BE DONE properly
+!!gm only valid if ln_bfrimp=F otherwise the bottom stress as to be recomputed at the end of the computation....
+!         IF(.NOT. ln_bfrimp) THEN
+!            DO jj = 1, jpj    !   
+!               DO ji = 1, jpi
+!                  ikbu = mbku(ji,jj)         ! deepest ocean u- & v-levels
+!                  ikbv = mbkv(ji,jj)   
+!                  z2dx(ji,jj) = un(ji,jj,ikbu) * bfrua(ji,jj) * un(ji,jj,ikbu)
+!                  z2dy(ji,jj) = vn(ji,jj,ikbu) * bfrva(ji,jj) * vn(ji,jj,ikbv)
+!               END DO
+!            END DO
+!            zke2d(1,:) = 0._wp   ;   zke2d(:,1) = 0._wp
+!            DO jj = 2, jpj
+!               DO ji = 2, jpi
+!                  zke2d(ji,jj) = 0.5_wp * (   z2dx(ji,jj) + z2dx(ji-1,jj)   &
+!                     &                      + z2dy(ji,jj) + z2dy(ji,jj-1)   ) * r1_bt(ji,jj,  BEURK!!!
+!               END DO
+!            END DO
+!                              CALL iom_put( "ketrd_bfr", zke2d )    ! bottom friction (explicit case)
+!         ENDIF
+!!gm end
+      	CASE( jpdyn_atf )   ;   CALL iom_put( "ketrd_atf", zke )    ! asselin filter trends 
+!! a faire !!!!  idee changer dynnxt pour avoir un appel a jpdyn_bfr avant le swap !!!
+!! reflechir a une possible sauvegarde du "vrai" un,vn pour le calcul de atf....
+!
+!         IF( ln_bfrimp ) THEN                                          ! bottom friction (implicit case)
+!            DO jj = 1, jpj                                                  ! after velocity known (now filed at this stage)
+!               DO ji = 1, jpi
+!                  ikbu = mbku(ji,jj)          ! deepest ocean u- & v-levels
+!                  ikbv = mbkv(ji,jj)
+!                  z2dx(ji,jj) = un(ji,jj,ikbu) * bfrua(ji,jj) * un(ji,jj,ikbu) / fse3u(ji,jj,ikbu)
+!                  z2dy(ji,jj) = un(ji,jj,ikbu) * bfrva(ji,jj) * vn(ji,jj,ikbv) / fse3v(ji,jj,ikbv)
+!               END DO
+!            END DO
+!            zke2d(1,:) = 0._wp   ;   zke2d(:,1) = 0._wp
+!            DO jj = 2, jpj
+!               DO ji = 2, jpi
+!                  zke2d(ji,jj) = 0.5_wp * (   z2dx(ji,jj) + z2dx(ji-1,jj)   &
+!                     &                      + z2dy(ji,jj) + z2dy(ji,jj-1)   )
+!               END DO
+!            END DO
+!                              CALL iom_put( "ketrd_bfri", zke2d )
+!         ENDIF
+      	CASE( jpdyn_ken )   ;   ! kinetic energy
+      							! called in dynnxt.F90 before asselin time filter
+      							! with putrd=ua and pvtrd=va
+      							zke(:,:,:) = 0.5_wp * zke(:,:,:)
+      							CALL iom_put( "KE", zke )
+      							!
+      							CALL ken_p2k( kt , zke )
+            					CALL iom_put( "ketrd_convP2K", zke )     ! conversion -rau*g*w
+         !
+      END SELECT
+      !
+      CALL wrk_dealloc( jpi, jpj, jpk, zke )
+      !
+   END SUBROUTINE trd_ken
+
+
+   SUBROUTINE ken_p2k( kt , pconv )
+      !!---------------------------------------------------------------------
+      !!                 ***  ROUTINE ken_p2k  ***
+      !!                    
+      !! ** Purpose :   compute rate of conversion from potential to kinetic energy
+      !!
+      !! ** Method  : - compute conv defined as -rau*g*w on T-grid points
+      !! 
+      !! ** Work only for full steps and partial steps (ln_hpg_zco or ln_hpg_zps)
+      !!---------------------------------------------------------------------- 
+      INTEGER, INTENT(in) ::   kt    ! ocean time-step index
+      !!
+      REAL(wp), DIMENSION(jpi,jpj,jpk     ), INTENT(  out) ::   pconv
+      !
+      INTEGER  ::   ji, jj, jk                       ! dummy loop indices
+      INTEGER  ::   iku, ikv                         ! temporary integers
+      REAL(wp) ::   zcoef                            ! temporary scalars
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::  zconv  ! temporary conv on W-grid
+      !!----------------------------------------------------------------------
+      !
+      CALL wrk_alloc( jpi,jpj,jpk, zconv )
+      !
+      ! Local constant initialization 
+      zcoef = - rau0 * grav * 0.5_wp      
+      
+      !  Surface value (also valid in partial step case)
+      zconv(:,:,1) = zcoef * ( 2._wp * rhd(:,:,1) ) * wn(:,:,1) * fse3w(:,:,1)
+
+      ! interior value (2=<jk=<jpkm1)
+      DO jk = 2, jpk
+         zconv(:,:,jk) = zcoef * ( rhd(:,:,jk) + rhd(:,:,jk-1) ) * wn(:,:,jk) * fse3w(:,:,jk)
+      END DO
+
+      ! conv value on T-point
+      DO jk = 1, jpkm1
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               zcoef = 0.5_wp / fse3t(ji,jj,jk)
+               pconv(ji,jj,jk) = zcoef * ( zconv(ji,jj,jk) + zconv(ji,jj,jk+1) ) * tmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      !
+      CALL wrk_dealloc( jpi,jpj,jpk, zconv )      
+      !
+   END SUBROUTINE ken_p2k
+
+
+   SUBROUTINE trd_ken_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_ken_init  ***
+      !! 
+      !! ** Purpose :   initialisation of 3D Kinetic Energy trend diagnostic
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trd_ken_init : 3D Kinetic Energy trends'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !                           ! allocate box volume arrays
+      IF ( trd_ken_alloc() /= 0 )   CALL ctl_stop('trd_ken_alloc: failed to allocate arrays')
+      !
+!!gm      IF( .NOT. (ln_hpg_zco.OR.ln_hpg_zps) )   &
+!!gm         &   CALL ctl_stop('trd_ken_init : only full and partial cells are coded for conversion rate')
+      !
+      IF ( .NOT.lk_vvl ) THEN     ! constant volume: bu, bv, 1/bt computed one for all
+         DO jk = 1, jpkm1
+            bu   (:,:,jk) =  e1u(:,:) * e2u(:,:) * fse3u_n(:,:,jk)
+            bv   (:,:,jk) =  e1v(:,:) * e2v(:,:) * fse3v_n(:,:,jk)
+            r1_bt(:,:,jk) = 1._wp / ( e1e2t(:,:) * fse3t_n(:,:,jk) )
+         END DO
+      ENDIF
+      !
+   END SUBROUTINE trd_ken_init
+
+   !!======================================================================
+END MODULE trdken
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmld.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmld.F90	(revision 5074)
+++ 	(revision )
@@ -1,979 +1,0 @@
-MODULE trdmld
-   !!======================================================================
-   !!                       ***  MODULE  trdmld  ***
-   !! Ocean diagnostics:  mixed layer T-S trends 
-   !!=====================================================================
-   !! History :       !  95-04  (J. Vialard)    Original code
-   !!                 !  97-02  (E. Guilyardi)  Adaptation global + base cmo
-   !!                 !  99-09  (E. Guilyardi)  Re-writing + netCDF output
-   !!            8.5  !  02-06  (G. Madec)      F90: Free form and module
-   !!            9.0  !  04-08  (C. Talandier)  New trends organization
-   !!                 !  05-05  (C. Deltel)     Diagnose trends of time averaged ML T & S
-   !!----------------------------------------------------------------------
-#if   defined key_trdmld   ||   defined key_esopa
-   !!----------------------------------------------------------------------
-   !!   'key_trdmld'                          mixed layer trend diagnostics
-   !!----------------------------------------------------------------------
-   !!   trd_mld          : T and S cumulated trends averaged over the mixed layer
-   !!   trd_mld_zint     : T and S trends vertical integration
-   !!   trd_mld_init     : initialization step
-   !!----------------------------------------------------------------------
-   USE oce             ! ocean dynamics and tracers variables
-   USE dom_oce         ! ocean space and time domain variables
-   USE trdmod_oce      ! ocean variables trends
-   USE trdmld_oce      ! ocean variables trends
-   USE ldftra_oce      ! ocean active tracers lateral physics
-   USE zdf_oce         ! ocean vertical physics
-   USE in_out_manager  ! I/O manager
-   USE phycst          ! Define parameters for the routines
-   USE dianam          ! build the name of file (routine)
-   USE ldfslp          ! iso-neutral slopes 
-   USE zdfmxl          ! mixed layer depth
-   USE zdfddm          ! ocean vertical physics: double diffusion
-   USE ioipsl          ! NetCDF library
-   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
-   USE diadimg         ! dimg direct access file format output
-   USE trdmld_rst      ! restart for diagnosing the ML trends
-   USE prtctl          ! Print control
-   USE lib_mpp         ! MPP library
-   USE wrk_nemo        ! Memory allocation
-
-   IMPLICIT NONE
-   PRIVATE
-
-   PUBLIC   trd_mld        ! routine called by step.F90
-   PUBLIC   trd_mld_init   ! routine called by opa.F90
-   PUBLIC   trd_mld_zint   ! routine called by tracers routines
-
-   CHARACTER (LEN=40) ::  clhstnam         ! name of the trends NetCDF file
-   INTEGER ::   nh_t, nmoymltrd
-   INTEGER ::   nidtrd
-   INTEGER, ALLOCATABLE, SAVE, DIMENSION(:) ::   ndextrd1
-   INTEGER ::   ndimtrd1                        
-   INTEGER ::   ionce, icount                   
-
-   !! * Substitutions
-#  include "domzgr_substitute.h90"
-#  include "ldftra_substitute.h90"
-#  include "zdfddm_substitute.h90"
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$ 
-   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-CONTAINS
-
-   INTEGER FUNCTION trd_mld_alloc()
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld_alloc  ***
-      !!----------------------------------------------------------------------
-      ALLOCATE( ndextrd1(jpi*jpj) , STAT=trd_mld_alloc )
-      !
-      IF( lk_mpp             )   CALL mpp_sum ( trd_mld_alloc )
-      IF( trd_mld_alloc /= 0 )   CALL ctl_warn('trd_mld_alloc: failed to allocate array ndextrd1')
-   END FUNCTION trd_mld_alloc
-
-
-   SUBROUTINE trd_mld_zint( pttrdmld, pstrdmld, ktrd, ctype )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld_zint  ***
-      !! 
-      !! ** Purpose :   Compute the vertical average of the 3D fields given as arguments 
-      !!                to the subroutine. This vertical average is performed from ocean
-      !!                surface down to a chosen control surface.
-      !!
-      !! ** Method/usage :
-      !!      The control surface can be either a mixed layer depth (time varying)
-      !!      or a fixed surface (jk level or bowl). 
-      !!      Choose control surface with nn_ctls in namelist NAMTRD :
-      !!        nn_ctls = 0  : use mixed layer with density criterion 
-      !!        nn_ctls = 1  : read index from file 'ctlsurf_idx'
-      !!        nn_ctls > 1  : use fixed level surface jk = nn_ctls
-      !!      Note: in the remainder of the routine, the volume between the 
-      !!            surface and the control surface is called "mixed-layer"
-      !!----------------------------------------------------------------------
-      !
-      INTEGER                         , INTENT( in ) ::   ktrd       ! ocean trend index
-      CHARACTER(len=2)                , INTENT( in ) ::   ctype      ! 2D surface/bottom or 3D interior physics
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( in ) ::   pttrdmld   ! temperature trend 
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( in ) ::   pstrdmld   ! salinity trend 
-      !
-      INTEGER ::   ji, jj, jk, isum
-      REAL(wp), POINTER, DIMENSION(:,:)  :: zvlmsk 
-      !!----------------------------------------------------------------------
-
-      CALL wrk_alloc( jpi, jpj, zvlmsk ) 
-
-      ! I. Definition of control surface and associated fields
-      ! ------------------------------------------------------
-      !            ==> only once per time step <== 
-
-      IF( icount == 1 ) THEN        
-         !
-         tmltrd(:,:,:) = 0.e0    ;    smltrd(:,:,:) = 0.e0    ! <<< reset trend arrays to zero
-         
-         ! ... Set nmld(ji,jj) = index of first T point below control surf. or outside mixed-layer
-         IF( nn_ctls == 0 ) THEN       ! * control surface = mixed-layer with density criterion 
-            nmld(:,:) = nmln(:,:)    ! array nmln computed in zdfmxl.F90
-         ELSE IF( nn_ctls == 1 ) THEN  ! * control surface = read index from file 
-            nmld(:,:) = nbol(:,:)
-         ELSE IF( nn_ctls >= 2 ) THEN  ! * control surface = model level
-            nn_ctls = MIN( nn_ctls, jpktrd - 1 )
-            nmld(:,:) = nn_ctls + 1
-         ENDIF
-
-         ! ... Compute ndextrd1 and ndimtrd1 only once
-         IF( ionce == 1 ) THEN
-            !
-            ! Check of validity : nmld(ji,jj) <= jpktrd
-            isum        = 0
-            zvlmsk(:,:) = 0.e0
-
-            IF( jpktrd < jpk ) THEN 
-               DO jj = 1, jpj
-                  DO ji = 1, jpi
-                     IF( nmld(ji,jj) <= jpktrd ) THEN
-                        zvlmsk(ji,jj) = tmask(ji,jj,1)
-                     ELSE
-                        isum = isum + 1
-                        zvlmsk(ji,jj) = 0.
-                     ENDIF
-                  END DO
-               END DO
-            ENDIF
-
-            ! Index of ocean points (2D only)
-            IF( isum > 0 ) THEN
-               WRITE(numout,*)' Number of invalid points nmld > jpktrd', isum 
-               CALL wheneq( jpi*jpj, zvlmsk(:,:) , 1, 1., ndextrd1, ndimtrd1 )    ! surface
-            ELSE 
-               CALL wheneq( jpi*jpj, tmask(:,:,1), 1, 1., ndextrd1, ndimtrd1 )    ! surface
-            ENDIF                                
-
-            ionce = 0                ! no more pass here
-            !
-         END IF
-         
-         ! ... Weights for vertical averaging
-         wkx(:,:,:) = 0.e0
-         DO jk = 1, jpktrd             ! initialize wkx with vertical scale factor in mixed-layer
-            DO jj = 1,jpj
-               DO ji = 1,jpi
-                  IF( jk - nmld(ji,jj) < 0.e0 )   wkx(ji,jj,jk) = fse3t(ji,jj,jk) * tmask(ji,jj,jk)
-               END DO
-            END DO
-         END DO
-         
-         rmld(:,:) = 0.e0                ! compute mixed-layer depth : rmld
-         DO jk = 1, jpktrd
-            rmld(:,:) = rmld(:,:) + wkx(:,:,jk)
-         END DO
-         
-         DO jk = 1, jpktrd             ! compute integration weights
-            wkx(:,:,jk) = wkx(:,:,jk) / MAX( 1., rmld(:,:) )
-         END DO
-
-         icount = 0                    ! <<< flag = off : control surface & integr. weights
-         !                             !     computed only once per time step
-      END IF
-
-      ! II. Vertical integration of trends in the mixed-layer
-      ! -----------------------------------------------------
-
-      SELECT CASE (ctype)
-      CASE ( '3D' )   ! mean T/S trends in the mixed-layer
-         DO jk = 1, jpktrd
-            tmltrd(:,:,ktrd) = tmltrd(:,:,ktrd) + pttrdmld(:,:,jk) * wkx(:,:,jk)   ! temperature
-            smltrd(:,:,ktrd) = smltrd(:,:,ktrd) + pstrdmld(:,:,jk) * wkx(:,:,jk)   ! salinity
-         END DO
-      CASE ( '2D' )   ! forcing at upper boundary of the mixed-layer
-         tmltrd(:,:,ktrd) = tmltrd(:,:,ktrd) + pttrdmld(:,:,1) * wkx(:,:,1)        ! non penetrative
-         smltrd(:,:,ktrd) = smltrd(:,:,ktrd) + pstrdmld(:,:,1) * wkx(:,:,1)            
-      END SELECT
-      !
-      CALL wrk_dealloc( jpi, jpj, zvlmsk ) 
-      !
-   END SUBROUTINE trd_mld_zint
-    
-
-   SUBROUTINE trd_mld( kt )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld  ***
-      !! 
-      !! ** Purpose :  Compute and cumulate the mixed layer trends over an analysis
-      !!               period, and write NetCDF (or dimg) outputs.
-      !!
-      !! ** Method/usage :
-      !!          The stored trends can be chosen twofold (according to the ln_trdmld_instant 
-      !!          logical namelist variable) :
-      !!          1) to explain the difference between initial and final 
-      !!             mixed-layer T & S (where initial and final relate to the
-      !!             current analysis window, defined by nn_trd in the namelist)
-      !!          2) to explain the difference between the current and previous 
-      !!             TIME-AVERAGED mixed-layer T & S (where time-averaging is
-      !!             performed over each analysis window).
-      !!
-      !! ** Consistency check : 
-      !!        If the control surface is fixed ( nn_ctls > 1 ), the residual term (dh/dt
-      !!        entrainment) should be zero, at machine accuracy. Note that in the case
-      !!        of time-averaged mixed-layer fields, this residual WILL NOT BE ZERO
-      !!        over the first two analysis windows (except if restart).
-      !!        N.B. For ORCA2_LIM, use e.g. nn_trd=5, rn_ucf=1., nn_ctls=8
-      !!             for checking residuals.
-      !!             On a NEC-SX5 computer, this typically leads to:
-      !!                   O(1.e-20) temp. residuals (tml_res) when ln_trdmld_instant=.false.
-      !!                   O(1.e-21) temp. residuals (tml_res) when ln_trdmld_instant=.true.
-      !!
-      !! ** Action :
-      !!       At each time step, mixed-layer averaged trends are stored in the 
-      !!       tmltrd(:,:,jpmld_xxx) array (see trdmld_oce.F90 for definitions of jpmld_xxx).
-      !!       This array is known when trd_mld is called, at the end of the stp subroutine, 
-      !!       except for the purely vertical K_z diffusion term, which is embedded in the
-      !!       lateral diffusion trend.
-      !!
-      !!       In I), this K_z term is diagnosed and stored, thus its contribution is removed
-      !!       from the lateral diffusion trend.
-      !!       In II), the instantaneous mixed-layer T & S are computed, and misc. cumulative
-      !!       arrays are updated.
-      !!       In III), called only once per analysis window, we compute the total trends,
-      !!       along with the residuals and the Asselin correction terms.
-      !!       In IV), the appropriate trends are written in the trends NetCDF file.
-      !!
-      !! References :
-      !!       - Vialard & al.
-      !!       - See NEMO documentation (in preparation)
-      !!----------------------------------------------------------------------
-      !
-      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
-      !
-      INTEGER :: ji, jj, jk, jl, ik, it, itmod
-      LOGICAL :: lldebug = .TRUE.
-      REAL(wp) :: zavt, zfn, zfn2
-      !                                              ! z(ts)mltot : dT/dt over the anlysis window (including Asselin)
-      !                                              ! z(ts)mlres : residual = dh/dt entrainment term
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::  ztmltot , zsmltot , ztmlres , zsmlres , ztmlatf , zsmlatf
-      REAL(wp), POINTER, DIMENSION(:,:  ) ::  ztmltot2, zsmltot2, ztmlres2, zsmlres2, ztmlatf2, zsmlatf2, ztmltrdm2, zsmltrdm2  
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztmltrd2, zsmltrd2   ! only needed for mean diagnostics
-#if defined key_dimgout
-      INTEGER ::  iyear,imon,iday
-      CHARACTER(LEN=80) :: cltext, clmode
-#endif
-      !!----------------------------------------------------------------------
-  
-      CALL wrk_alloc( jpi, jpj,         ztmltot , zsmltot , ztmlres , zsmlres , ztmlatf , zsmlatf                        )
-      CALL wrk_alloc( jpi, jpj,         ztmltot2, zsmltot2, ztmlres2, zsmlres2, ztmlatf2, zsmlatf2, ztmltrdm2, zsmltrdm2 )  
-      CALL wrk_alloc( jpi, jpj, jpltrd, ztmltrd2, zsmltrd2                                                               )
-
-      ! ======================================================================
-      ! I. Diagnose the purely vertical (K_z) diffusion trend
-      ! ======================================================================
-
-      ! ... These terms can be estimated by flux computation at the lower boundary of the ML 
-      !     (we compute (-1/h) * K_z * d_z( T ) and (-1/h) * K_z * d_z( S ))
-      IF( ln_traldf_iso ) THEN
-         DO jj = 1,jpj
-            DO ji = 1,jpi
-               ik = nmld(ji,jj)
-               zavt = avt(ji,jj,ik)
-               tmltrd(ji,jj,jpmld_zdf) = - zavt / fse3w(ji,jj,ik) * tmask(ji,jj,ik)  &
-                  &                      * ( tsn(ji,jj,ik-1,jp_tem) - tsn(ji,jj,ik,jp_tem) )         &
-                  &                      / MAX( 1., rmld(ji,jj) ) * tmask(ji,jj,1)
-               zavt = fsavs(ji,jj,ik)
-               smltrd(ji,jj,jpmld_zdf) = - zavt / fse3w(ji,jj,ik) * tmask(ji,jj,ik)  &
-                  &                      * ( tsn(ji,jj,ik-1,jp_sal) - tsn(ji,jj,ik,jp_sal) )         &
-                  &                      / MAX( 1., rmld(ji,jj) ) * tmask(ji,jj,1)
-            END DO
-         END DO
-
-         ! ... Remove this K_z trend from the iso-neutral diffusion term (if any)
-         tmltrd(:,:,jpmld_ldf) = tmltrd(:,:,jpmld_ldf) - tmltrd(:,:,jpmld_zdf)
-         smltrd(:,:,jpmld_ldf) = smltrd(:,:,jpmld_ldf) - smltrd(:,:,jpmld_zdf)
-      END IF
-
-      ! ... Lateral boundary conditions
-      DO jl = 1, jpltrd
-         CALL lbc_lnk( tmltrd(:,:,jl), 'T', 1. )
-         CALL lbc_lnk( smltrd(:,:,jl), 'T', 1. )
-      END DO
-
-      ! ======================================================================
-      ! II. Cumulate the trends over the analysis window
-      ! ======================================================================
-
-      ztmltrd2(:,:,:) = 0.e0   ;    zsmltrd2(:,:,:) = 0.e0  ! <<< reset arrays to zero
-      ztmltot2(:,:)   = 0.e0   ;    zsmltot2(:,:)   = 0.e0
-      ztmlres2(:,:)   = 0.e0   ;    zsmlres2(:,:)   = 0.e0
-      ztmlatf2(:,:)   = 0.e0   ;    zsmlatf2(:,:)   = 0.e0
-
-      ! II.1 Set before values of vertically average T and S 
-      ! ----------------------------------------------------
-      IF( kt > nit000 ) THEN
-         !   ... temperature ...                    ... salinity ...
-         tmlb   (:,:) = tml   (:,:)           ; smlb   (:,:) = sml   (:,:)
-         tmlatfn(:,:) = tmltrd(:,:,jpmld_atf) ; smlatfn(:,:) = smltrd(:,:,jpmld_atf)
-      END IF
-
-      ! II.2 Vertically averaged T and S
-      ! --------------------------------
-      tml(:,:) = 0.e0   ;   sml(:,:) = 0.e0
-      DO jk = 1, jpktrd - 1
-         tml(:,:) = tml(:,:) + wkx(:,:,jk) * tsn(:,:,jk,jp_tem)
-         sml(:,:) = sml(:,:) + wkx(:,:,jk) * tsn(:,:,jk,jp_sal)
-      END DO
-
-      ! II.3 Initialize mixed-layer "before" arrays for the 1rst analysis window    
-      ! ------------------------------------------------------------------------
-      IF( kt == 2 ) THEN  !  i.e. ( .NOT. ln_rstart ).AND.( kt == nit000 + 1)
-         !
-         !   ... temperature ...                ... salinity ...
-         tmlbb  (:,:) = tmlb   (:,:)   ;   smlbb  (:,:) = smlb   (:,:)
-         tmlbn  (:,:) = tml    (:,:)   ;   smlbn  (:,:) = sml    (:,:)
-         tmlatfb(:,:) = tmlatfn(:,:)   ;   smlatfb(:,:) = smlatfn(:,:)
-         
-         tmltrd_csum_ub (:,:,:) = 0.e0  ;   smltrd_csum_ub (:,:,:) = 0.e0
-         tmltrd_atf_sumb(:,:)   = 0.e0  ;   smltrd_atf_sumb(:,:)   = 0.e0
-
-         rmldbn(:,:) = rmld(:,:)
-
-         IF( ln_ctl ) THEN
-            WRITE(numout,*) '             we reach kt == nit000 + 1 = ', nit000+1
-            CALL prt_ctl(tab2d_1=tmlbb   , clinfo1=' tmlbb   -   : ', mask1=tmask, ovlap=1)
-            CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask, ovlap=1)
-            CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask, ovlap=1)
-         END IF
-         !
-      END IF
-
-      IF( ( ln_rstart ) .AND. ( kt == nit000 ) .AND. ( ln_ctl ) ) THEN
-         IF( ln_trdmld_instant ) THEN
-            WRITE(numout,*) '             restart from kt == nit000 = ', nit000
-            CALL prt_ctl(tab2d_1=tmlbb   , clinfo1=' tmlbb   -   : ', mask1=tmask, ovlap=1)
-            CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask, ovlap=1)
-            CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask, ovlap=1)
-         ELSE
-            WRITE(numout,*) '             restart from kt == nit000 = ', nit000
-            CALL prt_ctl(tab2d_1=tmlbn          , clinfo1=' tmlbn           -  : ', mask1=tmask, ovlap=1)
-            CALL prt_ctl(tab2d_1=rmldbn         , clinfo1=' rmldbn          -  : ', mask1=tmask, ovlap=1)
-            CALL prt_ctl(tab2d_1=tml_sumb       , clinfo1=' tml_sumb        -  : ', mask1=tmask, ovlap=1)
-            CALL prt_ctl(tab2d_1=tmltrd_atf_sumb, clinfo1=' tmltrd_atf_sumb -  : ', mask1=tmask, ovlap=1)
-            CALL prt_ctl(tab3d_1=tmltrd_csum_ub , clinfo1=' tmltrd_csum_ub  -  : ', mask1=tmask, ovlap=1, kdim=1)
-         END IF
-      END IF
-
-      ! II.4 Cumulated trends over the analysis period
-      ! ----------------------------------------------
-      !
-      !         [  1rst analysis window ] [     2nd analysis window     ]                       
-      !
-      !     o---[--o-----o-----o-----o--]-[--o-----o-----o-----o-----o--]---o-----o--> time steps
-      !                          nn_trd                           2*nn_trd       etc.
-      !     1      2     3     4    =5 e.g.                          =10
-      !
-      IF( ( kt >= 2 ).OR.( ln_rstart ) ) THEN
-         !
-         nmoymltrd = nmoymltrd + 1
-         
-         ! ... Cumulate over BOTH physical contributions AND over time steps
-         DO jl = 1, jpltrd
-            tmltrdm(:,:) = tmltrdm(:,:) + tmltrd(:,:,jl)
-            smltrdm(:,:) = smltrdm(:,:) + smltrd(:,:,jl)
-         END DO
-
-         ! ... Special handling of the Asselin trend 
-         tmlatfm(:,:) = tmlatfm(:,:) + tmlatfn(:,:)
-         smlatfm(:,:) = smlatfm(:,:) + smlatfn(:,:)
-
-         ! ... Trends associated with the time mean of the ML T/S
-         tmltrd_sum    (:,:,:) = tmltrd_sum    (:,:,:) + tmltrd    (:,:,:) ! tem
-         tmltrd_csum_ln(:,:,:) = tmltrd_csum_ln(:,:,:) + tmltrd_sum(:,:,:)
-         tml_sum       (:,:)   = tml_sum       (:,:)   + tml       (:,:)
-         smltrd_sum    (:,:,:) = smltrd_sum    (:,:,:) + smltrd    (:,:,:) ! sal
-         smltrd_csum_ln(:,:,:) = smltrd_csum_ln(:,:,:) + smltrd_sum(:,:,:)
-         sml_sum       (:,:)   = sml_sum       (:,:)   + sml       (:,:)
-         rmld_sum      (:,:)   = rmld_sum      (:,:)   + rmld      (:,:)   ! rmld
-         !
-      END IF
-
-      ! ======================================================================
-      ! III. Prepare fields for output (get here ONCE PER ANALYSIS PERIOD)
-      ! ======================================================================
-
-      ! Convert to appropriate physical units
-      ! N.B. It may be useful to check IOIPSL time averaging with :
-      !      tmltrd (:,:,:) = 1. ; smltrd (:,:,:) = 1.
-      tmltrd(:,:,:) = tmltrd(:,:,:) * rn_ucf   ! (actually needed for 1:jpltrd-1, but trdmld(:,:,jpltrd)
-      smltrd(:,:,:) = smltrd(:,:,:) * rn_ucf   !  is no longer used, and is reset to 0. at next time step)
-      
-      ! define time axis
-      it = kt
-      itmod = kt - nit000 + 1
-
-      MODULO_NTRD : IF( MOD( itmod, nn_trd ) == 0 ) THEN        ! nitend MUST be multiple of nn_trd
-         !
-         ztmltot (:,:) = 0.e0   ;   zsmltot (:,:) = 0.e0   ! reset arrays to zero
-         ztmlres (:,:) = 0.e0   ;   zsmlres (:,:) = 0.e0
-         ztmltot2(:,:) = 0.e0   ;   zsmltot2(:,:) = 0.e0
-         ztmlres2(:,:) = 0.e0   ;   zsmlres2(:,:) = 0.e0
-      
-         zfn  = float(nmoymltrd)    ;    zfn2 = zfn * zfn
-         
-         ! III.1 Prepare fields for output ("instantaneous" diagnostics) 
-         ! -------------------------------------------------------------
-         
-         !-- Compute total trends
-         ztmltot(:,:) = ( tml(:,:) - tmlbn(:,:) + tmlb(:,:) - tmlbb(:,:) ) / ( 2.*rdt )
-         zsmltot(:,:) = ( sml(:,:) - smlbn(:,:) + smlb(:,:) - smlbb(:,:) ) / ( 2.*rdt )
-         
-         !-- Compute residuals
-         ztmlres(:,:) = ztmltot(:,:) - ( tmltrdm(:,:) - tmlatfn(:,:) + tmlatfb(:,:) )
-         zsmlres(:,:) = zsmltot(:,:) - ( smltrdm(:,:) - smlatfn(:,:) + smlatfb(:,:) )
-      
-         !-- Diagnose Asselin trend over the analysis window 
-         ztmlatf(:,:) = tmlatfm(:,:) - tmlatfn(:,:) + tmlatfb(:,:)
-         zsmlatf(:,:) = smlatfm(:,:) - smlatfn(:,:) + smlatfb(:,:)
-         
-         !-- Lateral boundary conditions
-         !         ... temperature ...                    ... salinity ...
-         CALL lbc_lnk( ztmltot , 'T', 1. )  ;   CALL lbc_lnk( zsmltot , 'T', 1. )
-         CALL lbc_lnk( ztmlres , 'T', 1. )  ;   CALL lbc_lnk( zsmlres , 'T', 1. )
-         CALL lbc_lnk( ztmlatf , 'T', 1. )  ;   CALL lbc_lnk( zsmlatf , 'T', 1. )
-
-#if defined key_diainstant
-         CALL ctl_stop( 'tml_trd : key_diainstant was never checked within trdmld. Comment this to proceed.')
-#endif
-         ! III.2 Prepare fields for output ("mean" diagnostics) 
-         ! ----------------------------------------------------
-         
-         !-- Update the ML depth time sum (to build the Leap-Frog time mean)
-         rmld_sum(:,:) = rmldbn(:,:) + 2 * ( rmld_sum(:,:) - rmld(:,:) ) + rmld(:,:)
-
-         !-- Compute temperature total trends
-         tml_sum (:,:) = tmlbn(:,:) + 2 * ( tml_sum(:,:) - tml(:,:) ) + tml(:,:)
-         ztmltot2(:,:) = ( tml_sum(:,:) - tml_sumb(:,:) ) /  ( 2.*rdt )    ! now in degC/s
-         
-         !-- Compute salinity total trends
-         sml_sum (:,:) = smlbn(:,:) + 2 * ( sml_sum(:,:) - sml(:,:) ) + sml(:,:)
-         zsmltot2(:,:) = ( sml_sum(:,:) - sml_sumb(:,:) ) /  ( 2.*rdt )    ! now in psu/s
-         
-         !-- Compute temperature residuals
-         DO jl = 1, jpltrd
-            ztmltrd2(:,:,jl) = tmltrd_csum_ub(:,:,jl) + tmltrd_csum_ln(:,:,jl)
-         END DO
-
-         ztmltrdm2(:,:) = 0.e0
-         DO jl = 1, jpltrd
-            ztmltrdm2(:,:) = ztmltrdm2(:,:) + ztmltrd2(:,:,jl)
-         END DO
-
-         ztmlres2(:,:) =  ztmltot2(:,:)  -       &
-              ( ztmltrdm2(:,:) - tmltrd_sum(:,:,jpmld_atf) + tmltrd_atf_sumb(:,:) )
-         
-         !-- Compute salinity residuals
-         DO jl = 1, jpltrd
-            zsmltrd2(:,:,jl) = smltrd_csum_ub(:,:,jl) + smltrd_csum_ln(:,:,jl)
-         END DO
-
-         zsmltrdm2(:,:) = 0.
-         DO jl = 1, jpltrd
-            zsmltrdm2(:,:) = zsmltrdm2(:,:) + zsmltrd2(:,:,jl)
-         END DO
-
-         zsmlres2(:,:) =  zsmltot2(:,:)  -       &
-              ( zsmltrdm2(:,:) - smltrd_sum(:,:,jpmld_atf) + smltrd_atf_sumb(:,:) )
-         
-         !-- Diagnose Asselin trend over the analysis window
-         ztmlatf2(:,:) = ztmltrd2(:,:,jpmld_atf) - tmltrd_sum(:,:,jpmld_atf) + tmltrd_atf_sumb(:,:)
-         zsmlatf2(:,:) = zsmltrd2(:,:,jpmld_atf) - smltrd_sum(:,:,jpmld_atf) + smltrd_atf_sumb(:,:)
-
-         !-- Lateral boundary conditions
-         !         ... temperature ...                    ... salinity ...
-         CALL lbc_lnk( ztmltot2, 'T', 1. )  ;   CALL lbc_lnk( zsmltot2, 'T', 1. )
-         CALL lbc_lnk( ztmlres2, 'T', 1. )  ;   CALL lbc_lnk( zsmlres2, 'T', 1. )
-         DO jl = 1, jpltrd
-            CALL lbc_lnk( ztmltrd2(:,:,jl), 'T', 1. ) ! \  these will be output
-            CALL lbc_lnk( zsmltrd2(:,:,jl), 'T', 1. ) ! /  in the NetCDF trends file
-         END DO
-         
-         ! III.3 Time evolution array swap
-         ! -------------------------------
-         
-         ! For T/S instantaneous diagnostics 
-         !   ... temperature ...               ... salinity ...
-         tmlbb  (:,:) = tmlb   (:,:)  ;   smlbb  (:,:) = smlb   (:,:)
-         tmlbn  (:,:) = tml    (:,:)  ;   smlbn  (:,:) = sml    (:,:)
-         tmlatfb(:,:) = tmlatfn(:,:)  ;   smlatfb(:,:) = smlatfn(:,:)
-
-         ! For T mean diagnostics 
-         tmltrd_csum_ub (:,:,:) = zfn * tmltrd_sum(:,:,:) - tmltrd_csum_ln(:,:,:)
-         tml_sumb       (:,:)   = tml_sum(:,:)
-         tmltrd_atf_sumb(:,:)   = tmltrd_sum(:,:,jpmld_atf)
-         
-         ! For S mean diagnostics 
-         smltrd_csum_ub (:,:,:) = zfn * smltrd_sum(:,:,:) - smltrd_csum_ln(:,:,:)
-         sml_sumb       (:,:)   = sml_sum(:,:)
-         smltrd_atf_sumb(:,:)   = smltrd_sum(:,:,jpmld_atf)
-         
-         ! ML depth
-         rmldbn         (:,:)   = rmld    (:,:)
-         
-         IF( ln_ctl ) THEN
-            IF( ln_trdmld_instant ) THEN
-               CALL prt_ctl(tab2d_1=tmlbb   , clinfo1=' tmlbb   -   : ', mask1=tmask, ovlap=1)
-               CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask, ovlap=1)
-               CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask, ovlap=1)
-            ELSE
-               CALL prt_ctl(tab2d_1=tmlbn          , clinfo1=' tmlbn           -  : ', mask1=tmask, ovlap=1)
-               CALL prt_ctl(tab2d_1=rmldbn         , clinfo1=' rmldbn          -  : ', mask1=tmask, ovlap=1)
-               CALL prt_ctl(tab2d_1=tml_sumb       , clinfo1=' tml_sumb        -  : ', mask1=tmask, ovlap=1)
-               CALL prt_ctl(tab2d_1=tmltrd_atf_sumb, clinfo1=' tmltrd_atf_sumb -  : ', mask1=tmask, ovlap=1)
-               CALL prt_ctl(tab3d_1=tmltrd_csum_ub , clinfo1=' tmltrd_csum_ub  -  : ', mask1=tmask, ovlap=1, kdim=1)
-            END IF
-         END IF
-
-         ! III.4 Convert to appropriate physical units
-         ! -------------------------------------------
-
-         !    ... temperature ...                         ... salinity ...
-         ztmltot (:,:)   = ztmltot(:,:)   * rn_ucf/zfn  ; zsmltot (:,:)   = zsmltot(:,:)   * rn_ucf/zfn
-         ztmlres (:,:)   = ztmlres(:,:)   * rn_ucf/zfn  ; zsmlres (:,:)   = zsmlres(:,:)   * rn_ucf/zfn
-         ztmlatf (:,:)   = ztmlatf(:,:)   * rn_ucf/zfn  ; zsmlatf (:,:)   = zsmlatf(:,:)   * rn_ucf/zfn
-
-         tml_sum (:,:)   = tml_sum (:,:)  /  (2*zfn) ; sml_sum (:,:)   = sml_sum (:,:)  /  (2*zfn)
-         ztmltot2(:,:)   = ztmltot2(:,:)  * rn_ucf/zfn2 ; zsmltot2(:,:)   = zsmltot2(:,:)  * rn_ucf/zfn2
-         ztmltrd2(:,:,:) = ztmltrd2(:,:,:)* rn_ucf/zfn2 ; zsmltrd2(:,:,:) = zsmltrd2(:,:,:)* rn_ucf/zfn2
-         ztmlatf2(:,:)   = ztmlatf2(:,:)  * rn_ucf/zfn2 ; zsmlatf2(:,:)   = zsmlatf2(:,:)  * rn_ucf/zfn2
-         ztmlres2(:,:)   = ztmlres2(:,:)  * rn_ucf/zfn2 ; zsmlres2(:,:)   = zsmlres2(:,:)  * rn_ucf/zfn2
-
-         rmld_sum(:,:)   = rmld_sum(:,:)  /  (2*zfn)  ! similar to tml_sum and sml_sum
-
-         ! * Debugging information *
-         IF( lldebug ) THEN
-            !
-            WRITE(numout,*)
-            WRITE(numout,*) 'trd_mld : write trends in the Mixed Layer for debugging process:'
-            WRITE(numout,*) '~~~~~~~  '
-            WRITE(numout,*) '          TRA kt = ', kt, 'nmoymltrd = ', nmoymltrd
-            WRITE(numout,*)
-            WRITE(numout,*) '          >>>>>>>>>>>>>>>>>>  TRA TEMPERATURE <<<<<<<<<<<<<<<<<<'
-            WRITE(numout,*) '          TRA ztmlres    : ', SUM(ztmlres(:,:))
-            WRITE(numout,*) '          TRA ztmltot    : ', SUM(ztmltot(:,:))
-            WRITE(numout,*) '          TRA tmltrdm    : ', SUM(tmltrdm(:,:))
-            WRITE(numout,*) '          TRA tmlatfb    : ', SUM(tmlatfb(:,:))
-            WRITE(numout,*) '          TRA tmlatfn    : ', SUM(tmlatfn(:,:))
-            DO jl = 1, jpltrd
-               WRITE(numout,*) '          * TRA TREND INDEX jpmld_xxx = jl = ', jl, &
-                    & ' tmltrd : ', SUM(tmltrd(:,:,jl))
-            END DO
-            WRITE(numout,*) '          TRA ztmlres (jpi/2,jpj/2) : ', ztmlres (jpi/2,jpj/2)
-            WRITE(numout,*) '          TRA ztmlres2(jpi/2,jpj/2) : ', ztmlres2(jpi/2,jpj/2)
-            WRITE(numout,*)
-            WRITE(numout,*) '          >>>>>>>>>>>>>>>>>>  TRA SALINITY <<<<<<<<<<<<<<<<<<'
-            WRITE(numout,*) '          TRA zsmlres    : ', SUM(zsmlres(:,:))
-            WRITE(numout,*) '          TRA zsmltot    : ', SUM(zsmltot(:,:))
-            WRITE(numout,*) '          TRA smltrdm    : ', SUM(smltrdm(:,:))
-            WRITE(numout,*) '          TRA smlatfb    : ', SUM(smlatfb(:,:))
-            WRITE(numout,*) '          TRA smlatfn    : ', SUM(smlatfn(:,:))
-            DO jl = 1, jpltrd
-               WRITE(numout,*) '          * TRA TREND INDEX jpmld_xxx = jl = ', jl, &
-                    & ' smltrd : ', SUM(smltrd(:,:,jl))
-            END DO
-            WRITE(numout,*) '          TRA zsmlres (jpi/2,jpj/2) : ', zsmlres (jpi/2,jpj/2)
-            WRITE(numout,*) '          TRA zsmlres2(jpi/2,jpj/2) : ', zsmlres2(jpi/2,jpj/2)
-            !
-         END IF
-         !
-      END IF MODULO_NTRD
-
-      ! ======================================================================
-      ! IV. Write trends in the NetCDF file
-      ! ======================================================================
-
-      ! IV.1 Code for dimg mpp output
-      ! -----------------------------
-
-#if defined key_dimgout
-
-      IF( MOD( itmod, nn_trd ) == 0 ) THEN
-         iyear =  ndastp/10000
-         imon  = (ndastp-iyear*10000)/100
-         iday  =  ndastp - imon*100 - iyear*10000
-         WRITE(clname,9000) TRIM(cexper),'MLDiags',iyear,imon,iday
-         WRITE(clmode,'(f5.1,a)') nn_trd*rdt/86400.,' days average'
-         cltext = TRIM(cexper)//' mld diags'//TRIM(clmode)
-         CALL dia_wri_dimg (clname, cltext, smltrd, jpltrd, '2')
-      END IF
-
-9000  FORMAT(a,"_",a,"_y",i4.4,"m",i2.2,"d",i2.2,".dimgproc")
-
-#else
-      
-      ! IV.2 Code for IOIPSL/NetCDF output
-      ! ----------------------------------
-
-      IF( lwp .AND. MOD( itmod , nn_trd ) == 0 ) THEN
-         WRITE(numout,*) ' '
-         WRITE(numout,*) 'trd_mld : write trends in the NetCDF file :'
-         WRITE(numout,*) '~~~~~~~  '
-         WRITE(numout,*) '          ', TRIM(clhstnam), ' at kt = ', kt
-         WRITE(numout,*) '          N.B. nmoymltrd = ', nmoymltrd
-         WRITE(numout,*) ' '
-      END IF
-         
-      !-- Write the trends for T/S instantaneous diagnostics 
-      IF( ln_trdmld_instant ) THEN           
-
-         CALL histwrite( nidtrd, "mxl_depth", it, rmld(:,:), ndimtrd1, ndextrd1 )
-         
-         !................................. ( ML temperature ) ...................................
-         
-         !-- Output the fields
-         CALL histwrite( nidtrd, "tml"     , it, tml    (:,:), ndimtrd1, ndextrd1 ) 
-         CALL histwrite( nidtrd, "tml_tot" , it, ztmltot(:,:), ndimtrd1, ndextrd1 ) 
-         CALL histwrite( nidtrd, "tml_res" , it, ztmlres(:,:), ndimtrd1, ndextrd1 ) 
-         
-         DO jl = 1, jpltrd - 1
-            CALL histwrite( nidtrd, trim("tml"//ctrd(jl,2)),            &
-                 &          it, tmltrd (:,:,jl), ndimtrd1, ndextrd1 )
-         END DO
-         
-         CALL histwrite( nidtrd, trim("tml"//ctrd(jpmld_atf,2)),        &
-              &          it, ztmlatf(:,:), ndimtrd1, ndextrd1 )
-         
-         !.................................. ( ML salinity ) .....................................
-         
-         !-- Output the fields
-         CALL histwrite( nidtrd, "sml"     , it, sml    (:,:), ndimtrd1, ndextrd1 ) 
-         CALL histwrite( nidtrd, "sml_tot" , it, zsmltot(:,:), ndimtrd1, ndextrd1 ) 
-         CALL histwrite( nidtrd, "sml_res" , it, zsmlres(:,:), ndimtrd1, ndextrd1 ) 
-         
-         DO jl = 1, jpltrd - 1
-            CALL histwrite( nidtrd, trim("sml"//ctrd(jl,2)),            &
-                 &          it, smltrd(:,:,jl), ndimtrd1, ndextrd1 )
-         END DO
-         
-         CALL histwrite( nidtrd, trim("sml"//ctrd(jpmld_atf,2)),        &
-              &          it, zsmlatf(:,:), ndimtrd1, ndextrd1 )
-         
-         IF( kt == nitend )   CALL histclo( nidtrd )
-
-      !-- Write the trends for T/S mean diagnostics 
-      ELSE
-         
-         CALL histwrite( nidtrd, "mxl_depth", it, rmld_sum(:,:), ndimtrd1, ndextrd1 ) 
-         
-         !................................. ( ML temperature ) ...................................
-         
-         !-- Output the fields
-         CALL histwrite( nidtrd, "tml"     , it, tml_sum (:,:), ndimtrd1, ndextrd1 ) 
-         CALL histwrite( nidtrd, "tml_tot" , it, ztmltot2(:,:), ndimtrd1, ndextrd1 ) 
-         CALL histwrite( nidtrd, "tml_res" , it, ztmlres2(:,:), ndimtrd1, ndextrd1 ) 
-         
-         DO jl = 1, jpltrd - 1
-            CALL histwrite( nidtrd, trim("tml"//ctrd(jl,2)),            &
-                 &          it, ztmltrd2(:,:,jl), ndimtrd1, ndextrd1 )
-         END DO
-         
-         CALL histwrite( nidtrd, trim("tml"//ctrd(jpmld_atf,2)),        &
-              &          it, ztmlatf2(:,:), ndimtrd1, ndextrd1 )
-         
-         !.................................. ( ML salinity ) .....................................
-                     
-         !-- Output the fields
-         CALL histwrite( nidtrd, "sml"     , it, sml_sum (:,:), ndimtrd1, ndextrd1 ) 
-         CALL histwrite( nidtrd, "sml_tot" , it, zsmltot2(:,:), ndimtrd1, ndextrd1 ) 
-         CALL histwrite( nidtrd, "sml_res" , it, zsmlres2(:,:), ndimtrd1, ndextrd1 ) 
-         
-         DO jl = 1, jpltrd - 1
-            CALL histwrite( nidtrd, trim("sml"//ctrd(jl,2)),            &
-                 &          it, zsmltrd2(:,:,jl), ndimtrd1, ndextrd1 )
-         END DO
-         
-         CALL histwrite( nidtrd, trim("sml"//ctrd(jpmld_atf,2)),        &
-              &          it, zsmlatf2(:,:), ndimtrd1, ndextrd1 )
-         
-         IF( kt == nitend )   CALL histclo( nidtrd )
-
-      END IF
-      
-      ! Compute the control surface (for next time step) : flag = on
-      icount = 1
-      !
-#endif
-
-      IF( MOD( itmod, nn_trd ) == 0 ) THEN
-         !
-         ! III.5 Reset cumulative arrays to zero
-         ! -------------------------------------
-         nmoymltrd = 0
-         
-         !   ... temperature ...               ... salinity ...
-         tmltrdm        (:,:)   = 0.e0   ;   smltrdm        (:,:)   = 0.e0
-         tmlatfm        (:,:)   = 0.e0   ;   smlatfm        (:,:)   = 0.e0
-         tml_sum        (:,:)   = 0.e0   ;   sml_sum        (:,:)   = 0.e0
-         tmltrd_csum_ln (:,:,:) = 0.e0   ;   smltrd_csum_ln (:,:,:) = 0.e0
-         tmltrd_sum     (:,:,:) = 0.e0   ;   smltrd_sum     (:,:,:) = 0.e0
-
-         rmld_sum       (:,:)   = 0.e0
-         !
-      END IF
-
-      ! ======================================================================
-      ! V. Write restart file
-      ! ======================================================================
-
-      IF( lrst_oce )   CALL trd_mld_rst_write( kt ) 
-
-      CALL wrk_dealloc( jpi, jpj,         ztmltot , zsmltot , ztmlres , zsmlres , ztmlatf , zsmlatf                        )
-      CALL wrk_dealloc( jpi, jpj,         ztmltot2, zsmltot2, ztmlres2, zsmlres2, ztmlatf2, zsmlatf2, ztmltrdm2, zsmltrdm2 )  
-      CALL wrk_dealloc( jpi, jpj, jpltrd, ztmltrd2, zsmltrd2                                                               )
-      !
-   END SUBROUTINE trd_mld
-
-
-   SUBROUTINE trd_mld_init
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld_init  ***
-      !! 
-      !! ** Purpose :   computation of vertically integrated T and S budgets
-      !!      from ocean surface down to control surface (NetCDF output)
-      !!----------------------------------------------------------------------
-      INTEGER :: jl
-      INTEGER :: inum   ! logical unit
-      REAL(wp) ::   zjulian, zsto, zout
-      CHARACTER (LEN=40) ::   clop
-      CHARACTER (LEN=12) ::   clmxl, cltu, clsu
-      !!----------------------------------------------------------------------
-
-      ! ======================================================================
-      ! I. initialization
-      ! ======================================================================
-
-      IF(lwp) THEN
-         WRITE(numout,*)
-         WRITE(numout,*) ' trd_mld_init : Mixed-layer trends'
-         WRITE(numout,*) ' ~~~~~~~~~~~~~'
-         WRITE(numout,*) '                namelist namtrd read in trd_mod_init                        '
-         WRITE(numout,*)
-      END IF
-
-      ! I.1 Check consistency of user defined preferences
-      ! -------------------------------------------------
-
-      IF( ( lk_trdmld ) .AND. ( MOD( nitend-nit000+1, nn_trd ) /= 0 ) ) THEN
-         WRITE(numout,cform_err)
-         WRITE(numout,*) '                Your nitend parameter, nitend = ', nitend
-         WRITE(numout,*) '                is no multiple of the trends diagnostics frequency        '
-         WRITE(numout,*) '                          you defined, nn_trd   = ', nn_trd
-         WRITE(numout,*) '                This will not allow you to restart from this simulation.  '
-         WRITE(numout,*) '                You should reconsider this choice.                        ' 
-         WRITE(numout,*) 
-         WRITE(numout,*) '                N.B. the nitend parameter is also constrained to be a     '
-         WRITE(numout,*) '                multiple of the sea-ice frequency parameter (typically 5) '
-         nstop = nstop + 1
-      END IF
-
-      IF( ( lk_trdmld ) .AND. ( nn_cla == 1 ) ) THEN
-         WRITE(numout,cform_war)
-         WRITE(numout,*) '                You set n_cla = 1. Note that the Mixed-Layer diagnostics  '
-         WRITE(numout,*) '                are not exact along the corresponding straits.            '
-         nwarn = nwarn + 1
-      END IF
-
-      !                                   ! allocate trdmld arrays
-      IF( trd_mld_alloc()    /= 0 )   CALL ctl_stop( 'STOP', 'trd_mld_init : unable to allocate trdmld     arrays' )
-      IF( trdmld_oce_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trd_mld_init : unable to allocate trdmld_oce arrays' )
-
-      ! I.2 Initialize arrays to zero or read a restart file
-      ! ----------------------------------------------------
-
-      nmoymltrd = 0
-
-      !     ... temperature ...                  ... salinity ...
-      tml            (:,:)   = 0.e0    ;    sml            (:,:)   = 0.e0     ! inst.
-      tmltrdm        (:,:)   = 0.e0    ;    smltrdm        (:,:)   = 0.e0
-      tmlatfm        (:,:)   = 0.e0    ;    smlatfm        (:,:)   = 0.e0
-      tml_sum        (:,:)   = 0.e0    ;    sml_sum        (:,:)   = 0.e0     ! mean
-      tmltrd_sum     (:,:,:) = 0.e0    ;    smltrd_sum     (:,:,:) = 0.e0
-      tmltrd_csum_ln (:,:,:) = 0.e0    ;    smltrd_csum_ln (:,:,:) = 0.e0
-
-      rmld           (:,:)   = 0.e0            
-      rmld_sum       (:,:)   = 0.e0
-
-      IF( ln_rstart .AND. ln_trdmld_restart ) THEN
-         CALL trd_mld_rst_read
-      ELSE
-         !     ... temperature ...                  ... salinity ...
-         tmlb           (:,:)   = 0.e0    ;    smlb           (:,:)   = 0.e0  ! inst.
-         tmlbb          (:,:)   = 0.e0    ;    smlbb          (:,:)   = 0.e0  
-         tmlbn          (:,:)   = 0.e0    ;    smlbn          (:,:)   = 0.e0  
-         tml_sumb       (:,:)   = 0.e0    ;    sml_sumb       (:,:)   = 0.e0  ! mean
-         tmltrd_csum_ub (:,:,:) = 0.e0    ;    smltrd_csum_ub (:,:,:) = 0.e0
-         tmltrd_atf_sumb(:,:)   = 0.e0    ;    smltrd_atf_sumb(:,:)   = 0.e0  
-      END IF
-
-      icount = 1   ;   ionce  = 1                            ! open specifier
-
-      ! I.3 Read control surface from file ctlsurf_idx
-      ! ----------------------------------------------
- 
-      IF( nn_ctls == 1 ) THEN
-         CALL ctl_opn( inum, 'ctlsurf_idx', 'OLD', 'UNFORMATTED', 'SEQUENTIAL', -1, numout, lwp )
-         READ ( inum ) nbol
-         CLOSE( inum )
-      END IF
-
-      ! ======================================================================
-      ! II. netCDF output initialization
-      ! ======================================================================
-
-#if defined key_dimgout 
-      ???
-#else
-      ! clmxl = legend root for netCDF output
-      IF( nn_ctls == 0 ) THEN      ! control surface = mixed-layer with density criterion
-         clmxl = 'Mixed Layer '  !                   (array nmln computed in zdfmxl.F90)
-      ELSE IF( nn_ctls == 1 ) THEN ! control surface = read index from file 
-         clmxl = '      Bowl '
-      ELSE IF( nn_ctls >= 2 ) THEN ! control surface = model level
-         WRITE(clmxl,'(A10,I2,1X)') 'Levels 1 -', nn_ctls
-      END IF
-
-      ! II.1 Define frequency of output and means
-      ! -----------------------------------------
-      IF( ln_mskland )   THEN   ;   clop = "only(x)"   ! put 1.e+20 on land (very expensive!!)
-      ELSE                      ;   clop = "x"         ! no use of the mask value (require less cpu time)
-      ENDIF
-#  if defined key_diainstant
-      IF( .NOT. ln_trdmld_instant ) THEN
-         CALL ctl_stop( 'trd_mld : this was never checked. Comment this line to proceed...' )
-      END IF
-      zsto = nn_trd * rdt
-      clop = "inst("//TRIM(clop)//")"
-#  else
-      IF( ln_trdmld_instant ) THEN
-         zsto = rdt                 ! inst. diags : we use IOIPSL time averaging
-      ELSE
-         zsto = nn_trd * rdt          ! mean  diags : we DO NOT use any IOIPSL time averaging
-      END IF
-      clop = "ave("//TRIM(clop)//")"
-#  endif
-      zout = nn_trd * rdt
-
-      IF(lwp) WRITE (numout,*) '                netCDF initialization'
-
-      ! II.2 Compute julian date from starting date of the run
-      ! ------------------------------------------------------
-      CALL ymds2ju( nyear, nmonth, nday, rdt, zjulian )
-      zjulian = zjulian - adatrj   !   set calendar origin to the beginning of the experiment
-      IF(lwp) WRITE(numout,*)' '  
-      IF(lwp) WRITE(numout,*)'                Date 0 used :',nit000,    &
-         &                   ' YEAR ', nyear,' MONTH '      , nmonth,   &
-         &                   ' DAY ' , nday, 'Julian day : ', zjulian
-
-
-      ! II.3 Define the T grid trend file (nidtrd)
-      ! ------------------------------------------
-      !-- Define long and short names for the NetCDF output variables
-      !       ==> choose them according to trdmld_oce.F90 <==
-
-      ctrd(jpmld_xad,1) = " Zonal advection"                  ;   ctrd(jpmld_xad,2) = "_xad"
-      ctrd(jpmld_yad,1) = " Meridional advection"             ;   ctrd(jpmld_yad,2) = "_yad"
-      ctrd(jpmld_zad,1) = " Vertical advection"               ;   ctrd(jpmld_zad,2) = "_zad"
-      ctrd(jpmld_ldf,1) = " Lateral diffusion"                ;   ctrd(jpmld_ldf,2) = "_ldf"
-      ctrd(jpmld_for,1) = " Forcing"                          ;   ctrd(jpmld_for,2) = "_for"
-      ctrd(jpmld_zdf,1) = " Vertical diff. (Kz)"              ;   ctrd(jpmld_zdf,2) = "_zdf"
-      ctrd(jpmld_bbc,1) = " Geothermal flux"                  ;   ctrd(jpmld_bbc,2) = "_bbc"
-      ctrd(jpmld_bbl,1) = " Adv/diff. Bottom boundary layer"  ;   ctrd(jpmld_bbl,2) = "_bbl"
-      ctrd(jpmld_dmp,1) = " Tracer damping"                   ;   ctrd(jpmld_dmp,2) = "_dmp"
-      ctrd(jpmld_npc,1) = " Non penetrative convec. adjust."  ;   ctrd(jpmld_npc,2) = "_npc"
-      ctrd(jpmld_atf,1) = " Asselin time filter"              ;   ctrd(jpmld_atf,2) = "_atf"
-                                                                  
-      !-- Create a NetCDF file and enter the define mode 
-      CALL dia_nam( clhstnam, nn_trd, 'trends' )
-      IF(lwp) WRITE(numout,*) ' Name of NETCDF file ', clhstnam
-      CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,                                            &
-      &             1, jpi, 1, jpj, nit000-1, zjulian, rdt, nh_t, nidtrd, domain_id=nidom, snc4chunks=snc4set )
-
-      !-- Define the ML depth variable
-      CALL histdef(nidtrd, "mxl_depth", clmxl//"  Mixed Layer Depth"              , "m",         &
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-
-      !-- Define physical units
-      IF     ( rn_ucf == 1.       ) THEN   ;   cltu = "degC/s"     ;   clsu = "p.s.u./s"
-      ELSEIF ( rn_ucf == 3600.*24.) THEN   ;   cltu = "degC/day"   ;   clsu = "p.s.u./day"
-      ELSE                                 ;   cltu = "unknown?"   ;   clsu = "unknown?"
-      END IF
-
-
-      !-- Define miscellaneous T and S mixed-layer variables 
-
-      IF( jpltrd /= jpmld_atf ) CALL ctl_stop( 'Error : jpltrd /= jpmld_atf' ) ! see below
-
-      !................................. ( ML temperature ) ...................................
-
-      CALL histdef(nidtrd, "tml"      , clmxl//" T Mixed Layer Temperature"       ,  "C",        &
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zsto, zout )           
-      CALL histdef(nidtrd, "tml_tot",   clmxl//" T Total trend"                   , cltu,        & 
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zout, zout )              
-      CALL histdef(nidtrd, "tml_res",   clmxl//" T dh/dt Entrainment (Resid.)"    , cltu,        & 
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zout, zout )                   
-      
-      DO jl = 1, jpltrd - 1      ! <== only true if jpltrd == jpmld_atf
-         CALL histdef(nidtrd, trim("tml"//ctrd(jl,2)), clmxl//" T"//ctrd(jl,1), cltu,            & 
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zsto, zout ) ! IOIPSL: time mean
-      END DO                                                                 ! if zsto=rdt above
-      
-      CALL histdef(nidtrd, trim("tml"//ctrd(jpmld_atf,2)), clmxl//" T"//ctrd(jpmld_atf,1), cltu, & 
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zout, zout ) ! IOIPSL: NO time mean
-      
-      !.................................. ( ML salinity ) .....................................
-     
-      CALL histdef(nidtrd, "sml"      , clmxl//" S Mixed Layer Salinity"          , "p.s.u.",       &
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zsto, zout )           
-      CALL histdef(nidtrd, "sml_tot",   clmxl//" S Total trend"                   , clsu,        & 
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zout, zout )              
-      CALL histdef(nidtrd, "sml_res",   clmxl//" S dh/dt Entrainment (Resid.)"    , clsu,        & 
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zout, zout )                   
-      
-      DO jl = 1, jpltrd - 1      ! <== only true if jpltrd == jpmld_atf
-         CALL histdef(nidtrd, trim("sml"//ctrd(jl,2)), clmxl//" S"//ctrd(jl,1), clsu,            & 
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zsto, zout ) ! IOIPSL: time mean
-      END DO                                                                 ! if zsto=rdt above
-      
-      CALL histdef(nidtrd, trim("sml"//ctrd(jpmld_atf,2)), clmxl//" S"//ctrd(jpmld_atf,1), clsu, & 
-                   jpi, jpj, nh_t, 1  , 1, 1  , -99 , 32, clop, zout, zout ) ! IOIPSL: NO time mean
-
-      !-- Leave IOIPSL/NetCDF define mode
-      CALL histend( nidtrd, snc4set )
-
-#endif        /* key_dimgout */
-   END SUBROUTINE trd_mld_init
-
-#else
-   !!----------------------------------------------------------------------
-   !!   Default option :                                       Empty module
-   !!----------------------------------------------------------------------
-CONTAINS
-   SUBROUTINE trd_mld( kt )             ! Empty routine
-      INTEGER, INTENT( in) ::   kt
-      WRITE(*,*) 'trd_mld: You should not have seen this print! error?', kt
-   END SUBROUTINE trd_mld
-   SUBROUTINE trd_mld_zint( pttrdmld, pstrdmld, ktrd, ctype )
-      REAL, DIMENSION(:,:,:), INTENT( in ) ::   &
-         pttrdmld, pstrdmld                   ! Temperature and Salinity trends
-      INTEGER, INTENT( in ) ::   ktrd         ! ocean trend index
-      CHARACTER(len=2), INTENT( in ) ::   &  
-         ctype                                ! surface/bottom (2D arrays) or
-         !                                    ! interior (3D arrays) physics
-      WRITE(*,*) 'trd_mld_zint: You should not have seen this print! error?', pttrdmld(1,1,1)
-      WRITE(*,*) '  "      "  : You should not have seen this print! error?', pstrdmld(1,1,1)
-      WRITE(*,*) '  "      "  : You should not have seen this print! error?', ctype
-      WRITE(*,*) '  "      "  : You should not have seen this print! error?', ktrd
-   END SUBROUTINE trd_mld_zint
-   SUBROUTINE trd_mld_init              ! Empty routine
-      WRITE(*,*) 'trd_mld_init: You should not have seen this print! error?'
-   END SUBROUTINE trd_mld_init
-#endif
-
-   !!======================================================================
-END MODULE trdmld
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmld_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmld_oce.F90	(revision 5074)
+++ 	(revision )
@@ -1,136 +1,0 @@
-MODULE trdmld_oce
-   !!======================================================================
-   !!                   ***  MODULE trdmld_oce  ***
-   !! Ocean trends :   set tracer and momentum trend variables
-   !!======================================================================
-   !! History :  1.0  ! 2004-08  (C. Talandier)  New trends organization
-   !!----------------------------------------------------------------------
-   USE par_oce        ! ocean parameters
-
-   IMPLICIT NONE
-   PRIVATE
-
-   PUBLIC   trdmld_oce_alloc    ! Called in trdmld.F90
-
-#if defined key_trdmld
-   LOGICAL, PUBLIC, PARAMETER ::   lk_trdmld = .TRUE.    !: ML trend flag
-#else
-   LOGICAL, PUBLIC, PARAMETER ::   lk_trdmld = .FALSE.   !: ML trend flag
-#endif
-   !!* mixed layer trends indices
-   INTEGER, PARAMETER, PUBLIC ::   jpltrd = 11      !: number of mixed-layer trends arrays
-   INTEGER, PUBLIC            ::   jpktrd           !: max level for mixed-layer trends diag.
-   !
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_xad =  1   !:  zonal      
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_yad =  2   !:  meridonal   > advection
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_zad =  3   !:  vertical   
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_ldf =  4   !:  lateral diffusion (geopot. or iso-neutral)
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_for =  5   !:  forcing 
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_zdf =  6   !:  vertical diffusion (TKE)
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_bbc =  7   !:  geothermal flux
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_bbl =  8   !:  bottom boundary layer (advective/diffusive)
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_dmp =  9   !:  internal restoring trend
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_npc = 10   !:  non penetrative convective adjustment
-!! INTEGER, PUBLIC, PARAMETER ::   jpmld_xxx = xx   !:  add here any additional trend (add change jpltrd)
-   INTEGER, PUBLIC, PARAMETER ::   jpmld_atf = 11   !:  asselin trend (**MUST BE THE LAST ONE**)
-
-#if   defined  key_trdmld   ||   defined key_esopa
-   !!----------------------------------------------------------------------
-   !!   'key_trdmld'                         mixed layer trends diagnostics
-   !!----------------------------------------------------------------------
-
-   !! Arrays used for diagnosing mixed-layer trends 
-   !!---------------------------------------------------------------------
-   CHARACTER(LEN=80) , PUBLIC :: clname, ctrd(jpltrd+1,2)
-
-   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nmld   !: mixed layer depth indexes 
-   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nbol   !: mixed-layer depth indexes when read from file
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   wkx    !:
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::  &
-      rmld   ,                      & !: mld depth (m) corresponding to nmld
-      tml    , sml  ,               & !: \ "now" mixed layer temperature/salinity
-      tmlb   , smlb ,               & !: /  and associated "before" fields
-      tmlbb  , smlbb,               & !: \  idem, but valid at the 1rst time step of the
-      tmlbn  , smlbn,               & !: /  current analysis window
-      tmltrdm, smltrdm,             & !: total cumulative trends over the analysis window
-      tml_sum,                      & !: mixed layer T, summed over the current analysis period
-      tml_sumb,                     & !: idem, but from the previous analysis period
-      tmltrd_atf_sumb,              & !: Asselin trends, summed over the previous analysis period
-      sml_sum,                      & !: 
-      sml_sumb,                     & !:    ( idem for salinity )
-      smltrd_atf_sumb,              & !: 
-      rmld_sum, rmldbn                !: needed to compute the leap-frog time mean of the ML depth
-
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::  &
-      tmlatfb, tmlatfn ,            & !: "before" Asselin contribution at begining of the averaging
-      smlatfb, smlatfn,             & !: period (i.e. last contrib. from previous such period) and 
-                                      !: "now" Asselin contribution to the ML temp. & salinity trends
-      tmlatfm, smlatfm                !: accumulator for Asselin trends (needed for storage only)
-
-   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:) ::  &
-      tmltrd,                       & !: \ physical contributions to the total trend (for T/S),
-      smltrd,                       & !: / cumulated over the current analysis window
-      tmltrd_sum,                   & !: sum of these trends over the analysis period
-      tmltrd_csum_ln,               & !: now cumulated sum of the trends over the "lower triangle"
-      tmltrd_csum_ub,               & !: before (prev. analysis period) cumulated sum over the upper triangle
-      smltrd_sum,                   & !: 
-      smltrd_csum_ln,               & !:    ( idem for salinity )
-      smltrd_csum_ub                  !: 
-#endif
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 4.0 , NEMO Consortium (2011)
-   !! $Id$ 
-   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-CONTAINS
-
-  INTEGER FUNCTION trdmld_oce_alloc()
-     !!----------------------------------------------------------------------
-     !!                 ***  FUNCTION trdmld_oce_alloc   ***
-     !!----------------------------------------------------------------------
-     USE lib_mpp
-     INTEGER :: ierr(5)
-     !!----------------------------------------------------------------------
-
-     ! Initialise jpktrd here as can no longer do it in MODULE body since
-     ! jpk is now a variable.
-     jpktrd = jpk   !: max level for mixed-layer trends diag.
-
-     ierr(:) = 0
-
-#if   defined  key_trdmld   ||   defined key_esopa
-     ALLOCATE( nmld(jpi,jpj), nbol(jpi,jpj),       &
-        &      wkx(jpi,jpj,jpk), rmld(jpi,jpj),    & 
-        &      tml(jpi,jpj)    , sml(jpi,jpj),     & 
-        &      tmlb(jpi,jpj)   , smlb(jpi,jpj) ,   &
-        &      tmlbb(jpi,jpj)  , smlbb(jpi,jpj), STAT = ierr(1) )
-
-     ALLOCATE( tmlbn(jpi,jpj)  , smlbn(jpi,jpj),   &
-        &      tmltrdm(jpi,jpj), smltrdm(jpi,jpj), &
-        &      tml_sum(jpi,jpj), tml_sumb(jpi,jpj),&
-        &      tmltrd_atf_sumb(jpi,jpj)           , STAT=ierr(2) )
-
-     ALLOCATE( sml_sum(jpi,jpj), sml_sumb(jpi,jpj), &
-        &      smltrd_atf_sumb(jpi,jpj),            &
-        &      rmld_sum(jpi,jpj), rmldbn(jpi,jpj),  &
-        &      tmlatfb(jpi,jpj), tmlatfn(jpi,jpj), STAT = ierr(3) )
-
-     ALLOCATE( smlatfb(jpi,jpj), smlatfn(jpi,jpj), & 
-        &      tmlatfm(jpi,jpj), smlatfm(jpi,jpj), &
-        &      tmltrd(jpi,jpj,jpltrd),   smltrd(jpi,jpj,jpltrd), STAT=ierr(4))
-
-     ALLOCATE( tmltrd_sum(jpi,jpj,jpltrd),tmltrd_csum_ln(jpi,jpj,jpltrd),      &
-        &      tmltrd_csum_ub(jpi,jpj,jpltrd), smltrd_sum(jpi,jpj,jpltrd),     &
-        &      smltrd_csum_ln(jpi,jpj,jpltrd), smltrd_csum_ub(jpi,jpj,jpltrd), STAT=ierr(5) )
-#endif
-      !
-      trdmld_oce_alloc = MAXVAL( ierr )
-      IF( lk_mpp                )   CALL mpp_sum ( trdmld_oce_alloc )
-      IF( trdmld_oce_alloc /= 0 )   CALL ctl_warn('trdmld_oce_alloc: failed to allocate arrays')
-      !
-   END FUNCTION trdmld_oce_alloc
-
-   !!======================================================================
-END MODULE trdmld_oce
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmld_rst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmld_rst.F90	(revision 5074)
+++ 	(revision )
@@ -1,207 +1,0 @@
-MODULE trdmld_rst
-   !!=================================================================================
-   !!                       ***  MODULE  trdmld_rst  ***
-   !! Ocean dynamic :  Input/Output files for restart on mixed-layer diagnostics
-   !!=================================================================================
-   !! History :  9.0  ! 05-05 (C. Deltel) Original code
-   !!---------------------------------------------------------------------------------
-#if defined key_trdmld
-   !!---------------------------------------------------------------------------------
-   USE dom_oce         ! ocean space and time domain
-   USE trdmod_oce      ! ocean variables for trend diagnostics (i.e. icp/mixed-layer/vorticity)
-   USE in_out_manager  ! I/O manager
-   USE iom             ! I/O module
-
-   IMPLICIT NONE
-   PRIVATE
-  
-   PUBLIC   trd_mld_rst_read    ! routine called by trd_mld_init
-   PUBLIC   trd_mld_rst_write   ! routine called by step.F90
-  
-   INTEGER ::   nummldw         ! logical unit for mld restart
-
-   !!---------------------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$ 
-   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
-   !!---------------------------------------------------------------------------------
-  
-CONTAINS
-  
-   SUBROUTINE trd_mld_rst_write( kt )
-      !!--------------------------------------------------------------------------------
-      !!                  ***  SUBROUTINE trd_mld_rst_wri  ***
-      !!                
-      !! ** Purpose :   Write mixed-layer diagnostics restart fields.
-      !!--------------------------------------------------------------------------------
-      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
-      !
-      CHARACTER (len=35) :: charout
-      INTEGER ::   jk                 ! loop indice
-      CHARACTER(LEN=20)   ::   clkt     ! ocean time-step deine as a character
-      CHARACTER(LEN=50)   ::   clname   ! ice output restart file name
-      !!--------------------------------------------------------------------------------
-
-      ! to get better performances with NetCDF format:
-      ! we open and define the ocean restart_mld file one time step before writing the data (-> at nitrst - 1)
-      ! except if we write ocean restart_mld files every time step or if an ocean restart_mld file was writen at nitend - 1
-      IF( kt == nitrst - 1 .OR. nstock == 1 .OR. ( kt == nitend .AND. MOD( nitend - 1, nstock ) == 0 ) ) THEN
-         ! beware of the format used to write kt (default is i8.8, that should be large enough...)
-         IF( nitrst > 999999999 ) THEN   ;   WRITE(clkt, *       ) nitrst
-         ELSE                            ;   WRITE(clkt, '(i8.8)') nitrst
-         ENDIF
-         ! create the file
-         clname = TRIM(cexper)//"_"//TRIM(ADJUSTL(clkt))//"_"//TRIM(cn_trdrst_out)
-         IF(lwp) THEN
-            WRITE(numout,*)
-            SELECT CASE ( jprstlib )
-            CASE ( jprstdimg )   ;   WRITE(numout,*) '             open ocean restart_mld binary file: '//clname
-            CASE DEFAULT         ;   WRITE(numout,*) '             open ocean restart_mld NetCDF file: '//clname
-            END SELECT
-            IF( kt == nitrst - 1 ) THEN   ;   WRITE(numout,*) '             kt = nitrst - 1 = ', kt,' date= ', ndastp
-            ELSE                          ;   WRITE(numout,*) '             kt = '             , kt,' date= ', ndastp
-            ENDIF
-         ENDIF
-
-         CALL iom_open( clname, nummldw, ldwrt = .TRUE., kiolib = jprstlib )
-      ENDIF
-
-      IF( kt == nitrst .AND. lwp ) THEN
-         WRITE(numout,*)
-         WRITE(numout,*) 'trdmld_rst: output for ML diags. restart, with trd_mld_rst_write routine kt =', kt
-         WRITE(numout,*) '~~~~~~~~~~'
-         WRITE(numout,*)
-      ENDIF
-
-      IF( ln_trdmld_instant ) THEN 
-         !-- Temperature
-         CALL iom_rstput( kt, nitrst, nummldw, 'tmlbb'           , tmlbb           )
-         CALL iom_rstput( kt, nitrst, nummldw, 'tmlbn'           , tmlbn           )
-         CALL iom_rstput( kt, nitrst, nummldw, 'tmlatfb'         , tmlatfb         )
-
-         !-- Salinity
-         CALL iom_rstput( kt, nitrst, nummldw, 'smlbb'           , smlbb           )
-         CALL iom_rstput( kt, nitrst, nummldw, 'smlbn'           , smlbn           )
-         CALL iom_rstput( kt, nitrst, nummldw, 'smlatfb'         , smlatfb         )
-      ELSE
-         CALL iom_rstput( kt, nitrst, nummldw, 'rmldbn'          , rmldbn          )
-
-         !-- Temperature
-         CALL iom_rstput( kt, nitrst, nummldw, 'tmlbn'           , tmlbn           )
-         CALL iom_rstput( kt, nitrst, nummldw, 'tml_sumb'        , tml_sumb        )
-         DO jk = 1, jpltrd
-            IF( jk < 10 ) THEN   ;   WRITE(charout,FMT="('tmltrd_csum_ub_', I1)") jk
-            ELSE                 ;   WRITE(charout,FMT="('tmltrd_csum_ub_', I2)") jk
-            ENDIF
-            CALL iom_rstput( kt, nitrst, nummldw, charout,  tmltrd_csum_ub(:,:,jk) )
-         ENDDO
-         CALL iom_rstput( kt, nitrst, nummldw, 'tmltrd_atf_sumb' , tmltrd_atf_sumb )
-
-         !-- Salinity
-         CALL iom_rstput( kt, nitrst, nummldw, 'smlbn'           , smlbn           )
-         CALL iom_rstput( kt, nitrst, nummldw, 'sml_sumb'        , sml_sumb        )
-         DO jk = 1, jpltrd
-            IF( jk < 10 ) THEN   ;   WRITE(charout,FMT="('smltrd_csum_ub_', I1)") jk
-            ELSE                 ;   WRITE(charout,FMT="('smltrd_csum_ub_', I2)") jk
-            ENDIF
-            CALL iom_rstput( kt, nitrst, nummldw, charout , smltrd_csum_ub(:,:,jk) )
-         ENDDO
-         CALL iom_rstput( kt, nitrst, nummldw, 'smltrd_atf_sumb' , smltrd_atf_sumb )
-      ENDIF
-      !
-      IF( kt == nitrst ) THEN
-         CALL iom_close( nummldw )     ! close the restart file (only at last time step)
-         lrst_oce = .FALSE.
-      ENDIF
-      ! 
-      !    
-   END SUBROUTINE trd_mld_rst_write
-
-
-   SUBROUTINE trd_mld_rst_read
-    !!----------------------------------------------------------------------------
-    !!                   ***  SUBROUTINE trd_mld_rst_lec  ***
-    !!                   
-    !! ** Purpose :   Read file for mixed-layer diagnostics restart.
-    !!----------------------------------------------------------------------------
-    INTEGER  ::  inum       ! temporary logical unit
-    !
-    CHARACTER (len=35) :: charout
-    INTEGER ::   jk         ! loop indice
-    INTEGER ::   jlibalt = jprstlib
-    LOGICAL ::   llok
-    !!-----------------------------------------------------------------------------
-
-    IF(lwp)  THEN
-       WRITE(numout,*)
-       WRITE(numout,*) ' trd_mld_rst_read : read the NetCDF MLD restart file'
-       WRITE(numout,*) ' ~~~~~~~~~~~~~~~~'
-    ENDIF
-    IF ( jprstlib == jprstdimg ) THEN
-       ! eventually read netcdf file (monobloc)  for restarting on different number of processors
-       ! if {cn_trdrst_in}.nc exists, then set jlibalt to jpnf90
-       INQUIRE( FILE = TRIM(cn_trdrst_in)//'.nc', EXIST = llok )
-       IF ( llok ) THEN ; jlibalt = jpnf90  ; ELSE ; jlibalt = jprstlib ; ENDIF
-    ENDIF
-
-    CALL iom_open( cn_trdrst_in, inum, kiolib = jlibalt ) 
-
-    IF( ln_trdmld_instant ) THEN 
-       !-- Temperature
-       CALL iom_get( inum, jpdom_autoglo, 'tmlbb'           , tmlbb          )
-       CALL iom_get( inum, jpdom_autoglo, 'tmlbn'           , tmlbn          )
-       CALL iom_get( inum, jpdom_autoglo, 'tmlatfb'         , tmlatfb        )
-
-       !-- Salinity
-       CALL iom_get( inum, jpdom_autoglo, 'smlbb'           , smlbb          )
-       CALL iom_get( inum, jpdom_autoglo, 'smlbn'           , smlbn          )
-       CALL iom_get( inum, jpdom_autoglo, 'smlatfb'         , smlatfb        )
-    ELSE
-       CALL iom_get( inum, jpdom_autoglo, 'rmldbn'          , rmldbn         ) ! needed for rmld_sum
-
-       !-- Temperature
-       CALL iom_get( inum, jpdom_autoglo, 'tmlbn'           , tmlbn          ) ! needed for tml_sum
-       CALL iom_get( inum, jpdom_autoglo, 'tml_sumb'        , tml_sumb       )
-       DO jk = 1, jpltrd
-          IF( jk < 10 )   THEN
-             WRITE(charout,FMT="('tmltrd_csum_ub_', I1)") jk
-          ELSE
-             WRITE(charout,FMT="('tmltrd_csum_ub_', I2)") jk
-          ENDIF
-          CALL iom_get( inum, jpdom_autoglo, charout, tmltrd_csum_ub(:,:,jk) )
-       ENDDO
-       CALL iom_get( inum, jpdom_autoglo, 'tmltrd_atf_sumb' , tmltrd_atf_sumb)
-
-       !-- Salinity
-       CALL iom_get( inum, jpdom_autoglo, 'smlbn'           , smlbn          ) ! needed for sml_sum
-       CALL iom_get( inum, jpdom_autoglo, 'sml_sumb'        , sml_sumb       )
-       DO jk = 1, jpltrd
-          IF( jk < 10 )   THEN
-             WRITE(charout,FMT="('smltrd_csum_ub_', I1)") jk
-          ELSE
-             WRITE(charout,FMT="('smltrd_csum_ub_', I2)") jk
-          ENDIF
-          CALL iom_get( inum, jpdom_autoglo, charout, smltrd_csum_ub(:,:,jk) )
-       ENDDO
-       CALL iom_get( inum, jpdom_autoglo, 'smltrd_atf_sumb' , smltrd_atf_sumb)
-
-       CALL iom_close( inum )
-    ENDIF
-
-  END SUBROUTINE trd_mld_rst_read
-  
-#else
-  !!=================================================================================
-  !!                       ***  MODULE  trdmld_rst  ***
-  !! Ocean dynamic :  Input/Output files for restart on mixed-layer diagnostics
-  !!=================================================================================
-CONTAINS
-  SUBROUTINE trd_mld_rst_write( kt )           !  No ML diags ==> empty routine
-    WRITE(*,*) 'trd_mld_rst_wri: You should not have seen this print! error?', kt
-  END SUBROUTINE trd_mld_rst_write
-  SUBROUTINE trd_mld_rst_read                  !  No ML Diags ==> empty routine
-  END SUBROUTINE trd_mld_rst_read
-#endif
-
-  !!=================================================================================
-END MODULE trdmld_rst
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmod.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmod.F90	(revision 5074)
+++ 	(revision )
@@ -1,290 +1,0 @@
-MODULE trdmod
-   !!======================================================================
-   !!                       ***  MODULE  trdmod  ***
-   !! Ocean diagnostics:  ocean tracers and dynamic trends
-   !!=====================================================================
-   !! History :  1.0  !  2004-08  (C. Talandier) Original code
-   !!             -   !  2005-04  (C. Deltel)    Add Asselin trend in the ML budget
-   !!            3.3  ! 2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
-   !!----------------------------------------------------------------------
-#if  defined key_trdtra || defined key_trddyn || defined key_trdmld || defined key_trdvor || defined key_esopa
-   !!----------------------------------------------------------------------
-   !!   trd_mod          : Call the trend to be computed
-   !!   trd_mod_init     : Initialization step
-   !!----------------------------------------------------------------------
-   USE oce                     ! ocean dynamics and tracers variables
-   USE dom_oce                 ! ocean space and time domain variables
-   USE zdf_oce                 ! ocean vertical physics variables
-   USE trdmod_oce              ! ocean variables trends
-   USE ldftra_oce              ! ocean active tracers lateral physics
-   USE sbc_oce                 ! surface boundary condition: ocean
-   USE phycst                  ! physical constants
-   USE trdvor                  ! ocean vorticity trends 
-   USE trdicp                  ! ocean bassin integral constraints properties
-   USE trdmld                  ! ocean active mixed layer tracers trends 
-   USE in_out_manager          ! I/O manager
-   USE lib_mpp                 ! MPP library
-   USE wrk_nemo                ! Memory allocation
-
-
-   IMPLICIT NONE
-   PRIVATE
-
-   REAL(wp) ::   r2dt          ! time-step, = 2 rdttra except at nit000 (=rdttra) if neuler=0
-
-   PUBLIC trd_mod              ! called by all dynXX or traXX modules
-   PUBLIC trd_mod_init         ! called by opa.F90 module
-
-   !! * Substitutions
-#  include "domzgr_substitute.h90"
-#  include "vectopt_loop_substitute.h90"
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$
-   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-
-CONTAINS
-
-   SUBROUTINE trd_mod( ptrdx, ptrdy, ktrd, ctype, kt )
-      !!---------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mod  ***
-      !! 
-      !! ** Purpose : Dispatch all trends computation, e.g. vorticity, mld or 
-      !!              integral constraints
-      !!----------------------------------------------------------------------
-      !
-      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdx   ! Temperature or U trend 
-      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdy   ! Salinity    or V trend
-      CHARACTER(len=3)          , INTENT(in   ) ::   ctype   ! momentum or tracers trends type 'DYN'/'TRA'
-      INTEGER                   , INTENT(in   ) ::   kt      ! time step
-      INTEGER                   , INTENT(in   ) ::   ktrd    ! tracer trend index
-      !!
-      INTEGER ::   ji, jj   ! dummy loop indices
-      REAL(wp), POINTER, DIMENSION(:,:)  :: ztswu, ztswv, ztbfu, ztbfv, z2dx, z2dy 
-      !!----------------------------------------------------------------------
-
-      CALL wrk_alloc( jpi, jpj, ztswu, ztswv, ztbfu, ztbfv, z2dx, z2dy )
-
-      z2dx(:,:) = 0._wp   ;   z2dy(:,:) = 0._wp                            ! initialization of workspace arrays
-
-      IF( neuler == 0 .AND. kt == nit000    ) THEN   ;   r2dt =      rdt   ! = rdtra (restart with Euler time stepping)
-      ELSEIF(               kt <= nit000 + 1) THEN   ;   r2dt = 2. * rdt   ! = 2 rdttra (leapfrog)
-      ENDIF
-
-      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-      ! I. Integral Constraints Properties for momentum and/or tracers trends
-      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-
-      IF( ( mod(kt,nn_trd) == 0 .OR. kt == nit000 .OR. kt == nitend) )   THEN
-         !
-         IF( lk_trdtra .AND. ctype == 'TRA' )   THEN       ! active tracer trends
-            SELECT CASE ( ktrd )
-            CASE ( jptra_trd_ldf )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_ldf, ctype )   ! lateral diff
-            CASE ( jptra_trd_zdf )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_zdf, ctype )   ! vertical diff (Kz)
-            CASE ( jptra_trd_bbc )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_bbc, ctype )   ! bottom boundary cond
-            CASE ( jptra_trd_bbl )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_bbl, ctype )   ! bottom boundary layer
-            CASE ( jptra_trd_npc )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_npc, ctype )   ! static instability mixing
-            CASE ( jptra_trd_dmp )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_dmp, ctype )   ! damping
-            CASE ( jptra_trd_qsr )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_qsr, ctype )   ! penetrative solar radiat.
-            CASE ( jptra_trd_nsr )   ;   z2dx(:,:) = ptrdx(:,:,1)   
-                                         z2dy(:,:) = ptrdy(:,:,1)
-                                         CALL trd_icp( z2dx , z2dy , jpicpt_nsr, ctype )   ! non solar radiation
-            CASE ( jptra_trd_xad )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_xad, ctype )   ! x- horiz adv
-            CASE ( jptra_trd_yad )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_yad, ctype )   ! y- horiz adv
-            CASE ( jptra_trd_zad )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpt_zad, ctype )   ! z- vertical adv 
-                                         CALL trd_icp( ptrdx, ptrdy, jpicpt_zad, ctype )   
-                                         ! compute the surface flux condition wn(:,:,1)*tsn(:,:,1,jp_tem)
-                                         z2dx(:,:) = wn(:,:,1)*tsn(:,:,1,jp_tem)/fse3t(:,:,1)
-                                         z2dy(:,:) = wn(:,:,1)*tsn(:,:,1,jp_sal)/fse3t(:,:,1)
-                                         CALL trd_icp( z2dx , z2dy , jpicpt_zl1, ctype )   ! 1st z- vertical adv 
-            END SELECT
-         END IF
-
-         IF( lk_trddyn .AND. ctype == 'DYN' )   THEN       ! momentum trends 
-            !
-            SELECT CASE ( ktrd )
-            CASE ( jpdyn_trd_hpg )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_hpg, ctype )   ! hydrost. pressure grad
-            CASE ( jpdyn_trd_keg )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_keg, ctype )   ! KE gradient 
-            CASE ( jpdyn_trd_rvo )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_rvo, ctype )   ! relative vorticity 
-            CASE ( jpdyn_trd_pvo )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_pvo, ctype )   ! planetary vorticity
-            CASE ( jpdyn_trd_ldf )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_ldf, ctype )   ! lateral diffusion 
-            CASE ( jpdyn_trd_had )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_had, ctype )   ! horizontal advection 
-            CASE ( jpdyn_trd_zad )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_zad, ctype )   ! vertical advection 
-            CASE ( jpdyn_trd_spg )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_spg, ctype )   ! surface pressure grad.
-            CASE ( jpdyn_trd_dat )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_dat, ctype )   ! damping term
-            CASE ( jpdyn_trd_zdf )                                                         ! vertical diffusion 
-               ! subtract surface forcing/bottom friction trends 
-               ! from vertical diffusive momentum trends
-               ztswu(:,:) = 0._wp   ;   ztswv(:,:) = 0._wp
-               ztbfu(:,:) = 0._wp   ;   ztbfv(:,:) = 0._wp 
-               DO jj = 2, jpjm1   
-                  DO ji = fs_2, fs_jpim1   ! vector opt.
-                     ! save the surface forcing momentum fluxes
-                     ztswu(ji,jj) = utau(ji,jj) / ( fse3u(ji,jj,1)*rau0 )
-                     ztswv(ji,jj) = vtau(ji,jj) / ( fse3v(ji,jj,1)*rau0 )
-                     ! bottom friction contribution now handled explicitly
-                     ptrdx(ji,jj,1) = ptrdx(ji,jj,1) - ztswu(ji,jj)
-                     ptrdy(ji,jj,1) = ptrdy(ji,jj,1) - ztswv(ji,jj)
-                  END DO
-               END DO
-               !
-               CALL trd_icp( ptrdx, ptrdy, jpicpd_zdf, ctype )   
-               CALL trd_icp( ztswu, ztswv, jpicpd_swf, ctype )                               ! wind stress forcing term
-               ! bottom friction contribution now handled explicitly
-            CASE ( jpdyn_trd_bfr )   ;   CALL trd_icp( ptrdx, ptrdy, jpicpd_bfr, ctype )     ! bottom friction term
-            END SELECT
-            !
-         END IF
-         !
-      END IF
-
-      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-      ! II. Vorticity trends
-      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-
-      IF( lk_trdvor .AND. ctype == 'DYN' )   THEN
-         !
-         SELECT CASE ( ktrd ) 
-         CASE ( jpdyn_trd_hpg )   ;   CALL trd_vor_zint( ptrdx, ptrdy, jpvor_prg )   ! Hydrostatique Pressure Gradient 
-         CASE ( jpdyn_trd_keg )   ;   CALL trd_vor_zint( ptrdx, ptrdy, jpvor_keg )   ! KE Gradient 
-         CASE ( jpdyn_trd_rvo )   ;   CALL trd_vor_zint( ptrdx, ptrdy, jpvor_rvo )   ! Relative Vorticity 
-         CASE ( jpdyn_trd_pvo )   ;   CALL trd_vor_zint( ptrdx, ptrdy, jpvor_pvo )   ! Planetary Vorticity Term 
-         CASE ( jpdyn_trd_ldf )   ;   CALL trd_vor_zint( ptrdx, ptrdy, jpvor_ldf )   ! Horizontal Diffusion 
-         CASE ( jpdyn_trd_had )   ;   CALL ctl_warn('Vorticity for horizontal advection trend never checked')   
-         CASE ( jpdyn_trd_zad )   ;   CALL trd_vor_zint( ptrdx, ptrdy, jpvor_zad )   ! Vertical Advection 
-         CASE ( jpdyn_trd_spg )   ;   CALL trd_vor_zint( ptrdx, ptrdy, jpvor_spg )   ! Surface Pressure Grad. 
-         CASE ( jpdyn_trd_dat )   ;   CALL trd_vor_zint( ptrdx, ptrdy, jpvor_bev )   ! Beta V  
-         CASE ( jpdyn_trd_zdf )                                                      ! Vertical Diffusion 
-            ! subtract surface forcing/bottom friction trends 
-            ! from vertical diffusive momentum trends
-            ztswu(:,:) = 0.e0   ;   ztswv(:,:) = 0.e0
-            ztbfu(:,:) = 0.e0   ;   ztbfv(:,:) = 0.e0  
-            DO jj = 2, jpjm1   
-               DO ji = fs_2, fs_jpim1   ! vector opt.
-                  ! save the surface forcing momentum fluxes
-                  ztswu(ji,jj) = utau(ji,jj) / ( fse3u(ji,jj,1)*rau0 )
-                  ztswv(ji,jj) = vtau(ji,jj) / ( fse3v(ji,jj,1)*rau0 )
-                  !
-                  ptrdx(ji,jj,1     ) = ptrdx(ji,jj,1     ) - ztswu(ji,jj)
-                  ptrdy(ji,jj,1     ) = ptrdy(ji,jj,1     ) - ztswv(ji,jj)
-               END DO
-            END DO
-            !
-            CALL trd_vor_zint( ptrdx, ptrdy, jpvor_zdf )   
-            CALL trd_vor_zint( ztswu, ztswv, jpvor_swf )                               ! Wind stress forcing term
-         CASE ( jpdyn_trd_bfr )
-            CALL trd_vor_zint( ptrdx, ptrdy, jpvor_bfr )                               ! Bottom friction term
-         END SELECT
-         !
-      ENDIF
-
-      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-      ! III. Mixed layer trends for active tracers
-      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-
-      IF( lk_trdmld .AND. ctype == 'TRA' )   THEN
-         
-         !-----------------------------------------------------------------------------------------------
-         ! W.A.R.N.I.N.G :
-         ! jptra_trd_ldf : called by traldf.F90
-         !                 at this stage we store:
-         !                  - the lateral geopotential diffusion (here, lateral = horizontal)
-         !                  - and the iso-neutral diffusion if activated 
-         ! jptra_trd_zdf : called by trazdf.F90
-         !                 * in case of iso-neutral diffusion we store the vertical diffusion component in the 
-         !                   lateral trend including the K_z contrib, which will be removed later (see trd_mld)
-         !-----------------------------------------------------------------------------------------------
-
-         SELECT CASE ( ktrd )
-         CASE ( jptra_trd_xad )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_xad, '3D' )   ! merid. advection
-         CASE ( jptra_trd_yad )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_yad, '3D' )   ! zonal  advection
-         CASE ( jptra_trd_zad )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_zad, '3D' )   ! vertical advection
-         CASE ( jptra_trd_ldf )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_ldf, '3D' )   ! lateral diffusive
-         CASE ( jptra_trd_bbl )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_bbl, '3D' )   ! bottom boundary layer
-         CASE ( jptra_trd_zdf )
-            IF( ln_traldf_iso )   THEN
-               CALL trd_mld_zint( ptrdx, ptrdy, jpmld_ldf, '3D' )   ! vertical diffusion (K_z)
-            ELSE
-               CALL trd_mld_zint( ptrdx, ptrdy, jpmld_zdf, '3D' )   ! vertical diffusion (K_z)
-            ENDIF
-         CASE ( jptra_trd_dmp )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_dmp, '3D' )   ! internal 3D restoring (tradmp)
-         CASE ( jptra_trd_qsr )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_for, '3D' )   ! air-sea : penetrative sol radiat
-         CASE ( jptra_trd_nsr )
-            ptrdx(:,:,2:jpk) = 0.e0   ;   ptrdy(:,:,2:jpk) = 0.e0
-            CALL trd_mld_zint( ptrdx, ptrdy, jpmld_for, '2D' )                             ! air-sea : non penetr sol radiat
-         CASE ( jptra_trd_bbc )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_bbc, '3D' )   ! bottom bound cond (geoth flux)
-         CASE ( jptra_trd_atf )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_atf, '3D' )   ! asselin numerical
-         CASE ( jptra_trd_npc )   ;   CALL trd_mld_zint( ptrdx, ptrdy, jpmld_npc, '3D' )   ! non penetr convect adjustment
-         END SELECT
-
-      ENDIF
-      !
-      CALL wrk_dealloc( jpi, jpj, ztswu, ztswv, ztbfu, ztbfv, z2dx, z2dy )
-      !
-   END SUBROUTINE trd_mod
-
-#else
-   !!----------------------------------------------------------------------
-   !!   Default case :                                         Empty module
-   !!----------------------------------------------------------------------
-   USE trdmod_oce      ! ocean variables trends
-   USE trdvor          ! ocean vorticity trends 
-   USE trdicp          ! ocean bassin integral constraints properties
-   USE trdmld          ! ocean active mixed layer tracers trends 
-   !!----------------------------------------------------------------------
-CONTAINS
-   SUBROUTINE trd_mod(ptrd3dx, ptrd3dy, ktrd , ctype, kt )   ! Empty routine
-      REAL(wp) ::   ptrd3dx(:,:,:), ptrd3dy(:,:,:)
-      INTEGER  ::   ktrd, kt                            
-      CHARACTER(len=3) ::  ctype                  
-      WRITE(*,*) 'trd_3d: You should not have seen this print! error ?', ptrd3dx(1,1,1), ptrd3dy(1,1,1)
-      WRITE(*,*) ' "   ": You should not have seen this print! error ?', ktrd, ctype, kt
-   END SUBROUTINE trd_mod
-#endif
-
-   SUBROUTINE trd_mod_init
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mod_init  ***
-      !! 
-      !! ** Purpose :   Initialization of activated trends
-      !!----------------------------------------------------------------------
-      USE in_out_manager          ! I/O manager
-      USE lib_mpp                 ! MPP library
-      !!    
-      NAMELIST/namtrd/ nn_trd, nn_ctls, cn_trdrst_in, cn_trdrst_out, ln_trdmld_restart, rn_ucf, ln_trdmld_instant
-      INTEGER  ::   ios           ! Local integer output status for namelist read
-      !!----------------------------------------------------------------------
-
-      IF( l_trdtra .OR. l_trddyn )   THEN
- 
-         REWIND( numnam_ref )              ! Namelist namtrd in reference namelist : Diagnostics: trends
-         READ  ( numnam_ref, namtrd, IOSTAT = ios, ERR = 901)
-901      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namtrd in reference namelist', lwp )
-
-         REWIND( numnam_cfg )              ! Namelist namtrd in configuration namelist : Diagnostics: trends
-         READ  ( numnam_cfg, namtrd, IOSTAT = ios, ERR = 902 )
-902      IF( ios /= 0 ) CALL ctl_nam ( ios , 'namtrd in configuration namelist', lwp )
-         IF(lwm) WRITE ( numond, namtrd )
-
-         IF(lwp) THEN
-            WRITE(numout,*)
-            WRITE(numout,*) ' trd_mod_init : Momentum/Tracers trends'
-            WRITE(numout,*) ' ~~~~~~~~~~~~~'
-            WRITE(numout,*) '   Namelist namtrd : set trends parameters'
-            WRITE(numout,*) '      frequency of trends diagnostics   nn_trd             = ', nn_trd
-            WRITE(numout,*) '      control surface type              nn_ctls            = ', nn_ctls
-            WRITE(numout,*) '      restart for ML diagnostics        ln_trdmld_restart  = ', ln_trdmld_restart
-            WRITE(numout,*) '      instantaneous or mean ML T/S      ln_trdmld_instant  = ', ln_trdmld_instant
-            WRITE(numout,*) '      unit conversion factor            rn_ucf             = ', rn_ucf
-        ENDIF
-      ENDIF
-      !
-      IF( lk_trddyn .OR. lk_trdtra )    CALL trd_icp_init       ! integral constraints trends
-      IF( lk_trdmld                )    CALL trd_mld_init       ! mixed-layer trends (active  tracers)  
-      IF( lk_trdvor                )    CALL trd_vor_init       ! vorticity trends        
-      !
-   END SUBROUTINE trd_mod_init
-
-   !!======================================================================
-END MODULE trdmod
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmod_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmod_oce.F90	(revision 5074)
+++ 	(revision )
@@ -1,79 +1,0 @@
-MODULE trdmod_oce
-   !!======================================================================
-   !!                   ***  MODULE trdmod_oce  ***
-   !! Ocean trends :   set tracer and momentum trend variables
-   !!======================================================================
-   !! History :  1.0  !  2004-08  (C. Talandier) Original code
-   !!----------------------------------------------------------------------
-   USE trdicp_oce              ! ocean momentum/tracers bassin properties trends variables
-   USE trdmld_oce              ! ocean active mixed layer tracers trends variables
-   USE trdvor_oce              ! ocean vorticity trends variables
-
-   IMPLICIT NONE
-   PUBLIC
-
-   !                                        !!* Namelist namtrd:  diagnostics on dynamics/tracer trends *
-   INTEGER , PUBLIC  ::   nn_trd             !: time step frequency dynamics and tracers trends
-   INTEGER , PUBLIC  ::   nn_ctls            !: control surface type for trends vertical integration
-   REAL(wp), PUBLIC  ::   rn_ucf             !: unit conversion factor (for netCDF trends outputs)
-                                             !: =1. (=86400.) for degC/s (degC/day) and psu/s (psu/day)
-   CHARACTER(len=32) ::   cn_trdrst_in       !: suffix of ocean restart name (input)
-   CHARACTER(len=32) ::   cn_trdrst_out      !: suffix of ocean restart name (output)
-   LOGICAL , PUBLIC  ::   ln_trdmld_instant  !: flag to diagnose inst./mean ML T/S trends
-   LOGICAL , PUBLIC  ::   ln_trdmld_restart  !: flag to restart mixed-layer diagnostics
-
-# if defined key_trdtra   ||   defined key_trdmld
-   LOGICAL , PUBLIC ::   l_trdtra = .TRUE.                !: tracers  trend flag
-# else
-   LOGICAL , PUBLIC ::   l_trdtra = .FALSE.               !: tracers  trend flag
-# endif
-# if defined key_trddyn   ||   defined key_trdvor
-   LOGICAL , PUBLIC ::   l_trddyn = .TRUE.                !: momentum trend flag
-# else
-   LOGICAL , PUBLIC ::   l_trddyn = .FALSE.               !: momentum trend flag
-# endif
-# if ( defined key_trdtrc && defined key_iomput )  ||  defined key_trdmld_trc
-   LOGICAL , PUBLIC ::   l_trdtrc = .TRUE.                !: tracers  trend flag
-# else
-   LOGICAL , PUBLIC ::   l_trdtrc = .FALSE.               !: tracers  trend flag
-# endif
-   !                                                     !!!* Active tracers trends indexes
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_xad =  1     !: x- horizontal advection
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_yad =  2     !: y- horizontal advection
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_zad =  3     !: z- vertical   advection
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_ldf =  4     !: lateral       diffusion
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_zdf =  5     !: vertical diffusion (Kz)
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_bbc =  6     !: Bottom Boundary Condition (geoth. flux) 
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_bbl =  7     !: Bottom Boundary Layer (diffusive/convective)
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_npc =  8     !: static instability mixing
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_dmp =  9     !: damping
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_qsr = 10     !: penetrative solar radiation
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_nsr = 11     !: non solar radiation
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_atf = 12     !: Asselin correction
-#if defined key_top
-   !                                                     !!!* Passive tracers trends indexes
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_sms  = 13    !: sources m. sinks
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_radn = 14    !: corr. trn<0 in trcrad
-   INTEGER, PUBLIC, PARAMETER ::   jptra_trd_radb = 15    !: corr. trb<0 in trcrad (like atf)
-#endif
-   
-   !                                                     !!!* Momentum trends indexes
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_hpg =  1     !: hydrostatic pressure gradient 
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_keg =  2     !: kinetic energy gradient
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_rvo =  3     !: relative vorticity
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_pvo =  4     !: planetary vorticity
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_ldf =  5     !: lateral diffusion
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_had =  6     !: horizontal advection
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_zad =  7     !: vertical advection
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_zdf =  8     !: vertical diffusion
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_spg =  9     !: surface pressure gradient
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_dat = 10     !: damping term
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_swf = 11     !: surface wind forcing
-   INTEGER, PUBLIC, PARAMETER ::   jpdyn_trd_bfr = 12     !: bottom friction 
-
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$
-   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-   !!======================================================================
-END MODULE trdmod_oce
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmod_trc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmod_trc.F90	(revision 5074)
+++ 	(revision )
@@ -1,23 +1,0 @@
-MODULE trdmod_trc
-   !!======================================================================
-   !!                       ***  MODULE trdmod_trc  ***
-   !!  Dummy module
-   !!======================================================================
-   !!----------------------------------------------------------------------
-   !!   Dummy module                                             NO TOP use
-   !!----------------------------------------------------------------------
-CONTAINS
-
-   SUBROUTINE trd_mod_trc( ptrtrd, kjn, ktrd, kt )
-      INTEGER ::   kt, kjn, ktrd   
-      REAL    ::   ptrtrd(:,:,:)  
-      WRITE(*,*) 'trd_mod_trc_trp : You should not have seen this print! error?', ptrtrd(1,1,1)
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kjn, ktrd, kt
-   END SUBROUTINE trd_mod_trc
-
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
-   !! $Id$
-   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
-   !!======================================================================
-END MODULE trdmod_trc
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl.F90	(revision 5075)
@@ -0,0 +1,899 @@
+MODULE trdmxl
+   !!======================================================================
+   !!                       ***  MODULE  trdmxl  ***
+   !! Ocean diagnostics:  mixed layer T-S trends 
+   !!======================================================================
+   !! History :  OPA  !  1995-04  (J. Vialard)    Original code
+   !!                 !  1997-02  (E. Guilyardi)  Adaptation global + base cmo
+   !!                 !  1999-09  (E. Guilyardi)  Re-writing + netCDF output
+   !!   NEMO     1.0  !  2002-06  (G. Madec)      F90: Free form and module
+   !!             -   !  2004-08  (C. Talandier)  New trends organization
+   !!            2.0  !  2005-05  (C. Deltel)     Diagnose trends of time averaged ML T & S
+   !!            3.5  !  2012-03  (G. Madec)      complete reorganisation + change in the time averaging
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trd_mxl          : T and S cumulated trends averaged over the mixed layer
+   !!   trd_mxl_zint     : T and S trends vertical integration
+   !!   trd_mxl_init     : initialization step
+   !!----------------------------------------------------------------------
+   USE oce             ! ocean dynamics and tracers variables
+   USE dom_oce         ! ocean space and time domain variables
+   USE trd_oce         ! trends: ocean variables
+   USE trdmxl_oce      ! ocean variables trends
+   USE ldftra_oce      ! ocean active tracers lateral physics
+   USE zdf_oce         ! ocean vertical physics
+   USE in_out_manager  ! I/O manager
+   USE phycst          ! Define parameters for the routines
+   USE dianam          ! build the name of file (routine)
+   USE ldfslp          ! iso-neutral slopes 
+   USE zdfmxl          ! mixed layer depth
+   USE zdfddm          ! ocean vertical physics: double diffusion
+   USE ioipsl          ! NetCDF library
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE diadimg         ! dimg direct access file format output
+   USE trdmxl_rst      ! restart for diagnosing the ML trends
+   USE prtctl          ! Print control
+   USE restart         ! for lrst_oce
+   USE lib_mpp         ! MPP library
+   USE wrk_nemo        ! Memory allocation
+   USE iom
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trd_mxl        ! routine called by step.F90
+   PUBLIC   trd_mxl_init   ! routine called by opa.F90
+   PUBLIC   trd_mxl_zint   ! routine called by tracers routines
+
+   INTEGER ::   nkstp       ! current time step 
+
+
+
+!!gm  to be moved from trdmxl_oce
+!   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   hml                ! ML depth (sum of e3t over nmln-1 levels) [m] 
+!   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   tml    , sml       ! now ML averaged T & S 
+!   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   tmlb_nf, smlb_nf   ! not filtered before ML averaged T & S
+!
+!
+!   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   hmlb, hmln         ! before, now, and after Mixed Layer depths [m]
+!   
+!   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   tb_mlb, tb_mln     ! before (not filtered) tracer averaged over before and now ML 
+!
+!   REAL(wp), ALLOCATABLE, DIMENSION(:,:) ::   tn_mln             ! now tracer averaged over now ML
+!!gm end   
+   
+   CHARACTER (LEN=40) ::  clhstnam         ! name of the trends NetCDF file
+   INTEGER ::   nh_t, nmoymltrd
+   INTEGER ::   nidtrd
+   INTEGER, ALLOCATABLE, SAVE, DIMENSION(:) ::   ndextrd1
+   INTEGER ::   ndimtrd1                        
+   INTEGER ::   ionce, icount                   
+
+   !! * Substitutions
+#  include "domzgr_substitute.h90"
+#  include "ldftra_substitute.h90"
+#  include "zdfddm_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: trdmxl.F90 3318 2012-02-25 15:50:01Z gm $ 
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_mxl_alloc()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( ndextrd1(jpi*jpj) , STAT=trd_mxl_alloc )
+      !
+      IF( lk_mpp             )   CALL mpp_sum ( trd_mxl_alloc )
+      IF( trd_mxl_alloc /= 0 )   CALL ctl_warn('trd_mxl_alloc: failed to allocate array ndextrd1')
+   END FUNCTION trd_mxl_alloc
+
+
+   SUBROUTINE trd_tra_mxl( ptrdx, ptrdy, ktrd, kt, p2dt, kmxln )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_tra_mng  ***
+      !! 
+      !! ** Purpose :   Dispatch all trends computation, e.g. 3D output, integral
+      !!                constraints, barotropic vorticity, kinetic enrgy, 
+      !!                potential energy, and/or mixed layer budget.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdx   ! Temperature or U trend 
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdy   ! Salinity    or V trend
+      INTEGER                   , INTENT(in   ) ::   ktrd    ! tracer trend index
+      INTEGER                   , INTENT(in   ) ::   kt      ! time step index
+      REAL(wp)                  , INTENT(in   ) ::   p2dt    ! time step  [s]
+      REAL(wp), DIMENSION(:,:)  , INTENT(in   ) ::   kmxln   ! number of t-box for the vertical average 
+      !
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+
+      !                         !==============================!
+      IF ( kt /= nkstp ) THEN   !=  1st call at kt time step  =!
+         !                      !==============================!
+         nkstp = kt
+         
+         
+         !                          !==  reset trend arrays to zero  ==!
+         tmltrd(:,:,:) = 0._wp    ;    smltrd(:,:,:) = 0._wp    
+         
+         
+         !
+         wkx(:,:,:) = 0._wp         !==  now ML weights for vertical averaging  ==!
+         DO jk = 1, jpktrd               ! initialize wkx with vertical scale factor in mixed-layer
+            DO jj = 1,jpj
+               DO ji = 1,jpi
+                  IF( jk - kmxln(ji,jj) < 0 )   wkx(ji,jj,jk) = fse3t(ji,jj,jk) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         hmxl(:,:) = 0._wp               ! NOW mixed-layer depth
+         DO jk = 1, jpktrd
+            hmxl(:,:) = hmxl(:,:) + wkx(:,:,jk)
+         END DO
+         DO jk = 1, jpktrd               ! integration weights
+            wkx(:,:,jk) = wkx(:,:,jk) / MAX( 1.e-20_wp, hmxl(:,:) ) * tmask(:,:,1)
+         END DO
+         
+         
+         !
+         !                          !==  Vertically averaged T and S  ==!
+         tml(:,:) = 0._wp   ;   sml(:,:) = 0._wp
+         DO jk = 1, jpktrd
+            tml(:,:) = tml(:,:) + wkx(:,:,jk) * tsn(:,:,jk,jp_tem)
+            sml(:,:) = sml(:,:) + wkx(:,:,jk) * tsn(:,:,jk,jp_sal)
+         END DO
+         !
+      ENDIF
+
+
+
+      ! mean now trends over the now ML 
+      tmltrd(:,:,ktrd) = tmltrd(:,:,ktrd) + ptrdx(:,:,jk) * wkx(:,:,jk)   ! temperature
+      smltrd(:,:,ktrd) = smltrd(:,:,ktrd) + ptrdy(:,:,jk) * wkx(:,:,jk)   ! salinity
+ 
+
+ 
+!!gm to be put juste before the output !
+!      ! Lateral boundary conditions
+!      CALL lbc_lnk( tmltrd(:,:,jl), 'T', 1. )
+!      CALL lbc_lnk( smltrd(:,:,jl), 'T', 1. )
+!!gm end
+
+
+
+		SELECT CASE( ktrd )
+		CASE( jptra_npc  )               ! non-penetrative convection: regrouped with zdf
+!!gm : to be completed ! 
+!		   IF( ....
+!!gm end
+		CASE( jptra_zdfp )               ! iso-neutral diffusion: "pure" vertical diffusion
+		   !                                   ! regroup iso-neutral diffusion in one term
+         tmltrd(:,:,jpmxl_ldf) = tmltrd(:,:,jpmxl_ldf) + ( tmltrd(:,:,jpmxl_zdf) - tmltrd(:,:,jpmxl_zdfp) )
+         smltrd(:,:,jpmxl_ldf) = smltrd(:,:,jpmxl_ldf) + ( smltrd(:,:,jpmxl_zdf) - smltrd(:,:,jpmxl_zdfp) )
+         !                                   ! put in zdf the dia-neutral diffusion
+         tmltrd(:,:,jpmxl_zdf) = tmltrd(:,:,jpmxl_zdfp)
+         smltrd(:,:,jpmxl_zdf) = smltrd(:,:,jpmxl_zdfp)
+         IF( ln_zdfnpc ) THEN
+            tmltrd(:,:,jpmxl_zdf) = tmltrd(:,:,jpmxl_zdf) + tmltrd(:,:,jpmxl_npc)
+            smltrd(:,:,jpmxl_zdf) = smltrd(:,:,jpmxl_zdf) + smltrd(:,:,jpmxl_npc)
+         ENDIF
+         !
+      CASE( jptra_atf  )               ! last trends of the current time step: perform the time averaging & output
+         !
+         ! after ML           :   zhmla                      NB will be swaped to provide hmln and hmlb
+         !
+         ! entrainement ent_1 :   tb_mln - tb_mlb        ==>> use previous timestep ztn_mla = tb_mln
+         !                                                    "     "         "     tn_mln = tb_mlb  (unfiltered tb!)
+         !                                                   NB: tn_mln itself comes from the 2 time step before (ta_mla)
+         !
+         ! atf trend          :   ztbf_mln - tb_mln      ==>> use previous timestep tn_mla = tb_mln
+         !                                                   need to compute tbf_mln, using the current tb
+         !                                                   which is the before fitered tracer
+         !
+         ! entrainement ent_2 :   zta_mla - zta_mln      ==>> need to compute zta_mla and zta_mln
+         !
+         ! time averaging     :   mean: CALL trd_mean( kt, ptrd, ptrdm )
+         !                              and out put the starting mean value and the total trends
+         !                              (i.e. difference between starting and ending values)
+         !                        hat : CALL trd_hat ( kt, ptrd, ptrdm )
+         !                              and output the starting hat value and the total hat trends
+         !
+         ! swaps              :   hmlb   <==   hmln   <== zhmla
+         !                        tb_mlb <==  tn_mln  <== zta_mla
+         !                        tb_mln <== ztn_mla     ==>> now T over after h, need to be computed here 
+         !                                                    to be used at next time step (unfiltered before)
+         !
+      END SELECT
+      !
+   END SUBROUTINE trd_tra_mxl
+
+
+   SUBROUTINE trd_mean( kt, ptrd, ptrdm )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mean  ***
+      !! 
+      !! ** Purpose :   
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in   ) ::   ptrd    ! trend at kt
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdm   ! cumulative trends at kt
+      INTEGER                   , INTENT(in   ) ::   kt      ! time step index
+      !!----------------------------------------------------------------------
+      !
+      IF ( kt == nn_it000 )   ptrdm(:,:,:) = 0._wp
+      !
+      ptrdm(:,:,:) = ptrdm(:,:,:) + ptrd(:,:,:)
+      !
+      IF ( MOD( kt - nn_it000 + 1, nn_trd ) == 0 ) THEN
+         !
+         ! call iom put????  avec en argument le tableau de nom des trends?
+         !
+      ENDIF
+      !
+   END SUBROUTINE trd_mean
+
+
+   SUBROUTINE trd_mxl_zint( pttrdmxl, pstrdmxl, ktrd, ctype )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_zint  ***
+      !! 
+      !! ** Purpose :   Compute the vertical average of the 3D fields given as arguments 
+      !!                to the subroutine. This vertical average is performed from ocean
+      !!                surface down to a chosen control surface.
+      !!
+      !! ** Method/usage :
+      !!      The control surface can be either a mixed layer depth (time varying)
+      !!      or a fixed surface (jk level or bowl). 
+      !!      Choose control surface with nn_ctls in namelist NAMTRD :
+      !!        nn_ctls = 0  : use mixed layer with density criterion 
+      !!        nn_ctls = 1  : read index from file 'ctlsurf_idx'
+      !!        nn_ctls > 1  : use fixed level surface jk = nn_ctls
+      !!      Note: in the remainder of the routine, the volume between the 
+      !!            surface and the control surface is called "mixed-layer"
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT( in ) ::   ktrd       ! ocean trend index
+      CHARACTER(len=2)                , INTENT( in ) ::   ctype      ! 2D surface/bottom or 3D interior physics
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( in ) ::   pttrdmxl   ! temperature trend 
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( in ) ::   pstrdmxl   ! salinity trend 
+      !
+      INTEGER ::   ji, jj, jk, isum
+      REAL(wp), POINTER, DIMENSION(:,:)  :: zvlmsk 
+      !!----------------------------------------------------------------------
+
+      CALL wrk_alloc( jpi, jpj, zvlmsk ) 
+
+      ! I. Definition of control surface and associated fields
+      ! ------------------------------------------------------
+      !            ==> only once per time step <== 
+
+      IF( icount == 1 ) THEN        
+         !
+         
+!!gm BUG?
+!!gm CAUTION:  double check the definition of nmln  it is the nb of w-level, not t-level I guess
+
+         
+         ! ... Set nmxl(ji,jj) = index of first T point below control surf. or outside mixed-layer
+         IF( nn_ctls == 0 ) THEN       ! * control surface = mixed-layer with density criterion 
+            nmxl(:,:) = nmln(:,:)    ! array nmln computed in zdfmxl.F90
+         ELSEIF( nn_ctls == 1 ) THEN   ! * control surface = read index from file 
+            nmxl(:,:) = nbol(:,:)
+         ELSEIF( nn_ctls >= 2 ) THEN   ! * control surface = model level
+            nn_ctls = MIN( nn_ctls, jpktrd - 1 )
+            nmxl(:,:) = nn_ctls + 1
+         ENDIF
+
+      END IF
+      !
+      CALL wrk_dealloc( jpi, jpj, zvlmsk ) 
+      !
+   END SUBROUTINE trd_mxl_zint
+    
+
+   SUBROUTINE trd_mxl( kt, p2dt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl  ***
+      !! 
+      !! ** Purpose :  Compute and cumulate the mixed layer trends over an analysis
+      !!               period, and write NetCDF (or dimg) outputs.
+      !!
+      !! ** Method/usage :
+      !!          The stored trends can be chosen twofold (according to the ln_trdmxl_instant 
+      !!          logical namelist variable) :
+      !!          1) to explain the difference between initial and final 
+      !!             mixed-layer T & S (where initial and final relate to the
+      !!             current analysis window, defined by nn_trd in the namelist)
+      !!          2) to explain the difference between the current and previous 
+      !!             TIME-AVERAGED mixed-layer T & S (where time-averaging is
+      !!             performed over each analysis window).
+      !!
+      !! ** Consistency check : 
+      !!        If the control surface is fixed ( nn_ctls > 1 ), the residual term (dh/dt
+      !!        entrainment) should be zero, at machine accuracy. Note that in the case
+      !!        of time-averaged mixed-layer fields, this residual WILL NOT BE ZERO
+      !!        over the first two analysis windows (except if restart).
+      !!        N.B. For ORCA2_LIM, use e.g. nn_trd=5, rn_ucf=1., nn_ctls=8
+      !!             for checking residuals.
+      !!             On a NEC-SX5 computer, this typically leads to:
+      !!                   O(1.e-20) temp. residuals (tml_res) when ln_trdmxl_instant=.false.
+      !!                   O(1.e-21) temp. residuals (tml_res) when ln_trdmxl_instant=.true.
+      !!
+      !! ** Action :
+      !!       At each time step, mixed-layer averaged trends are stored in the 
+      !!       tmltrd(:,:,jpmxl_xxx) array (see trdmxl_oce.F90 for definitions of jpmxl_xxx).
+      !!       This array is known when trd_mxl is called, at the end of the stp subroutine, 
+      !!       except for the purely vertical K_z diffusion term, which is embedded in the
+      !!       lateral diffusion trend.
+      !!
+      !!       In I), this K_z term is diagnosed and stored, thus its contribution is removed
+      !!       from the lateral diffusion trend.
+      !!       In II), the instantaneous mixed-layer T & S are computed, and misc. cumulative
+      !!       arrays are updated.
+      !!       In III), called only once per analysis window, we compute the total trends,
+      !!       along with the residuals and the Asselin correction terms.
+      !!       In IV), the appropriate trends are written in the trends NetCDF file.
+      !!
+      !! References :  Vialard et al.,2001, JPO.
+      !!----------------------------------------------------------------------
+      INTEGER , INTENT(in   ) ::   kt     ! ocean time-step index
+      REAL(wp), INTENT(in   ) ::   p2dt   ! time step  [s]
+      !
+      INTEGER :: ji, jj, jk, jl, ik, it, itmod
+      LOGICAL :: lldebug = .TRUE.
+      REAL(wp) :: zavt, zfn, zfn2
+      !                                              ! z(ts)mltot : dT/dt over the anlysis window (including Asselin)
+      !                                              ! z(ts)mlres : residual = dh/dt entrainment term
+      REAL(wp), POINTER, DIMENSION(:,:  ) ::  ztmltot , zsmltot , ztmlres , zsmlres , ztmlatf , zsmlatf
+      REAL(wp), POINTER, DIMENSION(:,:  ) ::  ztmltot2, zsmltot2, ztmlres2, zsmlres2, ztmlatf2, zsmlatf2, ztmltrdm2, zsmltrdm2  
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::  ztmltrd2, zsmltrd2   ! only needed for mean diagnostics
+#if defined key_dimgout
+      INTEGER ::  iyear,imon,iday
+      CHARACTER(LEN=80) :: cltext, clmode
+#endif
+      !!----------------------------------------------------------------------
+  
+      CALL wrk_alloc( jpi, jpj,         ztmltot , zsmltot , ztmlres , zsmlres , ztmlatf , zsmlatf                        )
+      CALL wrk_alloc( jpi, jpj,         ztmltot2, zsmltot2, ztmlres2, zsmlres2, ztmlatf2, zsmlatf2, ztmltrdm2, zsmltrdm2 )  
+      CALL wrk_alloc( jpi, jpj, jpltrd, ztmltrd2, zsmltrd2                                                               )
+
+      ! ======================================================================
+      ! II. Cumulate the trends over the analysis window
+      ! ======================================================================
+
+      ztmltrd2(:,:,:) = 0.e0   ;    zsmltrd2(:,:,:) = 0.e0  ! <<< reset arrays to zero
+      ztmltot2(:,:)   = 0.e0   ;    zsmltot2(:,:)   = 0.e0
+      ztmlres2(:,:)   = 0.e0   ;    zsmlres2(:,:)   = 0.e0
+      ztmlatf2(:,:)   = 0.e0   ;    zsmlatf2(:,:)   = 0.e0
+
+      ! II.1 Set before values of vertically average T and S 
+      ! ----------------------------------------------------
+      IF( kt > nit000 ) THEN
+         !   ... temperature ...                    ... salinity ...
+         tmlb   (:,:) = tml   (:,:)             ;   smlb   (:,:) = sml   (:,:)
+         tmlatfn(:,:) = tmltrd(:,:,jpmxl_atf)   ;   smlatfn(:,:) = smltrd(:,:,jpmxl_atf)
+      END IF
+
+
+      ! II.3 Initialize mixed-layer "before" arrays for the 1rst analysis window    
+      ! ------------------------------------------------------------------------
+      IF( kt == 2 ) THEN  !  i.e. ( .NOT. ln_rstart ).AND.( kt == nit000 + 1)
+         !
+         !   ... temperature ...                ... salinity ...
+         tmlbb  (:,:) = tmlb   (:,:)   ;   smlbb  (:,:) = smlb   (:,:)
+         tmlbn  (:,:) = tml    (:,:)   ;   smlbn  (:,:) = sml    (:,:)
+         tmlatfb(:,:) = tmlatfn(:,:)   ;   smlatfb(:,:) = smlatfn(:,:)
+         
+         tmltrd_csum_ub (:,:,:) = 0.e0  ;   smltrd_csum_ub (:,:,:) = 0.e0
+         tmltrd_atf_sumb(:,:)   = 0.e0  ;   smltrd_atf_sumb(:,:)   = 0.e0
+
+         hmxlbn(:,:) = hmxl(:,:)
+
+         IF( ln_ctl ) THEN
+            WRITE(numout,*) '             we reach kt == nit000 + 1 = ', nit000+1
+            CALL prt_ctl(tab2d_1=tmlbb   , clinfo1=' tmlbb   -   : ', mask1=tmask, ovlap=1)
+            CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask, ovlap=1)
+            CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask, ovlap=1)
+         END IF
+         !
+      END IF
+
+      IF( ( ln_rstart ) .AND. ( kt == nit000 ) .AND. ( ln_ctl ) ) THEN
+         IF( ln_trdmxl_instant ) THEN
+            WRITE(numout,*) '             restart from kt == nit000 = ', nit000
+            CALL prt_ctl(tab2d_1=tmlbb   , clinfo1=' tmlbb   -   : ', mask1=tmask, ovlap=1)
+            CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask, ovlap=1)
+            CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask, ovlap=1)
+         ELSE
+            WRITE(numout,*) '             restart from kt == nit000 = ', nit000
+            CALL prt_ctl(tab2d_1=tmlbn          , clinfo1=' tmlbn           -  : ', mask1=tmask, ovlap=1)
+            CALL prt_ctl(tab2d_1=hmxlbn         , clinfo1=' hmxlbn          -  : ', mask1=tmask, ovlap=1)
+            CALL prt_ctl(tab2d_1=tml_sumb       , clinfo1=' tml_sumb        -  : ', mask1=tmask, ovlap=1)
+            CALL prt_ctl(tab2d_1=tmltrd_atf_sumb, clinfo1=' tmltrd_atf_sumb -  : ', mask1=tmask, ovlap=1)
+            CALL prt_ctl(tab3d_1=tmltrd_csum_ub , clinfo1=' tmltrd_csum_ub  -  : ', mask1=tmask, ovlap=1, kdim=1)
+         END IF
+      END IF
+
+      ! II.4 Cumulated trends over the analysis period
+      ! ----------------------------------------------
+      !
+      !         [  1rst analysis window ] [     2nd analysis window     ]                       
+      !
+      !     o---[--o-----o-----o-----o--]-[--o-----o-----o-----o-----o--]---o-----o--> time steps
+      !                          nn_trd                           2*nn_trd       etc.
+      !     1      2     3     4    =5 e.g.                          =10
+      !
+      IF( ( kt >= 2 ).OR.( ln_rstart ) ) THEN
+         !
+         nmoymltrd = nmoymltrd + 1
+         
+         ! ... Cumulate over BOTH physical contributions AND over time steps
+         DO jl = 1, jpltrd
+            tmltrdm(:,:) = tmltrdm(:,:) + tmltrd(:,:,jl)
+            smltrdm(:,:) = smltrdm(:,:) + smltrd(:,:,jl)
+         END DO
+
+         ! ... Special handling of the Asselin trend 
+         tmlatfm(:,:) = tmlatfm(:,:) + tmlatfn(:,:)
+         smlatfm(:,:) = smlatfm(:,:) + smlatfn(:,:)
+
+         ! ... Trends associated with the time mean of the ML T/S
+         tmltrd_sum    (:,:,:) = tmltrd_sum    (:,:,:) + tmltrd    (:,:,:) ! tem
+         tmltrd_csum_ln(:,:,:) = tmltrd_csum_ln(:,:,:) + tmltrd_sum(:,:,:)
+         tml_sum       (:,:)   = tml_sum       (:,:)   + tml       (:,:)
+         smltrd_sum    (:,:,:) = smltrd_sum    (:,:,:) + smltrd    (:,:,:) ! sal
+         smltrd_csum_ln(:,:,:) = smltrd_csum_ln(:,:,:) + smltrd_sum(:,:,:)
+         sml_sum       (:,:)   = sml_sum       (:,:)   + sml       (:,:)
+         hmxl_sum      (:,:)   = hmxl_sum      (:,:)   + hmxl      (:,:)   ! rmxl
+         !
+      END IF
+
+      ! ======================================================================
+      ! III. Prepare fields for output (get here ONCE PER ANALYSIS PERIOD)
+      ! ======================================================================
+
+      ! Convert to appropriate physical units
+      ! N.B. It may be useful to check IOIPSL time averaging with :
+      !      tmltrd (:,:,:) = 1. ; smltrd (:,:,:) = 1.
+      tmltrd(:,:,:) = tmltrd(:,:,:) * rn_ucf   ! (actually needed for 1:jpltrd-1, but trdmxl(:,:,jpltrd)
+      smltrd(:,:,:) = smltrd(:,:,:) * rn_ucf   !  is no longer used, and is reset to 0. at next time step)
+      
+      ! define time axis
+      it = kt
+      itmod = kt - nit000 + 1
+
+      MODULO_NTRD : IF( MOD( itmod, nn_trd ) == 0 ) THEN        ! nitend MUST be multiple of nn_trd
+         !
+         ztmltot (:,:) = 0.e0   ;   zsmltot (:,:) = 0.e0   ! reset arrays to zero
+         ztmlres (:,:) = 0.e0   ;   zsmlres (:,:) = 0.e0
+         ztmltot2(:,:) = 0.e0   ;   zsmltot2(:,:) = 0.e0
+         ztmlres2(:,:) = 0.e0   ;   zsmlres2(:,:) = 0.e0
+      
+         zfn  = REAL( nmoymltrd, wp )   ;   zfn2 = zfn * zfn
+         
+         ! III.1 Prepare fields for output ("instantaneous" diagnostics) 
+         ! -------------------------------------------------------------
+         
+         !-- Compute total trends
+         ztmltot(:,:) = ( tml(:,:) - tmlbn(:,:) + tmlb(:,:) - tmlbb(:,:) ) / p2dt
+         zsmltot(:,:) = ( sml(:,:) - smlbn(:,:) + smlb(:,:) - smlbb(:,:) ) / p2dt
+         
+         !-- Compute residuals
+         ztmlres(:,:) = ztmltot(:,:) - ( tmltrdm(:,:) - tmlatfn(:,:) + tmlatfb(:,:) )
+         zsmlres(:,:) = zsmltot(:,:) - ( smltrdm(:,:) - smlatfn(:,:) + smlatfb(:,:) )
+      
+         !-- Diagnose Asselin trend over the analysis window 
+         ztmlatf(:,:) = tmlatfm(:,:) - tmlatfn(:,:) + tmlatfb(:,:)
+         zsmlatf(:,:) = smlatfm(:,:) - smlatfn(:,:) + smlatfb(:,:)
+         
+         !-- Lateral boundary conditions
+         !         ... temperature ...                    ... salinity ...
+         CALL lbc_lnk( ztmltot , 'T', 1. )  ;   CALL lbc_lnk( zsmltot , 'T', 1. )
+         CALL lbc_lnk( ztmlres , 'T', 1. )  ;   CALL lbc_lnk( zsmlres , 'T', 1. )
+         CALL lbc_lnk( ztmlatf , 'T', 1. )  ;   CALL lbc_lnk( zsmlatf , 'T', 1. )
+
+
+         ! III.2 Prepare fields for output ("mean" diagnostics) 
+         ! ----------------------------------------------------
+         
+         !-- Update the ML depth time sum (to build the Leap-Frog time mean)
+         hmxl_sum(:,:) = hmxlbn(:,:) + 2 * ( hmxl_sum(:,:) - hmxl(:,:) ) + hmxl(:,:)
+
+         !-- Compute temperature total trends
+         tml_sum (:,:) = tmlbn(:,:) + 2 * ( tml_sum(:,:) - tml(:,:) ) + tml(:,:)
+         ztmltot2(:,:) = ( tml_sum(:,:) - tml_sumb(:,:) ) / p2dt    ! now in degC/s
+         
+         !-- Compute salinity total trends
+         sml_sum (:,:) = smlbn(:,:) + 2 * ( sml_sum(:,:) - sml(:,:) ) + sml(:,:)
+         zsmltot2(:,:) = ( sml_sum(:,:) - sml_sumb(:,:) ) / p2dt    ! now in psu/s
+         
+         !-- Compute temperature residuals
+         DO jl = 1, jpltrd
+            ztmltrd2(:,:,jl) = tmltrd_csum_ub(:,:,jl) + tmltrd_csum_ln(:,:,jl)
+         END DO
+
+         ztmltrdm2(:,:) = 0.e0
+         DO jl = 1, jpltrd
+            ztmltrdm2(:,:) = ztmltrdm2(:,:) + ztmltrd2(:,:,jl)
+         END DO
+
+         ztmlres2(:,:) =  ztmltot2(:,:)  -       &
+              ( ztmltrdm2(:,:) - tmltrd_sum(:,:,jpmxl_atf) + tmltrd_atf_sumb(:,:) )
+         
+         !-- Compute salinity residuals
+         DO jl = 1, jpltrd
+            zsmltrd2(:,:,jl) = smltrd_csum_ub(:,:,jl) + smltrd_csum_ln(:,:,jl)
+         END DO
+
+         zsmltrdm2(:,:) = 0.
+         DO jl = 1, jpltrd
+            zsmltrdm2(:,:) = zsmltrdm2(:,:) + zsmltrd2(:,:,jl)
+         END DO
+
+         zsmlres2(:,:) =  zsmltot2(:,:)  -       &
+              ( zsmltrdm2(:,:) - smltrd_sum(:,:,jpmxl_atf) + smltrd_atf_sumb(:,:) )
+         
+         !-- Diagnose Asselin trend over the analysis window
+         ztmlatf2(:,:) = ztmltrd2(:,:,jpmxl_atf) - tmltrd_sum(:,:,jpmxl_atf) + tmltrd_atf_sumb(:,:)
+         zsmlatf2(:,:) = zsmltrd2(:,:,jpmxl_atf) - smltrd_sum(:,:,jpmxl_atf) + smltrd_atf_sumb(:,:)
+
+         !-- Lateral boundary conditions
+         !         ... temperature ...                    ... salinity ...
+         CALL lbc_lnk( ztmltot2, 'T', 1. )  ;   CALL lbc_lnk( zsmltot2, 'T', 1. )
+         CALL lbc_lnk( ztmlres2, 'T', 1. )  ;   CALL lbc_lnk( zsmlres2, 'T', 1. )
+         DO jl = 1, jpltrd
+            CALL lbc_lnk( ztmltrd2(:,:,jl), 'T', 1. ) ! \  these will be output
+            CALL lbc_lnk( zsmltrd2(:,:,jl), 'T', 1. ) ! /  in the NetCDF trends file
+         END DO
+         
+         ! III.3 Time evolution array swap
+         ! -------------------------------
+         
+         ! For T/S instantaneous diagnostics 
+         !   ... temperature ...               ... salinity ...
+         tmlbb  (:,:) = tmlb   (:,:)  ;   smlbb  (:,:) = smlb   (:,:)
+         tmlbn  (:,:) = tml    (:,:)  ;   smlbn  (:,:) = sml    (:,:)
+         tmlatfb(:,:) = tmlatfn(:,:)  ;   smlatfb(:,:) = smlatfn(:,:)
+
+         ! For T mean diagnostics 
+         tmltrd_csum_ub (:,:,:) = zfn * tmltrd_sum(:,:,:) - tmltrd_csum_ln(:,:,:)
+         tml_sumb       (:,:)   = tml_sum(:,:)
+         tmltrd_atf_sumb(:,:)   = tmltrd_sum(:,:,jpmxl_atf)
+         
+         ! For S mean diagnostics 
+         smltrd_csum_ub (:,:,:) = zfn * smltrd_sum(:,:,:) - smltrd_csum_ln(:,:,:)
+         sml_sumb       (:,:)   = sml_sum(:,:)
+         smltrd_atf_sumb(:,:)   = smltrd_sum(:,:,jpmxl_atf)
+         
+         ! ML depth
+         hmxlbn         (:,:)   = hmxl    (:,:)
+         
+         IF( ln_ctl ) THEN
+            IF( ln_trdmxl_instant ) THEN
+               CALL prt_ctl(tab2d_1=tmlbb   , clinfo1=' tmlbb   -   : ', mask1=tmask, ovlap=1)
+               CALL prt_ctl(tab2d_1=tmlbn   , clinfo1=' tmlbn   -   : ', mask1=tmask, ovlap=1)
+               CALL prt_ctl(tab2d_1=tmlatfb , clinfo1=' tmlatfb -   : ', mask1=tmask, ovlap=1)
+            ELSE
+               CALL prt_ctl(tab2d_1=tmlbn          , clinfo1=' tmlbn           -  : ', mask1=tmask, ovlap=1)
+               CALL prt_ctl(tab2d_1=hmxlbn         , clinfo1=' hmxlbn          -  : ', mask1=tmask, ovlap=1)
+               CALL prt_ctl(tab2d_1=tml_sumb       , clinfo1=' tml_sumb        -  : ', mask1=tmask, ovlap=1)
+               CALL prt_ctl(tab2d_1=tmltrd_atf_sumb, clinfo1=' tmltrd_atf_sumb -  : ', mask1=tmask, ovlap=1)
+               CALL prt_ctl(tab3d_1=tmltrd_csum_ub , clinfo1=' tmltrd_csum_ub  -  : ', mask1=tmask, ovlap=1, kdim=1)
+            END IF
+         END IF
+
+         ! III.4 Convert to appropriate physical units
+         ! -------------------------------------------
+
+         !    ... temperature ...                         ... salinity ...
+         ztmltot (:,:)   = ztmltot(:,:)   * rn_ucf/zfn  ; zsmltot (:,:)   = zsmltot(:,:)   * rn_ucf/zfn
+         ztmlres (:,:)   = ztmlres(:,:)   * rn_ucf/zfn  ; zsmlres (:,:)   = zsmlres(:,:)   * rn_ucf/zfn
+         ztmlatf (:,:)   = ztmlatf(:,:)   * rn_ucf/zfn  ; zsmlatf (:,:)   = zsmlatf(:,:)   * rn_ucf/zfn
+
+         tml_sum (:,:)   = tml_sum (:,:)  /  (2*zfn) ; sml_sum (:,:)   = sml_sum (:,:)  /  (2*zfn)
+         ztmltot2(:,:)   = ztmltot2(:,:)  * rn_ucf/zfn2 ; zsmltot2(:,:)   = zsmltot2(:,:)  * rn_ucf/zfn2
+         ztmltrd2(:,:,:) = ztmltrd2(:,:,:)* rn_ucf/zfn2 ; zsmltrd2(:,:,:) = zsmltrd2(:,:,:)* rn_ucf/zfn2
+         ztmlatf2(:,:)   = ztmlatf2(:,:)  * rn_ucf/zfn2 ; zsmlatf2(:,:)   = zsmlatf2(:,:)  * rn_ucf/zfn2
+         ztmlres2(:,:)   = ztmlres2(:,:)  * rn_ucf/zfn2 ; zsmlres2(:,:)   = zsmlres2(:,:)  * rn_ucf/zfn2
+
+         hmxl_sum(:,:)   = hmxl_sum(:,:)  /  (2*zfn)  ! similar to tml_sum and sml_sum
+
+         ! * Debugging information *
+         IF( lldebug ) THEN
+            !
+            WRITE(numout,*)
+            WRITE(numout,*) 'trd_mxl : write trends in the Mixed Layer for debugging process:'
+            WRITE(numout,*) '~~~~~~~  '
+            WRITE(numout,*) '          TRA kt = ', kt, 'nmoymltrd = ', nmoymltrd
+            WRITE(numout,*)
+            WRITE(numout,*) '          >>>>>>>>>>>>>>>>>>  TRA TEMPERATURE <<<<<<<<<<<<<<<<<<'
+            WRITE(numout,*) '          TRA ztmlres    : ', SUM(ztmlres(:,:))
+            WRITE(numout,*) '          TRA ztmltot    : ', SUM(ztmltot(:,:))
+            WRITE(numout,*) '          TRA tmltrdm    : ', SUM(tmltrdm(:,:))
+            WRITE(numout,*) '          TRA tmlatfb    : ', SUM(tmlatfb(:,:))
+            WRITE(numout,*) '          TRA tmlatfn    : ', SUM(tmlatfn(:,:))
+            DO jl = 1, jpltrd
+               WRITE(numout,*) '          * TRA TREND INDEX jpmxl_xxx = jl = ', jl, &
+                    & ' tmltrd : ', SUM(tmltrd(:,:,jl))
+            END DO
+            WRITE(numout,*) '          TRA ztmlres (jpi/2,jpj/2) : ', ztmlres (jpi/2,jpj/2)
+            WRITE(numout,*) '          TRA ztmlres2(jpi/2,jpj/2) : ', ztmlres2(jpi/2,jpj/2)
+            WRITE(numout,*)
+            WRITE(numout,*) '          >>>>>>>>>>>>>>>>>>  TRA SALINITY <<<<<<<<<<<<<<<<<<'
+            WRITE(numout,*) '          TRA zsmlres    : ', SUM(zsmlres(:,:))
+            WRITE(numout,*) '          TRA zsmltot    : ', SUM(zsmltot(:,:))
+            WRITE(numout,*) '          TRA smltrdm    : ', SUM(smltrdm(:,:))
+            WRITE(numout,*) '          TRA smlatfb    : ', SUM(smlatfb(:,:))
+            WRITE(numout,*) '          TRA smlatfn    : ', SUM(smlatfn(:,:))
+            DO jl = 1, jpltrd
+               WRITE(numout,*) '          * TRA TREND INDEX jpmxl_xxx = jl = ', jl, &
+                    & ' smltrd : ', SUM(smltrd(:,:,jl))
+            END DO
+            WRITE(numout,*) '          TRA zsmlres (jpi/2,jpj/2) : ', zsmlres (jpi/2,jpj/2)
+            WRITE(numout,*) '          TRA zsmlres2(jpi/2,jpj/2) : ', zsmlres2(jpi/2,jpj/2)
+            !
+         END IF
+         !
+      END IF MODULO_NTRD
+
+      ! ======================================================================
+      ! IV. Write trends in the NetCDF file
+      ! ======================================================================
+
+      !-- Write the trends for T/S instantaneous diagnostics 
+      
+      IF( ln_trdmxl_instant ) THEN           
+
+         CALL iom_put( "mxl_depth", hmxl(:,:) )
+         
+         !................................. ( ML temperature ) ...................................
+         
+         !-- Output the fields
+         CALL iom_put( "tml"     , tml    (:,:) ) 
+         CALL iom_put( "tml_tot" , ztmltot(:,:) ) 
+         CALL iom_put( "tml_res" , ztmlres(:,:) ) 
+         
+         DO jl = 1, jpltrd - 1
+            CALL iom_put( trim("tml"//ctrd(jl,2)), tmltrd (:,:,jl) )
+         END DO
+         
+         CALL iom_put( trim("tml"//ctrd(jpmxl_atf,2)), ztmlatf(:,:) )
+         
+         !.................................. ( ML salinity ) .....................................
+         
+         !-- Output the fields
+         CALL iom_put( "sml"    , sml    (:,:) )
+         CALL iom_put( "sml_tot", zsmltot(:,:) ) 
+         CALL iom_put( "sml_res", zsmlres(:,:) ) 
+         
+         DO jl = 1, jpltrd - 1
+            CALL iom_put( trim("sml"//ctrd(jl,2)), smltrd(:,:,jl) )
+         END DO
+         
+         CALL iom_put( trim("sml"//ctrd(jpmxl_atf,2)), zsmlatf(:,:) )
+
+
+         
+      ELSE      !-- Write the trends for T/S mean diagnostics 
+
+         CALL iom_put( "mxl_depth", hmxl_sum(:,:) )
+         
+         !................................. ( ML temperature ) ...................................
+         
+         !-- Output the fields
+         CALL iom_put( "tml"     , tml_sum (:,:) ) 
+         CALL iom_put( "tml_tot" , ztmltot2(:,:) ) 
+         CALL iom_put( "tml_res" , ztmlres2(:,:) ) 
+
+         DO jl = 1, jpltrd - 1
+            CALL iom_put( trim("tml"//ctrd(jl,2)), ztmltrd2(:,:,jl) )
+         END DO
+         
+         CALL iom_put( trim("tml"//ctrd(jpmxl_atf,2)), ztmlatf2(:,:) )
+         
+         !.................................. ( ML salinity ) .....................................
+                     
+         !-- Output the fields
+         CALL iom_put( "sml"    , sml_sum (:,:) )
+         CALL iom_put( "sml_tot", zsmltot2(:,:) ) 
+         CALL iom_put( "sml_res", zsmlres2(:,:) ) 
+
+         DO jl = 1, jpltrd - 1
+            CALL iom_put( trim("sml"//ctrd(jl,2)), zsmltrd2(:,:,jl) )
+         END DO
+         
+         CALL iom_put( trim("sml"//ctrd(jpmxl_atf,2)), zsmlatf2(:,:) )
+         !
+      END IF
+      !
+
+      IF( MOD( itmod, nn_trd ) == 0 ) THEN
+         !
+         ! III.5 Reset cumulative arrays to zero
+         ! -------------------------------------
+         nmoymltrd = 0
+         
+         !   ... temperature ...               ... salinity ...
+         tmltrdm        (:,:)   = 0.e0   ;   smltrdm        (:,:)   = 0.e0
+         tmlatfm        (:,:)   = 0.e0   ;   smlatfm        (:,:)   = 0.e0
+         tml_sum        (:,:)   = 0.e0   ;   sml_sum        (:,:)   = 0.e0
+         tmltrd_csum_ln (:,:,:) = 0.e0   ;   smltrd_csum_ln (:,:,:) = 0.e0
+         tmltrd_sum     (:,:,:) = 0.e0   ;   smltrd_sum     (:,:,:) = 0.e0
+
+         hmxl_sum       (:,:)   = 0.e0
+         !
+      END IF
+
+      ! ======================================================================
+      ! V. Write restart file
+      ! ======================================================================
+
+      IF( lrst_oce )   CALL trd_mxl_rst_write( kt ) 
+
+      CALL wrk_dealloc( jpi, jpj,         ztmltot , zsmltot , ztmlres , zsmlres , ztmlatf , zsmlatf                        )
+      CALL wrk_dealloc( jpi, jpj,         ztmltot2, zsmltot2, ztmlres2, zsmlres2, ztmlatf2, zsmlatf2, ztmltrdm2, zsmltrdm2 )  
+      CALL wrk_dealloc( jpi, jpj, jpltrd, ztmltrd2, zsmltrd2                                                               )
+      !
+   END SUBROUTINE trd_mxl
+
+
+   SUBROUTINE trd_mxl_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_init  ***
+      !! 
+      !! ** Purpose :   computation of vertically integrated T and S budgets
+      !!      from ocean surface down to control surface (NetCDF output)
+      !!----------------------------------------------------------------------
+      INTEGER  ::   jl     ! dummy loop indices
+      INTEGER  ::   inum   ! logical unit
+      INTEGER  ::   ios    ! local integer
+      REAL(wp) ::   zjulian, zsto, zout
+      CHARACTER (LEN=40) ::   clop
+      CHARACTER (LEN=12) ::   clmxl, cltu, clsu
+      !!
+      NAMELIST/namtrd_mxl/ nn_trd , cn_trdrst_in , ln_trdmxl_restart,       &
+         &                 nn_ctls, cn_trdrst_out, ln_trdmxl_instant, rn_ucf, rn_rho_c
+      !!----------------------------------------------------------------------
+      !
+      REWIND( numnam_ref )              ! Namelist namtrd_mxl in reference namelist : mixed layer trends diagnostic
+      READ  ( numnam_ref, namtrd_mxl, IOSTAT = ios, ERR = 901 )
+901   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namtrd_mxl in reference namelist', lwp )
+
+      REWIND( numnam_cfg )              ! Namelist namtrd_mxl in configuration namelist : mixed layer trends diagnostic
+      READ  ( numnam_cfg, namtrd_mxl, IOSTAT = ios, ERR = 902 )
+902   IF( ios /= 0 ) CALL ctl_nam ( ios , 'namtrd_mxl in configuration namelist', lwp )
+      IF(lwm) WRITE( numond, namtrd_mxl )
+      !
+      IF(lwp) THEN                      ! control print
+         WRITE(numout,*)
+         WRITE(numout,*) ' trd_mxl_init : Mixed-layer trends'
+         WRITE(numout,*) ' ~~~~~~~~~~'
+         WRITE(numout,*) '   Namelist namtrd : set trends parameters'
+         WRITE(numout,*) '      frequency of trends diagnostics (glo)      nn_trd             = ', nn_trd
+         WRITE(numout,*) '      density criteria used to defined the MLD   rn_rho_c           = ', rn_rho_c
+         WRITE(numout,*) '      control surface type            (mld)      nn_ctls            = ', nn_ctls
+         WRITE(numout,*) '      restart for ML diagnostics                 ln_trdmxl_restart  = ', ln_trdmxl_restart
+         WRITE(numout,*) '      instantaneous or mean ML T/S               ln_trdmxl_instant  = ', ln_trdmxl_instant
+         WRITE(numout,*) '      unit conversion factor                     rn_ucf             = ', rn_ucf
+         WRITE(numout,*) '      criteria to compute the MLD                rn_rho_c           = ', rn_rho_c
+      ENDIF
+
+
+
+      ! I.1 Check consistency of user defined preferences
+      ! -------------------------------------------------
+      
+      IF ( rn_rho_c /= rho_c )   CALL ctl_warn( 'Unless you have good reason to do so, you should use the value ',    &
+         &                                      'defined in zdfmxl.F90 module to calculate the mixed layer depth' )
+
+      IF( MOD( nitend, nn_trd ) /= 0 ) THEN
+         WRITE(numout,cform_err)
+         WRITE(numout,*) '                Your nitend parameter, nitend = ', nitend
+         WRITE(numout,*) '                is no multiple of the trends diagnostics frequency        '
+         WRITE(numout,*) '                          you defined, nn_trd   = ', nn_trd
+         WRITE(numout,*) '                This will not allow you to restart from this simulation.  '
+         WRITE(numout,*) '                You should reconsider this choice.                        ' 
+         WRITE(numout,*) 
+         WRITE(numout,*) '                N.B. the nitend parameter is also constrained to be a     '
+         WRITE(numout,*) '                     multiple of the nn_fsbc parameter '
+         nstop = nstop + 1
+      END IF
+
+      IF( nn_cla == 1 )   CALL ctl_warn( '      You set n_cla = 1. Note that the Mixed-Layer diagnostics  ',   &
+         &                               '      are not exact along the corresponding straits.            ')
+
+      !                                   ! allocate trdmxl arrays
+      IF( trd_mxl_alloc()    /= 0 )   CALL ctl_stop( 'STOP', 'trd_mxl_init : unable to allocate trdmxl     arrays' )
+      IF( trdmxl_oce_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trd_mxl_init : unable to allocate trdmxl_oce arrays' )
+
+
+
+
+   	nkstp     = nit000 - 1              ! current time step indicator initialization
+
+
+
+
+      ! I.2 Initialize arrays to zero or read a restart file
+      ! ----------------------------------------------------
+
+      nmoymltrd = 0
+
+      !     ... temperature ...                  ... salinity ...
+      tml            (:,:)   = 0.e0    ;    sml            (:,:)   = 0.e0     ! inst.
+      tmltrdm        (:,:)   = 0.e0    ;    smltrdm        (:,:)   = 0.e0
+      tmlatfm        (:,:)   = 0.e0    ;    smlatfm        (:,:)   = 0.e0
+      tml_sum        (:,:)   = 0.e0    ;    sml_sum        (:,:)   = 0.e0     ! mean
+      tmltrd_sum     (:,:,:) = 0.e0    ;    smltrd_sum     (:,:,:) = 0.e0
+      tmltrd_csum_ln (:,:,:) = 0.e0    ;    smltrd_csum_ln (:,:,:) = 0.e0
+
+      hmxl           (:,:)   = 0.e0            
+      hmxl_sum       (:,:)   = 0.e0
+
+      IF( ln_rstart .AND. ln_trdmxl_restart ) THEN
+         CALL trd_mxl_rst_read
+      ELSE
+         !     ... temperature ...                  ... salinity ...
+         tmlb           (:,:)   = 0.e0    ;    smlb           (:,:)   = 0.e0  ! inst.
+         tmlbb          (:,:)   = 0.e0    ;    smlbb          (:,:)   = 0.e0  
+         tmlbn          (:,:)   = 0.e0    ;    smlbn          (:,:)   = 0.e0  
+         tml_sumb       (:,:)   = 0.e0    ;    sml_sumb       (:,:)   = 0.e0  ! mean
+         tmltrd_csum_ub (:,:,:) = 0.e0    ;    smltrd_csum_ub (:,:,:) = 0.e0
+         tmltrd_atf_sumb(:,:)   = 0.e0    ;    smltrd_atf_sumb(:,:)   = 0.e0  
+      END IF
+
+      icount = 1   ;   ionce  = 1                            ! open specifier
+
+      ! I.3 Read control surface from file ctlsurf_idx
+      ! ----------------------------------------------
+ 
+      IF( nn_ctls == 1 ) THEN
+         CALL ctl_opn( inum, 'ctlsurf_idx', 'OLD', 'UNFORMATTED', 'SEQUENTIAL', -1, numout, lwp )
+         READ ( inum ) nbol
+         CLOSE( inum )
+      END IF
+
+      ! ======================================================================
+      ! II. netCDF output initialization
+      ! ======================================================================
+
+      ! clmxl = legend root for netCDF output
+      IF( nn_ctls == 0 ) THEN      ! control surface = mixed-layer with density criterion
+         clmxl = 'Mixed Layer '  !                   (array nmln computed in zdfmxl.F90)
+      ELSE IF( nn_ctls == 1 ) THEN ! control surface = read index from file 
+         clmxl = '      Bowl '
+      ELSE IF( nn_ctls >= 2 ) THEN ! control surface = model level
+         WRITE(clmxl,'(A10,I2,1X)') 'Levels 1 -', nn_ctls
+      END IF
+
+
+
+      ! II.3 Define the T grid trend file (nidtrd)
+      ! ------------------------------------------
+      !-- Define long and short names for the NetCDF output variables
+      !       ==> choose them according to trdmxl_oce.F90 <==
+
+      ctrd(jpmxl_xad,1) = " Zonal advection"                  ;   ctrd(jpmxl_xad,2) = "_xad"
+      ctrd(jpmxl_yad,1) = " Meridional advection"             ;   ctrd(jpmxl_yad,2) = "_yad"
+      ctrd(jpmxl_zad,1) = " Vertical advection"               ;   ctrd(jpmxl_zad,2) = "_zad"
+      ctrd(jpmxl_ldf,1) = " Lateral diffusion"                ;   ctrd(jpmxl_ldf,2) = "_ldf"
+      ctrd(jpmxl_for,1) = " Forcing"                          ;   ctrd(jpmxl_for,2) = "_for"
+      ctrd(jpmxl_zdf,1) = " Vertical diff. (Kz)"              ;   ctrd(jpmxl_zdf,2) = "_zdf"
+      ctrd(jpmxl_bbc,1) = " Geothermal flux"                  ;   ctrd(jpmxl_bbc,2) = "_bbc"
+      ctrd(jpmxl_bbl,1) = " Adv/diff. Bottom boundary layer"  ;   ctrd(jpmxl_bbl,2) = "_bbl"
+      ctrd(jpmxl_dmp,1) = " Tracer damping"                   ;   ctrd(jpmxl_dmp,2) = "_dmp"
+      ctrd(jpmxl_npc,1) = " Non penetrative convec. adjust."  ;   ctrd(jpmxl_npc,2) = "_npc"
+      ctrd(jpmxl_atf,1) = " Asselin time filter"              ;   ctrd(jpmxl_atf,2) = "_atf"
+                                                                  
+
+      !-- Define physical units
+      IF     ( rn_ucf == 1.       ) THEN   ;   cltu = "degC/s"     ;   clsu = "p.s.u./s"
+      ELSEIF ( rn_ucf == 3600.*24.) THEN   ;   cltu = "degC/day"   ;   clsu = "p.s.u./day"
+      ELSE                                 ;   cltu = "unknown?"   ;   clsu = "unknown?"
+      END IF
+      !
+   END SUBROUTINE trd_mxl_init
+
+   !!======================================================================
+END MODULE trdmxl
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_oce.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_oce.F90	(revision 5075)
@@ -0,0 +1,135 @@
+MODULE trdmxl_oce
+   !!======================================================================
+   !!                   ***  MODULE trdmxl_oce  ***
+   !! Ocean trends :   set tracer and momentum trend variables
+   !!======================================================================
+   !! History :  1.0  ! 2004-08  (C. Talandier)  New trends organization
+   !!            3.5  ! 2012-02  (G. Madec) suppress the trend keys + new trdmxl formulation
+   !!----------------------------------------------------------------------
+   USE par_oce        ! ocean parameters
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trdmxl_oce_alloc    ! Called in trdmxl.F90
+
+   !                                                !* mixed layer trend indices
+   INTEGER, PUBLIC, PARAMETER ::   jpltrd = 11      !: number of mixed-layer trends arrays
+   INTEGER, PUBLIC            ::   jpktrd           !: max level for mixed-layer trends diag.
+   !
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_xad =  1   !: i-componant of advection   
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_yad =  2   !: j-componant of advection
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_zad =  3   !: k-component of advection 
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_ldf =  4   !: lateral diffusion (geopot. or iso-neutral)
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_zdf =  5   !: vertical diffusion  
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_npc =  6   !: non penetrative convective adjustment
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_bbc =  7   !: geothermal flux
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_bbl =  8   !: bottom boundary layer (advective/diffusive)
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_for =  9   !: forcing 
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_dmp = 10   !: internal restoring trend
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_zdfp = 11   !: asselin trend (**MUST BE THE LAST ONE**)
+   INTEGER, PUBLIC, PARAMETER ::   jpmxl_atf  = 12   !: asselin trend (**MUST BE THE LAST ONE**)
+   !                                                            !!* Namelist namtrd_mxl:  trend diagnostics in the mixed layer *
+   INTEGER           , PUBLIC ::   nn_ctls  = 0                  !: control surface type for trends vertical integration
+   REAL(wp)          , PUBLIC ::   rn_rho_c = 0.01               !: density criteria for MLD definition
+   REAL(wp)          , PUBLIC ::   rn_ucf   = 1.                 !: unit conversion factor (for netCDF trends outputs)
+                                                                 !  =1. (=86400.) for degC/s (degC/day) and psu/s (psu/day)
+   CHARACTER(len=32), PUBLIC ::   cn_trdrst_in  = "restart_mxl"  !: suffix of ocean restart name (input)
+   CHARACTER(len=32), PUBLIC ::   cn_trdrst_out = "restart_mxl"  !: suffix of ocean restart name (output)
+   LOGICAL          , PUBLIC ::   ln_trdmxl_instant = .FALSE.    !: flag to diagnose inst./mean ML T/S trends
+   LOGICAL          , PUBLIC ::   ln_trdmxl_restart = .FALSE.    !: flag to restart mixed-layer diagnostics
+
+
+   !! Arrays used for diagnosing mixed-layer trends 
+   !!---------------------------------------------------------------------
+   CHARACTER(LEN=80) , PUBLIC :: clname, ctrd(jpltrd+1,2)
+
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nmxl   !: mixed layer depth indexes 
+   INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   nbol   !: mixed-layer depth indexes when read from file
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   wkx    !:
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::  &
+      hmxl   ,                      & !: mixed layer depth (m) corresponding to nmld
+      tml    , sml  ,               & !: \ "now" mixed layer temperature/salinity
+      tmlb   , smlb ,               & !: /  and associated "before" fields
+      tmlbb  , smlbb,               & !: \  idem, but valid at the 1rst time step of the
+      tmlbn  , smlbn,               & !: /  current analysis window
+      tmltrdm, smltrdm,             & !: total cumulative trends over the analysis window
+      tml_sum,                      & !: mixed layer T, summed over the current analysis period
+      tml_sumb,                     & !: idem, but from the previous analysis period
+      tmltrd_atf_sumb,              & !: Asselin trends, summed over the previous analysis period
+      sml_sum,                      & !: 
+      sml_sumb,                     & !:    ( idem for salinity )
+      smltrd_atf_sumb,              & !: 
+      hmxl_sum, hmxlbn                !: needed to compute the leap-frog time mean of the ML depth
+
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::  &
+      tmlatfb, tmlatfn ,            & !: "before" Asselin contribution at begining of the averaging
+      smlatfb, smlatfn,             & !: period (i.e. last contrib. from previous such period) and 
+                                      !: "now" Asselin contribution to the ML temp. & salinity trends
+      tmlatfm, smlatfm                !: accumulator for Asselin trends (needed for storage only)
+
+   REAL(wp), PUBLIC, ALLOCATABLE, DIMENSION(:,:,:) ::  &
+      tmltrd,                       & !: \ physical contributions to the total trend (for T/S),
+      smltrd,                       & !: / cumulated over the current analysis window
+      tmltrd_sum,                   & !: sum of these trends over the analysis period
+      tmltrd_csum_ln,               & !: now cumulated sum of the trends over the "lower triangle"
+      tmltrd_csum_ub,               & !: before (prev. analysis period) cumulated sum over the upper triangle
+      smltrd_sum,                   & !: 
+      smltrd_csum_ln,               & !:    ( idem for salinity )
+      smltrd_csum_ub                  !: 
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 4.0 , NEMO Consortium (2011)
+   !! $Id: $ 
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+  INTEGER FUNCTION trdmxl_oce_alloc()
+     !!----------------------------------------------------------------------
+     !!                 ***  FUNCTION trdmxl_oce_alloc   ***
+     !!----------------------------------------------------------------------
+     USE lib_mpp
+     INTEGER :: ierr(5)
+     !!----------------------------------------------------------------------
+
+     ! Initialise jpktrd here as can no longer do it in MODULE body since
+     ! jpk is now a variable.
+     jpktrd = jpk   !: max level for mixed-layer trends diag.
+
+     ierr(:) = 0
+
+     ALLOCATE( nmxl (jpi,jpj)    , nbol (jpi,jpj),    &
+        &      wkx  (jpi,jpj,jpk), hmxl (jpi,jpj),    & 
+        &      tml  (jpi,jpj)    , sml  (jpi,jpj),    & 
+        &      tmlb (jpi,jpj)    , smlb (jpi,jpj),    &
+        &      tmlbb(jpi,jpj)    , smlbb(jpi,jpj), STAT = ierr(1) )
+
+     ALLOCATE( tmlbn(jpi,jpj)  , smlbn(jpi,jpj),   &
+        &      tmltrdm(jpi,jpj), smltrdm(jpi,jpj), &
+        &      tml_sum(jpi,jpj), tml_sumb(jpi,jpj),&
+        &      tmltrd_atf_sumb(jpi,jpj)           , STAT=ierr(2) )
+
+     ALLOCATE( sml_sum(jpi,jpj), sml_sumb(jpi,jpj), &
+        &      smltrd_atf_sumb(jpi,jpj),            &
+        &      hmxl_sum(jpi,jpj), hmxlbn(jpi,jpj),  &
+        &      tmlatfb(jpi,jpj), tmlatfn(jpi,jpj), STAT = ierr(3) )
+
+     ALLOCATE( smlatfb(jpi,jpj), smlatfn(jpi,jpj), & 
+        &      tmlatfm(jpi,jpj), smlatfm(jpi,jpj), &
+        &      tmltrd(jpi,jpj,jpltrd),   smltrd(jpi,jpj,jpltrd), STAT=ierr(4))
+
+     ALLOCATE( tmltrd_sum(jpi,jpj,jpltrd),tmltrd_csum_ln(jpi,jpj,jpltrd),      &
+        &      tmltrd_csum_ub(jpi,jpj,jpltrd), smltrd_sum(jpi,jpj,jpltrd),     &
+        &      smltrd_csum_ln(jpi,jpj,jpltrd), smltrd_csum_ub(jpi,jpj,jpltrd), STAT=ierr(5) )
+      !
+      trdmxl_oce_alloc = MAXVAL( ierr )
+      IF( lk_mpp                )   CALL mpp_sum ( trdmxl_oce_alloc )
+      IF( trdmxl_oce_alloc /= 0 )   CALL ctl_warn('trdmxl_oce_alloc: failed to allocate arrays')
+      !
+   END FUNCTION trdmxl_oce_alloc
+
+   !!======================================================================
+END MODULE trdmxl_oce
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_rst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_rst.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdmxl_rst.F90	(revision 5075)
@@ -0,0 +1,194 @@
+MODULE trdmxl_rst
+   !!=================================================================================
+   !!                       ***  MODULE  trdmxl_rst  ***
+   !! Ocean dynamic :  Input/Output files for restart on mixed-layer diagnostics
+   !!=================================================================================
+   !! History :  1.0  ! 2005-05 (C. Deltel)  Original code
+   !!---------------------------------------------------------------------------------
+
+   !!---------------------------------------------------------------------------------
+   !!  trd_mxl_rst_write : write mixed layer trend restart
+   !!  trd_mxl_rst_read  : read  mixed layer trend restart
+   !!---------------------------------------------------------------------------------
+   USE dom_oce         ! ocean space and time domain
+   USE trd_oce         ! trends: ocean variables
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O module
+   USE restart         ! only for lrst_oce
+
+   IMPLICIT NONE
+   PRIVATE
+  
+   PUBLIC   trd_mxl_rst_read    ! routine called by trd_mxl_init
+   PUBLIC   trd_mxl_rst_write   ! routine called by step.F90
+  
+   INTEGER ::   nummxlw         ! logical unit for mxl restart
+
+   !!---------------------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: $ 
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!---------------------------------------------------------------------------------
+CONTAINS
+  
+   SUBROUTINE trd_mxl_rst_write( kt )
+      !!--------------------------------------------------------------------------------
+      !!                  ***  SUBROUTINE trd_mxl_rst_wri  ***
+      !!                
+      !! ** Purpose :   Write mixed-layer diagnostics restart fields.
+      !!--------------------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt   ! ocean time-step index
+      !
+      CHARACTER (len=35) :: charout
+      INTEGER ::   jk                 ! loop indice
+      CHARACTER(LEN=20)   ::   clkt     ! ocean time-step deine as a character
+      CHARACTER(LEN=50)   ::   clname   ! ice output restart file name
+      !!--------------------------------------------------------------------------------
+
+      ! to get better performances with NetCDF format:
+      ! we open and define the ocean restart_mxl file one time step before writing the data (-> at nitrst - 1)
+      ! except if we write ocean restart_mxl files every time step or if an ocean restart_mxl file was writen at nitend - 1
+      IF( kt == nitrst - 1 .OR. nstock == 1 .OR. ( kt == nitend .AND. MOD( nitend - 1, nstock ) == 0 ) ) THEN
+         ! beware of the format used to write kt (default is i8.8, that should be large enough...)
+         IF( nitrst > 999999999 ) THEN   ;   WRITE(clkt, *       ) nitrst
+         ELSE                            ;   WRITE(clkt, '(i8.8)') nitrst
+         ENDIF
+         ! create the file
+         clname = TRIM(cexper)//"_"//TRIM(ADJUSTL(clkt))//"_"//TRIM(cn_trdrst_out)
+         IF(lwp) THEN
+            WRITE(numout,*)
+            SELECT CASE ( jprstlib )
+            CASE ( jprstdimg )   ;   WRITE(numout,*) '             open ocean restart_mxl binary file: '//clname
+            CASE DEFAULT         ;   WRITE(numout,*) '             open ocean restart_mxl NetCDF file: '//clname
+            END SELECT
+            IF( kt == nitrst - 1 ) THEN   ;   WRITE(numout,*) '             kt = nitrst - 1 = ', kt,' date= ', ndastp
+            ELSE                          ;   WRITE(numout,*) '             kt = '             , kt,' date= ', ndastp
+            ENDIF
+         ENDIF
+
+         CALL iom_open( clname, nummxlw, ldwrt = .TRUE., kiolib = jprstlib )
+      ENDIF
+
+      IF( kt == nitrst .AND. lwp ) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trdmxl_rst: output for ML diags. restart, with trd_mxl_rst_write routine kt =', kt
+         WRITE(numout,*) '~~~~~~~~~~'
+         WRITE(numout,*)
+      ENDIF
+
+      IF( ln_trdmxl_instant ) THEN 
+         !-- Temperature
+         CALL iom_rstput( kt, nitrst, nummxlw, 'tmlbb'           , tmlbb           )
+         CALL iom_rstput( kt, nitrst, nummxlw, 'tmlbn'           , tmlbn           )
+         CALL iom_rstput( kt, nitrst, nummxlw, 'tmlatfb'         , tmlatfb         )
+
+         !-- Salinity
+         CALL iom_rstput( kt, nitrst, nummxlw, 'smlbb'           , smlbb           )
+         CALL iom_rstput( kt, nitrst, nummxlw, 'smlbn'           , smlbn           )
+         CALL iom_rstput( kt, nitrst, nummxlw, 'smlatfb'         , smlatfb         )
+      ELSE
+         CALL iom_rstput( kt, nitrst, nummxlw, 'hmxlbn'          , hmxlbn          )
+
+         !-- Temperature
+         CALL iom_rstput( kt, nitrst, nummxlw, 'tmlbn'           , tmlbn           )
+         CALL iom_rstput( kt, nitrst, nummxlw, 'tml_sumb'        , tml_sumb        )
+         DO jk = 1, jpltrd
+            IF( jk < 10 ) THEN   ;   WRITE(charout,FMT="('tmltrd_csum_ub_', I1)")   jk
+            ELSE                 ;   WRITE(charout,FMT="('tmltrd_csum_ub_', I2)")   jk
+            ENDIF
+            CALL iom_rstput( kt, nitrst, nummxlw, charout,  tmltrd_csum_ub(:,:,jk) )
+         ENDDO
+         CALL iom_rstput( kt, nitrst, nummxlw, 'tmltrd_atf_sumb' , tmltrd_atf_sumb )
+
+         !-- Salinity
+         CALL iom_rstput( kt, nitrst, nummxlw, 'smlbn'           , smlbn           )
+         CALL iom_rstput( kt, nitrst, nummxlw, 'sml_sumb'        , sml_sumb        )
+         DO jk = 1, jpltrd
+            IF( jk < 10 ) THEN   ;   WRITE(charout,FMT="('smltrd_csum_ub_', I1)")   jk
+            ELSE                 ;   WRITE(charout,FMT="('smltrd_csum_ub_', I2)")   jk
+            ENDIF
+            CALL iom_rstput( kt, nitrst, nummxlw, charout , smltrd_csum_ub(:,:,jk) )
+         ENDDO
+         CALL iom_rstput( kt, nitrst, nummxlw, 'smltrd_atf_sumb' , smltrd_atf_sumb )
+      ENDIF
+      !
+      IF( kt == nitrst ) THEN
+         CALL iom_close( nummxlw )     ! close the restart file (only at last time step)
+         lrst_oce = .FALSE.
+      ENDIF
+      ! 
+   END SUBROUTINE trd_mxl_rst_write
+
+
+   SUBROUTINE trd_mxl_rst_read
+      !!----------------------------------------------------------------------------
+      !!                   ***  SUBROUTINE trd_mxl_rst_lec  ***
+      !!                   
+      !! ** Purpose :   Read file for mixed-layer diagnostics restart.
+      !!----------------------------------------------------------------------------
+      INTEGER  ::  inum       ! temporary logical unit
+      !
+      CHARACTER (len=35) :: charout
+      INTEGER ::   jk         ! loop indice
+      INTEGER ::   jlibalt = jprstlib
+      LOGICAL ::   llok
+      !!-----------------------------------------------------------------------------
+
+      IF(lwp)  THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' trd_mxl_rst_read : read the NetCDF mixed layer trend restart file'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~'
+      ENDIF
+      IF ( jprstlib == jprstdimg ) THEN
+         ! eventually read netcdf file (monobloc)  for restarting on different number of processors
+         ! if {cn_trdrst_in}.nc exists, then set jlibalt to jpnf90
+         INQUIRE( FILE = TRIM(cn_trdrst_in)//'.nc', EXIST = llok )
+         IF ( llok ) THEN   ;   jlibalt = jpnf90   
+         ELSE               ;   jlibalt = jprstlib   
+         ENDIF
+      ENDIF
+
+      CALL iom_open( cn_trdrst_in, inum, kiolib = jlibalt ) 
+
+      IF( ln_trdmxl_instant ) THEN 
+         !-- Temperature
+         CALL iom_get( inum, jpdom_autoglo, 'tmlbb'           , tmlbb          )
+         CALL iom_get( inum, jpdom_autoglo, 'tmlbn'           , tmlbn          )
+         CALL iom_get( inum, jpdom_autoglo, 'tmlatfb'         , tmlatfb        )
+         !
+         !-- Salinity
+         CALL iom_get( inum, jpdom_autoglo, 'smlbb'           , smlbb          )
+         CALL iom_get( inum, jpdom_autoglo, 'smlbn'           , smlbn          )
+         CALL iom_get( inum, jpdom_autoglo, 'smlatfb'         , smlatfb        )
+      ELSE
+         CALL iom_get( inum, jpdom_autoglo, 'hmxlbn'          , hmxlbn         ) ! needed for hmxl_sum
+         !
+         !-- Temperature
+         CALL iom_get( inum, jpdom_autoglo, 'tmlbn'           , tmlbn          ) ! needed for tml_sum
+         CALL iom_get( inum, jpdom_autoglo, 'tml_sumb'        , tml_sumb       )
+         DO jk = 1, jpltrd
+            IF( jk < 10 ) THEN   ;   WRITE(charout,FMT="('tmltrd_csum_ub_', I1)")   jk
+            ELSE                 ;   WRITE(charout,FMT="('tmltrd_csum_ub_', I2)")   jk
+            ENDIF
+            CALL iom_get( inum, jpdom_autoglo, charout, tmltrd_csum_ub(:,:,jk) )
+         END DO
+         CALL iom_get( inum, jpdom_autoglo, 'tmltrd_atf_sumb' , tmltrd_atf_sumb)
+         !
+         !-- Salinity
+         CALL iom_get( inum, jpdom_autoglo, 'smlbn'           , smlbn          ) ! needed for sml_sum
+         CALL iom_get( inum, jpdom_autoglo, 'sml_sumb'        , sml_sumb       )
+         DO jk = 1, jpltrd
+            IF( jk < 10 ) THEN   ;   WRITE(charout,FMT="('smltrd_csum_ub_', I1)")   jk
+            ELSE                 ;   WRITE(charout,FMT="('smltrd_csum_ub_', I2)")   jk
+            ENDIF
+            CALL iom_get( inum, jpdom_autoglo, charout, smltrd_csum_ub(:,:,jk) )
+         END DO
+         CALL iom_get( inum, jpdom_autoglo, 'smltrd_atf_sumb' , smltrd_atf_sumb)
+         !
+         CALL iom_close( inum )
+      ENDIF
+      !
+   END SUBROUTINE trd_mxl_rst_read
+  
+  !!=================================================================================
+END MODULE trdmxl_rst
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdpen.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdpen.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdpen.F90	(revision 5075)
@@ -0,0 +1,159 @@
+MODULE trdpen
+   !!======================================================================
+   !!                       ***  MODULE  trdpen  ***
+   !! Ocean diagnostics:  Potential Energy trends
+   !!=====================================================================
+   !! History :  3.5  !  2012-02  (G. Madec) original code 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trd_pen       : compute and output Potential Energy trends from T & S trends
+   !!   trd_pen_init  : initialisation of PE trends
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean domain 
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE zdf_oce        ! ocean vertical physics
+   USE trd_oce        ! trends: ocean variables
+   USE eosbn2         ! equation of state and related derivatives
+   USE ldftra_oce     ! ocean active tracers lateral physics
+   USE zdfddm         ! vertical physics: double diffusion
+   USE phycst         ! physical constants
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE wrk_nemo       ! Memory allocation
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC   trd_pen        ! called by all trdtra module
+   PUBLIC   trd_pen_init   ! called by all nemogcm module
+
+   INTEGER ::   nkstp   ! current time step 
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   rab_pe   ! partial derivatives of PE anomaly with respect to T and S
+
+   !! * Substitutions
+#  include "domzgr_substitute.h90"
+#  include "zdfddm_substitute.h90"
+#  include "vectopt_loop_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: trdtra.F90 3318 2012-02-25 15:50:01Z gm $
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_pen_alloc()
+      !!---------------------------------------------------------------------
+      !!                  ***  FUNCTION trd_tra_alloc  ***
+      !!---------------------------------------------------------------------
+      ALLOCATE( rab_pe(jpi,jpj,jpk,jpts) , STAT= trd_pen_alloc )
+      !
+      IF( lk_mpp             )   CALL mpp_sum ( trd_pen_alloc )
+      IF( trd_pen_alloc /= 0 )   CALL ctl_warn( 'trd_pen_alloc: failed to allocate arrays' )
+   END FUNCTION trd_pen_alloc
+
+
+   SUBROUTINE trd_pen( ptrdx, ptrdy, ktrd, kt, pdt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_tra_mng  ***
+      !! 
+      !! ** Purpose :   Dispatch all trends computation, e.g. 3D output, integral
+      !!                constraints, barotropic vorticity, kinetic enrgy, 
+      !!                potential energy, and/or mixed layer budget.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(in) ::   ptrdx, ptrdy   ! Temperature & Salinity trends
+      INTEGER                   , INTENT(in) ::   ktrd           ! tracer trend index
+      INTEGER                   , INTENT(in) ::   kt             ! time step index
+      REAL(wp)                  , INTENT(in) ::   pdt            ! time step [s]
+      !
+      INTEGER ::   jk                                            ! dummy loop indices
+      REAL(wp), POINTER, DIMENSION(:,:)      ::   z2d            ! 2D workspace 
+      REAL(wp), POINTER, DIMENSION(:,:,:)    ::   zpe            ! 3D workspace 
+      !!----------------------------------------------------------------------
+      !
+      CALL wrk_alloc( jpi, jpj, jpk, zpe )
+      zpe(:,:,:) = 0._wp
+      !
+      IF ( kt /= nkstp ) THEN   ! full eos: set partial derivatives at the 1st call of kt time step
+         nkstp = kt
+         CALL eos_pen( tsn, rab_PE, zpe )
+         CALL iom_put( "alphaPE", rab_pe(:,:,:,jp_tem) )
+         CALL iom_put( "betaPE" , rab_pe(:,:,:,jp_sal) )
+         CALL iom_put( "PEanom" , zpe )
+      ENDIF
+      !
+      zpe(:,:,jpk) = 0._wp
+      DO jk = 1, jpkm1
+         zpe(:,:,jk) = ( - ( rab_n(:,:,jk,jp_tem) + rab_pe(:,:,jk,jp_tem) ) * ptrdx(:,:,jk)   &
+            &            + ( rab_n(:,:,jk,jp_sal) + rab_pe(:,:,jk,jp_sal) ) * ptrdy(:,:,jk)  )
+      END DO
+
+      SELECT CASE ( ktrd )
+      CASE ( jptra_xad  )   ;   CALL iom_put( "petrd_xad", zpe )   ! zonal    advection
+      CASE ( jptra_yad  )   ;   CALL iom_put( "petrd_yad", zpe )   ! merid.   advection
+      CASE ( jptra_zad  )   ;   CALL iom_put( "petrd_zad", zpe )   ! vertical advection
+                                IF( .NOT.lk_vvl ) THEN                   ! cst volume : adv flux through z=0 surface
+                                   CALL wrk_alloc( jpi, jpj, z2d )
+                                   z2d(:,:) = wn(:,:,1) * ( &
+                                   	  &   - ( rab_n(:,:,1,jp_tem) + rab_pe(:,:,1,jp_tem) ) * tsn(:,:,1,jp_tem)    &
+                                   	  &   + ( rab_n(:,:,1,jp_sal) + rab_pe(:,:,1,jp_sal) ) * tsn(:,:,1,jp_sal)    &
+                                      &   					) / fse3t(:,:,1)
+                                   CALL iom_put( "petrd_sad" , z2d )
+                                   CALL wrk_dealloc( jpi, jpj, z2d )
+                                ENDIF
+      CASE ( jptra_ldf  )   ;   CALL iom_put( "petrd_ldf" , zpe )   ! lateral  diffusion
+      CASE ( jptra_zdf  )   ;   CALL iom_put( "petrd_zdf" , zpe )   ! lateral  diffusion (K_z)
+      CASE ( jptra_zdfp )   ;   CALL iom_put( "petrd_zdfp", zpe )   ! vertical diffusion (K_z)
+      CASE ( jptra_dmp  )   ;   CALL iom_put( "petrd_dmp" , zpe )   ! internal 3D restoring (tradmp)
+      CASE ( jptra_bbl  )   ;   CALL iom_put( "petrd_bbl" , zpe )   ! bottom boundary layer
+      CASE ( jptra_npc  )   ;   CALL iom_put( "petrd_npc" , zpe )   ! non penetr convect adjustment
+      CASE ( jptra_nsr  )   ;   CALL iom_put( "petrd_nsr" , zpe )   ! surface forcing + runoff (ln_rnf=T)
+      CASE ( jptra_qsr  )   ;   CALL iom_put( "petrd_qsr" , zpe )   ! air-sea : penetrative sol radiat
+      CASE ( jptra_bbc  )   ;   CALL iom_put( "petrd_bbc" , zpe )   ! bottom bound cond (geoth flux)
+      CASE ( jptra_atf  )   ;   CALL iom_put( "petrd_atf" , zpe )   ! asselin time filter (last trend)
+                                !IF( .NOT.lk_vvl ) THEN                   ! cst volume : ssh term (otherwise include in e3t variation)
+                                !   CALL wrk_alloc( jpi, jpj, z2d )
+                                !   z2d(:,:) = ( ssha(:,:) - sshb(:,:) )                 &
+                                !      &     * (   dPE_dt(:,:,1) * tsn(:,:,1,jp_tem)    &
+                                !      &         + dPE_ds(:,:,1) * tsn(:,:,1,jp_sal)  ) / ( fse3t(:,:,1) * pdt )
+                                !   CALL iom_put( "petrd_sad" , z2d )
+                                !   CALL wrk_dealloc( jpi, jpj, z2d )
+                                !ENDIF
+         !
+      END SELECT
+      !
+      CALL wrk_dealloc( jpi, jpj, jpk, zpe )
+      !
+   END SUBROUTINE trd_pen
+
+
+   SUBROUTINE trd_pen_init
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_pen_init  ***
+      !! 
+      !! ** Purpose :   initialisation of 3D Kinetic Energy trend diagnostic
+      !!----------------------------------------------------------------------
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      !!----------------------------------------------------------------------
+      !
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) 'trd_pen_init : 3D Potential ENergy trends'
+         WRITE(numout,*) '~~~~~~~~~~~~~'
+      ENDIF
+      !                           ! allocate box volume arrays
+      IF ( trd_pen_alloc() /= 0 )   CALL ctl_stop('trd_pen_alloc: failed to allocate arrays')
+      !
+      rab_pe(:,:,:,:) = 0._wp
+      !
+      IF ( lk_vvl               )   CALL ctl_stop('trd_pen_init : PE trends not coded for variable volume')
+      !
+      nkstp     = nit000 - 1
+      !
+   END SUBROUTINE trd_pen_init
+
+   !!======================================================================
+END MODULE trdpen
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdtra.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdtra.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdtra.F90	(revision 5075)
@@ -2,35 +2,48 @@
    !!======================================================================
    !!                       ***  MODULE  trdtra  ***
-   !! Ocean diagnostics:  ocean tracers trends
+   !! Ocean diagnostics:  ocean tracers trends pre-processing
    !!=====================================================================
-   !! History :  1.0  !  2004-08  (C. Talandier) Original code
-   !!            2.0  !  2005-04  (C. Deltel)    Add Asselin trend in the ML budget
-   !!            3.3  !  2010-06  (C. Ethe) merge TRA-TRC 
-   !!----------------------------------------------------------------------
-#if  defined key_trdtra || defined key_trdtrc || defined key_trdmld || defined key_trdmld_trc 
-   !!----------------------------------------------------------------------
-   !!   trd_tra      : Call the trend to be computed
-   !!----------------------------------------------------------------------
-   USE dom_oce          ! ocean domain 
-   USE trdmod_oce       ! ocean active mixed layer tracers trends 
-   USE trdmod           ! ocean active mixed layer tracers trends 
-   USE trdmod_trc       ! ocean passive mixed layer tracers trends 
-   USE in_out_manager   ! I/O manager
-   USE lib_mpp          ! MPP library
-   USE wrk_nemo        ! Memory allocation
-
+   !! History :  3.3  !  2010-06  (C. Ethe) creation for the TRA/TRC merge
+   !!            3.5  !  2012-02  (G. Madec) update the comments 
+   !!----------------------------------------------------------------------
+
+   !!----------------------------------------------------------------------
+   !!   trd_tra       : pre-process the tracer trends
+   !!   trd_tra_adv   : transform a div(U.T) trend into a U.grad(T) trend
+   !!   trd_tra_mng   : tracer trend manager: dispatch to the diagnostic modules
+   !!   trd_tra_iom   : output 3D tracer trends using IOM
+   !!----------------------------------------------------------------------
+   USE oce            ! ocean dynamics and tracers variables
+   USE dom_oce        ! ocean domain 
+   USE sbc_oce        ! surface boundary condition: ocean
+   USE zdf_oce        ! ocean vertical physics
+   USE trd_oce        ! trends: ocean variables
+   USE trdtrc         ! ocean passive mixed layer tracers trends 
+   USE trdglo         ! trends: global domain averaged
+   USE trdpen         ! trends: Potential ENergy
+   USE trdmxl         ! ocean active mixed layer tracers trends 
+   USE ldftra_oce     ! ocean active tracers lateral physics
+   USE zdfddm         ! vertical physics: double diffusion
+   USE phycst         ! physical constants
+   USE in_out_manager ! I/O manager
+   USE iom            ! I/O manager library
+   USE lib_mpp        ! MPP library
+   USE wrk_nemo       ! Memory allocation
 
    IMPLICIT NONE
    PRIVATE
 
-   PUBLIC   trd_tra          ! called by all  traXX modules
- 
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) :: trdtx, trdty, trdt  !:
+   PUBLIC   trd_tra   ! called by all tra_... modules
+
+   REAL(wp) ::   r2dt   ! time-step, = 2 rdttra except at nit000 (=rdttra) if neuler=0
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   trdtx, trdty, trdt   ! use to store the temperature trends
 
    !! * Substitutions
 #  include "domzgr_substitute.h90"
+#  include "zdfddm_substitute.h90"
 #  include "vectopt_loop_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/OPA 4.0 , NEMO Consortium (2011)
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
    !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -39,7 +52,7 @@
 
    INTEGER FUNCTION trd_tra_alloc()
-      !!----------------------------------------------------------------------------
+      !!---------------------------------------------------------------------
       !!                  ***  FUNCTION trd_tra_alloc  ***
-      !!----------------------------------------------------------------------------
+      !!---------------------------------------------------------------------
       ALLOCATE( trdtx(jpi,jpj,jpk) , trdty(jpi,jpj,jpk) , trdt(jpi,jpj,jpk) , STAT= trd_tra_alloc )
       !
@@ -53,86 +66,97 @@
       !!                  ***  ROUTINE trd_tra  ***
       !! 
-      !! ** Purpose : Dispatch all trends computation, e.g. vorticity, mld or 
-      !!              integral constraints
+      !! ** Purpose : pre-process tracer trends
       !!
-      !! ** Method/usage : For the mixed-layer trend, the control surface can be either
-      !!       a mixed layer depth (time varying) or a fixed surface (jk level or bowl). 
-      !!      Choose control surface with nn_ctls in namelist NAMTRD :
-      !!        nn_ctls = 0  : use mixed layer with density criterion 
-      !!        nn_ctls = 1  : read index from file 'ctlsurf_idx'
-      !!        nn_ctls > 1  : use fixed level surface jk = nn_ctls
-      !!----------------------------------------------------------------------
-      !
-      INTEGER                         , INTENT(in)           ::  kt      ! time step
-      CHARACTER(len=3)                , INTENT(in)           ::  ctype   ! tracers trends type 'TRA'/'TRC'
-      INTEGER                         , INTENT(in)           ::  ktra    ! tracer index
-      INTEGER                         , INTENT(in)           ::  ktrd    ! tracer trend index
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)           ::  ptrd    ! tracer trend  or flux
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in), OPTIONAL ::  pun     ! velocity 
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in), OPTIONAL ::  ptra    ! Tracer variablea
-      !
-      REAL(wp), POINTER, DIMENSION(:,:,:)  ::  ztrds
-      !!----------------------------------------------------------------------
-
+      !! ** Method  : - mask the trend
+      !!              - advection (ptra present) converte the incoming flux (U.T) 
+      !!              into trend (U.T => -U.grat(T)=div(U.T)-T.div(U)) through a 
+      !!              call to trd_tra_adv
+      !!              - 'TRA' case : regroup T & S trends
+      !!              - send the trends to trd_tra_mng (trdtrc) for further processing
+      !!----------------------------------------------------------------------
+      INTEGER                         , INTENT(in)           ::   kt      ! time step
+      CHARACTER(len=3)                , INTENT(in)           ::   ctype   ! tracers trends type 'TRA'/'TRC'
+      INTEGER                         , INTENT(in)           ::   ktra    ! tracer index
+      INTEGER                         , INTENT(in)           ::   ktrd    ! tracer trend index
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)           ::   ptrd    ! tracer trend  or flux
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in), OPTIONAL ::   pun     ! now velocity 
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in), OPTIONAL ::   ptra    ! now tracer variable
+      !
+      INTEGER  ::   jk   ! loop indices
+      REAL(wp), POINTER, DIMENSION(:,:,:)  ::   zwt, zws, ztrdt, ztrds   ! 3D workspace
+      !!----------------------------------------------------------------------
+      !
       CALL wrk_alloc( jpi, jpj, jpk, ztrds )
-
-      IF( .NOT. ALLOCATED( trdtx ) ) THEN       ! allocate trdtra arrays
+      !      
+      IF( .NOT. ALLOCATED( trdtx ) ) THEN      ! allocate trdtra arrays
          IF( trd_tra_alloc() /= 0 )   CALL ctl_stop( 'STOP', 'trd_tra : unable to allocate arrays' )
       ENDIF
-      
-      ! Control of optional arguments
-      IF( ctype == 'TRA' .AND. ktra == jp_tem ) THEN 
-         IF( PRESENT( ptra ) ) THEN    
-            SELECT CASE( ktrd )            ! shift depending on the direction
-            CASE( jptra_trd_xad )  ;  CALL trd_tra_adv( ptrd, pun, ptra, 'X', trdtx ) 
-            CASE( jptra_trd_yad )  ;  CALL trd_tra_adv( ptrd, pun, ptra, 'Y', trdty ) 
-            CASE( jptra_trd_zad )  ;  CALL trd_tra_adv( ptrd, pun, ptra, 'Z', trdt  ) 
-            END SELECT
-         ELSE
-            trdt(:,:,:) = ptrd(:,:,:)
-            IF( ktrd == jptra_trd_bbc .OR. ktrd == jptra_trd_qsr ) THEN
-               ztrds(:,:,:) = 0.
-               CALL trd_mod( trdt, ztrds, ktrd, ctype, kt )
-            END IF
-         END IF
-      END IF
-
-      IF( ctype == 'TRA' .AND. ktra == jp_sal ) THEN 
-         IF( PRESENT( ptra ) ) THEN    
-            SELECT CASE( ktrd )            ! shift depending on the direction
-            CASE( jptra_trd_xad )  
-                                CALL trd_tra_adv( ptrd, pun, ptra, 'X', ztrds ) 
-                                CALL trd_mod( trdtx, ztrds, ktrd, ctype, kt   )
-            CASE( jptra_trd_yad )  
-                                CALL trd_tra_adv( ptrd, pun, ptra, 'Y', ztrds ) 
-                                CALL trd_mod( trdty, ztrds, ktrd, ctype, kt   )
-            CASE( jptra_trd_zad )    
-                                CALL trd_tra_adv( ptrd, pun, ptra, 'Z', ztrds ) 
-                                CALL trd_mod( trdt , ztrds, ktrd, ctype, kt   )
-            END SELECT
-         ELSE
-            ztrds(:,:,:) = ptrd(:,:,:)
-            CALL trd_mod( trdt, ztrds, ktrd, ctype, kt )  
-         END IF
-      END IF
-
-      IF( ctype == 'TRC' ) THEN
-         !
-         IF( PRESENT( ptra ) ) THEN  
-            SELECT CASE( ktrd )            ! shift depending on the direction
-            CASE( jptra_trd_xad )  
-                                CALL trd_tra_adv( ptrd, pun, ptra, 'X', ztrds ) 
-                                CALL trd_mod_trc( ztrds, ktra, ktrd, kt       )
-            CASE( jptra_trd_yad )  
-                                CALL trd_tra_adv( ptrd, pun, ptra, 'Y', ztrds ) 
-                                CALL trd_mod_trc( ztrds, ktra, ktrd, kt       )
-            CASE( jptra_trd_zad )    
-                                CALL trd_tra_adv( ptrd, pun, ptra, 'Z', ztrds ) 
-                                CALL trd_mod_trc( ztrds, ktra, ktrd, kt       )
-            END SELECT
-         ELSE
-            ztrds(:,:,:) = ptrd(:,:,:)
-            CALL trd_mod_trc( ztrds, ktra, ktrd, kt       )  
-         END IF
+
+      IF( ctype == 'TRA' .AND. ktra == jp_tem ) THEN   !==  Temperature trend  ==!
+         !
+         SELECT CASE( ktrd )
+         !                            ! advection: transform the advective flux into a trend
+         CASE( jptra_xad )   ;   CALL trd_tra_adv( ptrd, pun, ptra, 'X', trdtx ) 
+         CASE( jptra_yad )   ;   CALL trd_tra_adv( ptrd, pun, ptra, 'Y', trdty ) 
+         CASE( jptra_zad )   ;   CALL trd_tra_adv( ptrd, pun, ptra, 'Z', trdt  ) 
+         CASE( jptra_bbc,    &        ! qsr, bbc: on temperature only, send to trd_tra_mng
+            &  jptra_qsr )   ;   trdt(:,:,:) = ptrd(:,:,:) * tmask(:,:,:)
+                                 ztrds(:,:,:) = 0._wp
+                                 CALL trd_tra_mng( trdt, ztrds, ktrd, kt )
+         CASE DEFAULT                 ! other trends: masked trends
+            trdt(:,:,:) = ptrd(:,:,:) * tmask(:,:,:)              ! mask & store
+         END SELECT
+         !
+      ENDIF
+
+      IF( ctype == 'TRA' .AND. ktra == jp_sal ) THEN      !==  Salinity trends  ==!
+         !
+         SELECT CASE( ktrd )
+         !                            ! advection: transform the advective flux into a trend
+         !                            !            and send T & S trends to trd_tra_mng
+         CASE( jptra_xad  )   ;   CALL trd_tra_adv( ptrd , pun  , ptra, 'X'  , ztrds ) 
+                                  CALL trd_tra_mng( trdtx, ztrds, ktrd, kt   )
+         CASE( jptra_yad  )   ;   CALL trd_tra_adv( ptrd , pun  , ptra, 'Y'  , ztrds ) 
+                                  CALL trd_tra_mng( trdty, ztrds, ktrd, kt   )
+         CASE( jptra_zad  )   ;   CALL trd_tra_adv( ptrd , pun  , ptra, 'Z'  , ztrds ) 
+                                  CALL trd_tra_mng( trdt , ztrds, ktrd, kt   )
+         CASE( jptra_zdfp )           ! diagnose the "PURE" Kz trend (here: just before the swap)
+            !                         ! iso-neutral diffusion case otherwise jptra_zdf is "PURE"
+            CALL wrk_alloc( jpi, jpj, jpk, zwt, zws, ztrdt )
+            !
+            zwt(:,:, 1 ) = 0._wp   ;   zws(:,:, 1 ) = 0._wp            ! vertical diffusive fluxes
+            zwt(:,:,jpk) = 0._wp   ;   zws(:,:,jpk) = 0._wp
+            DO jk = 2, jpk
+               zwt(:,:,jk) =   avt(:,:,jk) * ( tsa(:,:,jk-1,jp_tem) - tsa(:,:,jk,jp_tem) ) / fse3w(:,:,jk) * tmask(:,:,jk)
+               zws(:,:,jk) = fsavs(:,:,jk) * ( tsa(:,:,jk-1,jp_sal) - tsa(:,:,jk,jp_sal) ) / fse3w(:,:,jk) * tmask(:,:,jk)
+            END DO
+            !
+            ztrdt(:,:,jpk) = 0._wp   ;   ztrds(:,:,jpk) = 0._wp
+            DO jk = 1, jpkm1
+               ztrdt(:,:,jk) = ( zwt(:,:,jk) - zwt(:,:,jk+1) ) / fse3t(:,:,jk)
+               ztrds(:,:,jk) = ( zws(:,:,jk) - zws(:,:,jk+1) ) / fse3t(:,:,jk) 
+            END DO
+            CALL trd_tra_mng( ztrdt, ztrds, jptra_zdfp, kt )  
+            !
+            CALL wrk_dealloc( jpi, jpj, jpk, zwt, zws, ztrdt )
+            !
+         CASE DEFAULT                 ! other trends: mask and send T & S trends to trd_tra_mng
+            ztrds(:,:,:) = ptrd(:,:,:) * tmask(:,:,:)
+            CALL trd_tra_mng( trdt, ztrds, ktrd, kt )  
+         END SELECT
+      ENDIF
+
+      IF( ctype == 'TRC' ) THEN                           !==  passive tracer trend  ==!
+         !
+         SELECT CASE( ktrd )
+         !                            ! advection: transform the advective flux into a masked trend
+         CASE( jptra_xad )   ;   CALL trd_tra_adv( ptrd , pun , ptra, 'X', ztrds ) 
+         CASE( jptra_yad )   ;   CALL trd_tra_adv( ptrd , pun , ptra, 'Y', ztrds ) 
+         CASE( jptra_zad )   ;   CALL trd_tra_adv( ptrd , pun , ptra, 'Z', ztrds ) 
+         CASE DEFAULT                 ! other trends: just masked 
+                                 ztrds(:,:,:) = ptrd(:,:,:) * tmask(:,:,:)
+         END SELECT
+         !                            ! send trend to trd_trc
+         CALL trd_trc( ztrds, ktra, ktrd, kt ) 
          !
       ENDIF
@@ -147,39 +171,39 @@
       !!                  ***  ROUTINE trd_tra_adv  ***
       !! 
-      !! ** Purpose :   transformed the i-, j- or k-advective flux into thes
-      !!              i-, j- or k-advective trends, resp.
-      !! ** Method  :   i-advective trends = -un. di-1[T] = -( di-1[fi] - tn di-1[un] )
-      !!                k-advective trends = -un. di-1[T] = -( dj-1[fi] - tn dj-1[un] )
-      !!                k-advective trends = -un. di+1[T] = -( dk+1[fi] - tn dk+1[un] )
-      !!----------------------------------------------------------------------
-      REAL(wp)        , INTENT(in ), DIMENSION(jpi,jpj,jpk) ::   pf      ! advective flux in one direction
-      REAL(wp)        , INTENT(in ), DIMENSION(jpi,jpj,jpk) ::   pun     ! now velocity  in one direction
-      REAL(wp)        , INTENT(in ), DIMENSION(jpi,jpj,jpk) ::   ptn     ! now or before tracer 
-      CHARACTER(len=1), INTENT(in )                         ::   cdir    ! X/Y/Z direction
-      REAL(wp)        , INTENT(out), DIMENSION(jpi,jpj,jpk) ::   ptrd    ! advective trend in one direction
+      !! ** Purpose :   transformed a advective flux into a masked advective trends
+      !!
+      !! ** Method  :   use the following transformation: -div(U.T) = - U grad(T) + T.div(U)
+      !!       i-advective trends = -un. di-1[T] = -( di-1[fi] - tn di-1[un] )
+      !!       j-advective trends = -un. di-1[T] = -( dj-1[fi] - tn dj-1[un] )
+      !!       k-advective trends = -un. di+1[T] = -( dk+1[fi] - tn dk+1[un] )
+      !!                where fi is the incoming advective flux.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pf      ! advective flux in one direction
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   pun     ! now velocity   in one direction
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in   ) ::   ptn     ! now or before tracer 
+      CHARACTER(len=1)                , INTENT(in   ) ::   cdir    ! X/Y/Z direction
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(  out) ::   ptrd    ! advective trend in one direction
       !
       INTEGER  ::   ji, jj, jk   ! dummy loop indices
-      INTEGER  ::   ii, ij, ik   ! index shift function of the direction
-      REAL(wp) ::   zbtr         ! local scalar
-      !!----------------------------------------------------------------------
-
-      SELECT CASE( cdir )            ! shift depending on the direction
-      CASE( 'X' )   ;   ii = 1   ; ij = 0   ;   ik = 0      ! i-advective trend
-      CASE( 'Y' )   ;   ii = 0   ; ij = 1   ;   ik = 0      ! j-advective trend
-      CASE( 'Z' )   ;   ii = 0   ; ij = 0   ;   ik =-1      ! k-advective trend
+      INTEGER  ::   ii, ij, ik   ! index shift as function of the direction
+      !!----------------------------------------------------------------------
+      !
+      SELECT CASE( cdir )      ! shift depending on the direction
+      CASE( 'X' )   ;   ii = 1   ;   ij = 0   ;   ik = 0      ! i-trend
+      CASE( 'Y' )   ;   ii = 0   ;   ij = 1   ;   ik = 0      ! j-trend
+      CASE( 'Z' )   ;   ii = 0   ;   ij = 0   ;   ik =-1      ! k-trend
       END SELECT
-
-      !                              ! set to zero uncomputed values
-      ptrd(jpi,:,:) = 0.e0   ;   ptrd(1,:,:) = 0.e0
-      ptrd(:,jpj,:) = 0.e0   ;   ptrd(:,1,:) = 0.e0
-      ptrd(:,:,jpk) = 0.e0
-      !
-      !
-      DO jk = 1, jpkm1
+      !
+      !                        ! set to zero uncomputed values
+      ptrd(jpi,:,:) = 0._wp   ;   ptrd(1,:,:) = 0._wp
+      ptrd(:,jpj,:) = 0._wp   ;   ptrd(:,1,:) = 0._wp
+      ptrd(:,:,jpk) = 0._wp
+      !
+      DO jk = 1, jpkm1         ! advective trend
          DO jj = 2, jpjm1
             DO ji = fs_2, fs_jpim1   ! vector opt.
-               zbtr    = 1.e0/ ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )
-               ptrd(ji,jj,jk) = - zbtr * (      pf (ji,jj,jk) - pf (ji-ii,jj-ij,jk-ik)                    &
-                 &                          - ( pun(ji,jj,jk) - pun(ji-ii,jj-ij,jk-ik) ) * ptn(ji,jj,jk)  )
+               ptrd(ji,jj,jk) = - (     pf (ji,jj,jk) - pf (ji-ii,jj-ij,jk-ik)                        &
+                 &                  - ( pun(ji,jj,jk) - pun(ji-ii,jj-ij,jk-ik) ) * ptn(ji,jj,jk)  )   &
+                 &              / ( e1t(ji,jj) * e2t(ji,jj) * fse3t(ji,jj,jk) )  * tmask(ji,jj,jk)
             END DO
          END DO
@@ -188,23 +212,126 @@
    END SUBROUTINE trd_tra_adv
 
-#   else
-   !!----------------------------------------------------------------------
-   !!   Default case :          Dummy module           No trend diagnostics
-   !!----------------------------------------------------------------------
-   USE par_oce      ! ocean variables trends
-CONTAINS
-   SUBROUTINE trd_tra( kt, ctype, ktra, ktrd, ptrd, pu, ptra )
-      !!----------------------------------------------------------------------
-      INTEGER                         , INTENT(in)           ::  kt      ! time step
-      CHARACTER(len=3)                , INTENT(in)           ::  ctype   ! tracers trends type 'TRA'/'TRC'
-      INTEGER                         , INTENT(in)           ::  ktra    ! tracer index
-      INTEGER                         , INTENT(in)           ::  ktrd    ! tracer trend index
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in)           ::  ptrd    ! tracer trend 
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in), OPTIONAL ::  pu      ! velocity 
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in), OPTIONAL ::  ptra    ! Tracer variable 
-      WRITE(*,*) 'trd_3d: You should not have seen this print! error ?', ptrd(1,1,1), ptra(1,1,1), pu(1,1,1),   &
-         &                                                               ktrd, ktra, ctype, kt
-   END SUBROUTINE trd_tra
-#   endif
+
+   SUBROUTINE trd_tra_mng( ptrdx, ptrdy, ktrd, kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_tra_mng  ***
+      !! 
+      !! ** Purpose :   Dispatch all tracer trends computation, e.g. 3D output,
+      !!                integral constraints, potential energy, and/or 
+      !!                mixed layer budget.
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdx   ! Temperature or U trend 
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdy   ! Salinity    or V trend
+      INTEGER                   , INTENT(in   ) ::   ktrd    ! tracer trend index
+      INTEGER                   , INTENT(in   ) ::   kt      ! time step
+      !!----------------------------------------------------------------------
+
+      IF( neuler == 0 .AND. kt == nit000    ) THEN   ;   r2dt =      rdt      ! = rdtra (restart with Euler time stepping)
+      ELSEIF(               kt <= nit000 + 1) THEN   ;   r2dt = 2. * rdt      ! = 2 rdttra (leapfrog)
+      ENDIF
+
+      !                   ! 3D output of tracers trends using IOM interface
+      IF( ln_tra_trd )   CALL trd_tra_iom ( ptrdx, ptrdy, ktrd, kt )
+
+      !                   ! Integral Constraints Properties for tracers trends                                       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+      IF( ln_glo_trd )   CALL trd_glo( ptrdx, ptrdy, ktrd, 'TRA', kt )
+
+      !                   ! Potential ENergy trends
+      IF( ln_PE_trd  )   CALL trd_pen( ptrdx, ptrdy, ktrd, kt, r2dt )
+
+      !                   ! Mixed layer trends for active tracers
+      IF( ln_tra_mxl )   THEN   
+         !-----------------------------------------------------------------------------------------------
+         ! W.A.R.N.I.N.G :
+         ! jptra_ldf : called by traldf.F90
+         !                 at this stage we store:
+         !                  - the lateral geopotential diffusion (here, lateral = horizontal)
+         !                  - and the iso-neutral diffusion if activated 
+         ! jptra_zdf : called by trazdf.F90
+         !                 * in case of iso-neutral diffusion we store the vertical diffusion component in the 
+         !                   lateral trend including the K_z contrib, which will be removed later (see trd_mxl)
+         !-----------------------------------------------------------------------------------------------
+
+         SELECT CASE ( ktrd )
+         CASE ( jptra_xad )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_xad, '3D' )   ! zonal    advection
+         CASE ( jptra_yad )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_yad, '3D' )   ! merid.   advection
+         CASE ( jptra_zad )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_zad, '3D' )   ! vertical advection
+         CASE ( jptra_ldf )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_ldf, '3D' )   ! lateral  diffusion
+         CASE ( jptra_bbl )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_bbl, '3D' )   ! bottom boundary layer
+         CASE ( jptra_zdf )
+            IF( ln_traldf_iso ) THEN ; CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_ldf, '3D' )   ! lateral  diffusion (K_z)
+            ELSE                   ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_zdf, '3D' )   ! vertical diffusion (K_z)
+            ENDIF
+         CASE ( jptra_dmp )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_dmp, '3D' )   ! internal 3D restoring (tradmp)
+         CASE ( jptra_qsr )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_for, '3D' )   ! air-sea : penetrative sol radiat
+         CASE ( jptra_nsr )        ;   ptrdx(:,:,2:jpk) = 0._wp   ;   ptrdy(:,:,2:jpk) = 0._wp
+                                       CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_for, '2D' )   ! air-sea : non penetr sol radiation
+         CASE ( jptra_bbc )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_bbc, '3D' )   ! bottom bound cond (geoth flux)
+         CASE ( jptra_npc )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_npc, '3D' )   ! non penetr convect adjustment
+         CASE ( jptra_atf )        ;   CALL trd_mxl_zint( ptrdx, ptrdy, jpmxl_atf, '3D' )   ! asselin time filter (last trend)
+                                   !
+                                       CALL trd_mxl( kt, r2dt )                             ! trends: Mixed-layer (output)
+         END SELECT
+         !
+      ENDIF
+      !
+   END SUBROUTINE trd_tra_mng
+
+
+   SUBROUTINE trd_tra_iom( ptrdx, ptrdy, ktrd, kt )
+      !!---------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_tra_iom  ***
+      !! 
+      !! ** Purpose :   output 3D tracer trends using IOM
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdx   ! Temperature or U trend 
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   ptrdy   ! Salinity    or V trend
+      INTEGER                   , INTENT(in   ) ::   ktrd    ! tracer trend index
+      INTEGER                   , INTENT(in   ) ::   kt      ! time step
+      !!
+      INTEGER ::   ji, jj, jk   ! dummy loop indices
+      INTEGER ::   ikbu, ikbv   ! local integers
+      REAL(wp), POINTER, DIMENSION(:,:)   ::   z2dx, z2dy   ! 2D workspace 
+      !!----------------------------------------------------------------------
+      !
+!!gm Rq: mask the trends already masked in trd_tra, but lbc_lnk should probably be added
+      !
+      SELECT CASE( ktrd )
+      CASE( jptra_xad  )   ;   CALL iom_put( "ttrd_xad" , ptrdx )        ! x- horizontal advection
+                               CALL iom_put( "strd_xad" , ptrdy )
+      CASE( jptra_yad  )   ;   CALL iom_put( "ttrd_yad" , ptrdx )        ! y- horizontal advection
+                               CALL iom_put( "strd_yad" , ptrdy )
+      CASE( jptra_zad  )   ;   CALL iom_put( "ttrd_zad" , ptrdx )        ! z- vertical   advection
+                               CALL iom_put( "strd_zad" , ptrdy )
+                               IF( .NOT. lk_vvl ) THEN                   ! cst volume : adv flux through z=0 surface
+                               	 CALL wrk_alloc( jpi, jpj, z2dx, z2dy )
+                                  z2dx(:,:) = wn(:,:,1) * tsn(:,:,1,jp_tem) / fse3t(:,:,1)
+                                  z2dy(:,:) = wn(:,:,1) * tsn(:,:,1,jp_sal) / fse3t(:,:,1)
+                                  CALL iom_put( "ttrd_sad", z2dx )
+                                  CALL iom_put( "strd_sad", z2dy )
+                                  CALL wrk_dealloc( jpi, jpj, z2dx, z2dy )
+                               ENDIF
+      CASE( jptra_ldf  )   ;   CALL iom_put( "ttrd_ldf" , ptrdx )        ! lateral diffusion
+                               CALL iom_put( "strd_ldf" , ptrdy )
+      CASE( jptra_zdf  )   ;   CALL iom_put( "ttrd_zdf" , ptrdx )        ! vertical diffusion (including Kz contribution)
+                               CALL iom_put( "strd_zdf" , ptrdy )
+      CASE( jptra_zdfp )   ;   CALL iom_put( "ttrd_zdfp", ptrdx )        ! PURE vertical diffusion (no isoneutral contribution)
+                               CALL iom_put( "strd_zdfp", ptrdy )
+      CASE( jptra_dmp  )   ;   CALL iom_put( "ttrd_dmp" , ptrdx )        ! internal restoring (damping)
+                               CALL iom_put( "strd_dmp" , ptrdy )
+      CASE( jptra_bbl  )   ;   CALL iom_put( "ttrd_bbl" , ptrdx )        ! bottom boundary layer
+                               CALL iom_put( "strd_bbl" , ptrdy )
+      CASE( jptra_npc  )   ;   CALL iom_put( "ttrd_npc" , ptrdx )        ! static instability mixing
+                               CALL iom_put( "strd_npc" , ptrdy )
+      CASE( jptra_nsr  )   ;   CALL iom_put( "ttrd_qns" , ptrdx )        ! surface forcing + runoff (ln_rnf=T)
+                               CALL iom_put( "strd_cdt" , ptrdy )
+      CASE( jptra_qsr  )   ;   CALL iom_put( "ttrd_qsr" , ptrdx )        ! penetrative solar radiat. (only on temperature)
+      CASE( jptra_bbc  )   ;   CALL iom_put( "ttrd_bbc" , ptrdx )        ! geothermal heating   (only on temperature)
+      CASE( jptra_atf  )   ;   CALL iom_put( "ttrd_atf" , ptrdx )        ! asselin time Filter
+                               CALL iom_put( "strd_atf" , ptrdy )
+      END SELECT
+      !
+   END SUBROUTINE trd_tra_iom
+
    !!======================================================================
 END MODULE trdtra
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdtrc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdtrc.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdtrc.F90	(revision 5075)
@@ -0,0 +1,23 @@
+MODULE trdtrc
+   !!======================================================================
+   !!                       ***  MODULE trdtrc  ***
+   !!  Dummy module
+   !!======================================================================
+   !!----------------------------------------------------------------------
+   !!   Dummy module                                             NO TOP use
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   SUBROUTINE trd_trc( ptrtrd, kjn, ktrd, kt )
+      INTEGER ::   kt, kjn, ktrd   
+      REAL    ::   ptrtrd(:,:,:)  
+      WRITE(*,*) 'trd_trc : You should not have seen this print! error?', ptrtrd(1,1,1)
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kjn, ktrd, kt
+   END SUBROUTINE trd_trc
+
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! $Id: trdtrc.F90 2715 2011-03-30 15:58:35Z rblod $
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!======================================================================
+END MODULE trdtrc
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdvor.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdvor.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdvor.F90	(revision 5075)
@@ -4,10 +4,9 @@
    !! Ocean diagnostics:  momentum trends
    !!=====================================================================
-   !! History :  1.0  !  04-2006  (L. Brunier, A-M. Treguier) Original code 
-   !!            2.0  !  04-2008  (C. Talandier) New trends organization
+   !! History :  1.0  !  2006-01  (L. Brunier, A-M. Treguier) Original code 
+   !!            2.0  !  2008-04  (C. Talandier) New trends organization
+   !!            3.5  !  2012-02  (G. Madec) regroup beta.V computation with pvo trend
    !!----------------------------------------------------------------------
-#if defined key_trdvor   ||   defined key_esopa
-   !!----------------------------------------------------------------------
-   !!   'key_trdvor'   : momentum trend diagnostics
+
    !!----------------------------------------------------------------------
    !!   trd_vor      : momentum trends averaged over the depth
@@ -17,16 +16,16 @@
    USE oce             ! ocean dynamics and tracers variables
    USE dom_oce         ! ocean space and time domain variables
-   USE trdmod_oce      ! ocean variables trends
+   USE trd_oce         ! trends: ocean variables
    USE zdf_oce         ! ocean vertical physics
-   USE in_out_manager  ! I/O manager
+   USE sbc_oce         ! surface boundary condition: ocean
    USE phycst          ! Define parameters for the routines
    USE ldfdyn_oce      ! ocean active tracers: lateral physics
    USE dianam          ! build the name of file (routine)
    USE zdfmxl          ! mixed layer depth
+   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
+   USE in_out_manager  ! I/O manager
    USE ioipsl          ! NetCDF library
-   USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
    USE lib_mpp         ! MPP library
    USE wrk_nemo        ! Memory allocation
-
 
    IMPLICIT NONE
@@ -37,6 +36,5 @@
    END INTERFACE
 
-   PUBLIC   trd_vor        ! routine called by step.F90
-   PUBLIC   trd_vor_zint   ! routine called by dynamics routines
+   PUBLIC   trd_vor        ! routine called by trddyn.F90
    PUBLIC   trd_vor_init   ! routine called by opa.F90
    PUBLIC   trd_vor_alloc  ! routine called by nemogcm.F90
@@ -80,4 +78,52 @@
       IF( trd_vor_alloc /= 0 )   CALL ctl_warn('trd_vor_alloc: failed to allocate arrays')
    END FUNCTION trd_vor_alloc
+
+
+   SUBROUTINE trd_vor( putrd, pvtrd, ktrd, kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_vor  ***
+      !! 
+      !! ** Purpose :  computation of cumulated trends over analysis period
+      !!               and make outputs (NetCDF or DIMG format)
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(:,:,:), INTENT(inout) ::   putrd, pvtrd   ! U and V trends 
+      INTEGER                   , INTENT(in   ) ::   ktrd           ! trend index
+      INTEGER                   , INTENT(in   ) ::   kt             ! time step
+      !
+      INTEGER ::   ji, jj   ! dummy loop indices
+      REAL(wp), POINTER, DIMENSION(:,:) ::   ztswu, ztswv    ! 2D workspace 
+      !!----------------------------------------------------------------------
+
+      CALL wrk_alloc( jpi, jpj, ztswu, ztswv )
+
+      SELECT CASE( ktrd ) 
+      CASE( jpdyn_hpg )   ;   CALL trd_vor_zint( putrd, pvtrd, jpvor_prg )   ! Hydrostatique Pressure Gradient 
+      CASE( jpdyn_keg )   ;   CALL trd_vor_zint( putrd, pvtrd, jpvor_keg )   ! KE Gradient 
+      CASE( jpdyn_rvo )   ;   CALL trd_vor_zint( putrd, pvtrd, jpvor_rvo )   ! Relative Vorticity 
+      CASE( jpdyn_pvo )   ;   CALL trd_vor_zint( putrd, pvtrd, jpvor_pvo )   ! Planetary Vorticity Term 
+      CASE( jpdyn_ldf )   ;   CALL trd_vor_zint( putrd, pvtrd, jpvor_ldf )   ! Horizontal Diffusion 
+      CASE( jpdyn_zad )   ;   CALL trd_vor_zint( putrd, pvtrd, jpvor_zad )   ! Vertical Advection 
+      CASE( jpdyn_spg )   ;   CALL trd_vor_zint( putrd, pvtrd, jpvor_spg )   ! Surface Pressure Grad. 
+      CASE( jpdyn_zdf )                                                      ! Vertical Diffusion 
+         ztswu(:,:) = 0.e0   ;   ztswv(:,:) = 0.e0
+         DO jj = 2, jpjm1                                                             ! wind stress trends
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               ztswu(ji,jj) = 0.5 * ( utau_b(ji,jj) + utau(ji,jj) ) / ( fse3u(ji,jj,1) * rau0 )
+               ztswv(ji,jj) = 0.5 * ( vtau_b(ji,jj) + vtau(ji,jj) ) / ( fse3v(ji,jj,1) * rau0 )
+            END DO
+         END DO
+         !
+         CALL trd_vor_zint( putrd, pvtrd, jpvor_zdf )                             ! zdf trend including surf./bot. stresses 
+         CALL trd_vor_zint( ztswu, ztswv, jpvor_swf )                             ! surface wind stress 
+      CASE( jpdyn_bfr )
+         CALL trd_vor_zint( putrd, pvtrd, jpvor_bfr )                             ! Bottom stress
+         !
+      CASE( jpdyn_atf )       ! last trends: perform the output of 2D vorticity trends
+         CALL trd_vor_iom( kt )
+      END SELECT
+      !
+      CALL wrk_dealloc( jpi, jpj, ztswu, ztswv )
+      !
+   END SUBROUTINE trd_vor
 
 
@@ -109,5 +155,4 @@
       !!      trends output in netCDF format using ioipsl
       !!----------------------------------------------------------------------
-      !
       INTEGER                     , INTENT(in   ) ::   ktrd       ! ocean trend index
       REAL(wp), DIMENSION(jpi,jpj), INTENT(inout) ::   putrdvor   ! u vorticity trend 
@@ -131,7 +176,7 @@
       !  =====================================
 
-      SELECT CASE (ktrd) 
-      !
-      CASE (jpvor_bfr)        ! bottom friction
+      SELECT CASE( ktrd ) 
+      !
+      CASE( jpvor_bfr )        ! bottom friction
          DO jj = 2, jpjm1
             DO ji = fs_2, fs_jpim1 
@@ -143,5 +188,5 @@
          END DO
          !
-      CASE (jpvor_swf)        ! wind stress
+      CASE( jpvor_swf )        ! wind stress
          zudpvor(:,:) = putrdvor(:,:) * fse3u(:,:,1) * e1u(:,:) * umask(:,:,1)
          zvdpvor(:,:) = pvtrdvor(:,:) * fse3v(:,:,1) * e2v(:,:) * vmask(:,:,1)
@@ -154,6 +199,6 @@
    
       ! Curl
-      DO ji=1,jpim1
-         DO jj=1,jpjm1
+      DO ji = 1, jpim1
+         DO jj = 1, jpjm1
             vortrd(ji,jj,ktrd) = (    zvdpvor(ji+1,jj) - zvdpvor(ji,jj)       &
                  &                - ( zudpvor(ji,jj+1) - zudpvor(ji,jj) )   ) / ( e1f(ji,jj) * e2f(ji,jj) )
@@ -229,15 +274,23 @@
       END DO
 
-      ! Save Beta.V term to avoid average before Curl
-      ! Beta.V : intergration, no average
-      IF( ktrd == jpvor_bev ) THEN 
+      ! Planetary vorticity: 2nd computation (Beta.V term) store the vertical sum
+      ! as Beta.V term need intergration, not average
+      IF( ktrd == jpvor_pvo ) THEN 
          zubet(:,:) = zudpvor(:,:)
          zvbet(:,:) = zvdpvor(:,:)
-      ENDIF
-
-      ! Average except for Beta.V
+         DO ji = 1, jpim1
+            DO jj = 1, jpjm1
+               vortrd(ji,jj,jpvor_bev) = (    zvbet(ji+1,jj) - zvbet(ji,jj)     &
+                  &                       - ( zubet(ji,jj+1) - zubet(ji,jj) ) ) / ( e1f(ji,jj) * e2f(ji,jj) )
+            END DO
+         END DO
+         ! Average of the Curl and Surface mask
+         vortrd(:,:,jpvor_bev) = vortrd(:,:,jpvor_bev) * hur(:,:) * fmask(:,:,1)
+      ENDIF
+      !
+      ! Average 
       zudpvor(:,:) = zudpvor(:,:) * hur(:,:)
       zvdpvor(:,:) = zvdpvor(:,:) * hvr(:,:)
-   
+      !
       ! Curl
       DO ji=1,jpim1
@@ -247,24 +300,6 @@
          END DO
       END DO
-
       ! Surface mask
       vortrd(:,:,ktrd) = vortrd(:,:,ktrd) * fmask(:,:,1)
-
-      ! Special treatement for the Beta.V term
-      ! Compute the Curl of the Beta.V term which is not averaged
-      IF( ktrd == jpvor_bev ) THEN
-         DO ji=1,jpim1
-            DO jj=1,jpjm1
-               vortrd(ji,jj,jpvor_bev) = (    zvbet(ji+1,jj) - zvbet(ji,jj)     &
-                  &                       - ( zubet(ji,jj+1) - zubet(ji,jj) ) ) / ( e1f(ji,jj) * e2f(ji,jj) )
-            END DO
-         END DO
-
-         ! Average on the Curl
-         vortrd(:,:,jpvor_bev) = vortrd(:,:,jpvor_bev) * hur(:,:)
-
-         ! Surface mask
-         vortrd(:,:,jpvor_bev) = vortrd(:,:,jpvor_bev) * fmask(:,:,1)
-      ENDIF
    
       IF( ndebug /= 0 ) THEN
@@ -278,5 +313,5 @@
 
 
-   SUBROUTINE trd_vor( kt )
+   SUBROUTINE trd_vor_iom( kt )
       !!----------------------------------------------------------------------
       !!                  ***  ROUTINE trd_vor  ***
@@ -285,6 +320,5 @@
       !!               and make outputs (NetCDF or DIMG format)
       !!----------------------------------------------------------------------
-      !
-      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      INTEGER                   , INTENT(in   ) ::   kt             ! time step
       !
       INTEGER  ::   ji, jj, jk, jl   ! dummy loop indices
@@ -305,9 +339,4 @@
 
       IF( kt > nit000 )   vor_avrb(:,:) = vor_avr(:,:)
-
-      IF( ndebug /= 0 ) THEN
-          WRITE(numout,*) ' debuging trd_vor: I.1 done '
-          CALL FLUSH(numout)
-      ENDIF
 
       ! I.2 vertically integrated vorticity
@@ -330,6 +359,6 @@
 
       ! Curl
-      DO ji=1,jpim1
-         DO jj=1,jpjm1
+      DO ji = 1, jpim1
+         DO jj = 1, jpjm1
             vor_avr(ji,jj) = (  ( zvn(ji+1,jj) - zvn(ji,jj) )    &
                &              - ( zun(ji,jj+1) - zun(ji,jj) ) ) / ( e1f(ji,jj) * e2f(ji,jj) ) * fmask(ji,jj,1)
@@ -337,9 +366,4 @@
       END DO
       
-      IF( ndebug /= 0 ) THEN
-         WRITE(numout,*) ' debuging trd_vor: I.2 done'
-         CALL FLUSH(numout)
-      ENDIF
-
       !  =================================
       !   II. Cumulated trends
@@ -351,9 +375,4 @@
          vor_avrbb(:,:) = vor_avrb(:,:)
          vor_avrbn(:,:) = vor_avr (:,:)
-      ENDIF
-
-      IF( ndebug /= 0 ) THEN
-         WRITE(numout,*) ' debuging trd_vor: I1.1 done'
-         CALL FLUSH(numout)
       ENDIF
 
@@ -371,9 +390,4 @@
       ENDIF
 
-      IF( ndebug /= 0 ) THEN
-         WRITE(numout,*) ' debuging trd_vor: II.2 done'
-         CALL FLUSH(numout)
-      ENDIF
-
       !  =============================================
       !   III. Output in netCDF + residual computation
@@ -391,9 +405,4 @@
          vor_avrtot(:,:) = (  vor_avr(:,:) - vor_avrbn(:,:) + vor_avrb(:,:) - vor_avrbb(:,:) ) * zmean
 
-         IF( ndebug /= 0 ) THEN
-             WRITE(numout,*) ' zmean = ',zmean
-             WRITE(numout,*) ' debuging trd_vor: III.1 done'
-             CALL FLUSH(numout)
-         ENDIF
 
          ! III.2 compute residual
@@ -406,8 +415,4 @@
          CALL lbc_lnk( vor_avrres, 'F', 1. )
 
-         IF( ndebug /= 0 ) THEN
-            WRITE(numout,*) ' debuging trd_vor: III.2 done'
-            CALL FLUSH(numout)
-         ENDIF
 
          ! III.3 time evolution array swap
@@ -415,9 +420,4 @@
          vor_avrbb(:,:) = vor_avrb(:,:)
          vor_avrbn(:,:) = vor_avr (:,:)
-
-         IF( ndebug /= 0 ) THEN
-            WRITE(numout,*) ' debuging trd_vor: III.3 done'
-            CALL FLUSH(numout)
-         ENDIF
          !
          nmoydpvor = 0
@@ -463,5 +463,5 @@
       CALL wrk_dealloc( jpi, jpj, zun, zvn )                                   
       !
-   END SUBROUTINE trd_vor
+   END SUBROUTINE trd_vor_iom
 
 
@@ -587,29 +587,4 @@
    END SUBROUTINE trd_vor_init
 
-#else
-   !!----------------------------------------------------------------------
-   !!   Default option :                                       Empty module
-   !!----------------------------------------------------------------------
-   INTERFACE trd_vor_zint
-      MODULE PROCEDURE trd_vor_zint_2d, trd_vor_zint_3d
-   END INTERFACE
-CONTAINS
-   SUBROUTINE trd_vor( kt )        ! Empty routine
-      WRITE(*,*) 'trd_vor: You should not have seen this print! error?', kt
-   END SUBROUTINE trd_vor
-   SUBROUTINE trd_vor_zint_2d( putrdvor, pvtrdvor, ktrd )
-      REAL, DIMENSION(:,:), INTENT( inout ) ::   putrdvor, pvtrdvor
-      INTEGER, INTENT( in ) ::   ktrd         ! ocean trend index
-      WRITE(*,*) 'trd_vor_zint_2d: You should not have seen this print! error?', putrdvor(1,1), pvtrdvor(1,1), ktrd
-   END SUBROUTINE trd_vor_zint_2d
-   SUBROUTINE trd_vor_zint_3d( putrdvor, pvtrdvor, ktrd )
-      REAL, DIMENSION(:,:,:), INTENT( inout ) ::   putrdvor, pvtrdvor
-      INTEGER, INTENT( in ) ::   ktrd         ! ocean trend index
-      WRITE(*,*) 'trd_vor_zint_3d: You should not have seen this print! error?', putrdvor(1,1,1), pvtrdvor(1,1,1), ktrd
-   END SUBROUTINE trd_vor_zint_3d
-   SUBROUTINE trd_vor_init              ! Empty routine
-      WRITE(*,*) 'trd_vor_init: You should not have seen this print! error?'
-   END SUBROUTINE trd_vor_init
-#endif
    !!======================================================================
 END MODULE trdvor
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdvor_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdvor_oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/TRD/trdvor_oce.F90	(revision 5075)
@@ -4,8 +4,7 @@
    !! Ocean trends :   set vorticity trend variables
    !!======================================================================
-   !! History :  9.0  !  04-2006  (L. Brunier, A-M. Treguier) Original code 
+   !! History :  1.0  !  04-2006  (L. Brunier, A-M. Treguier) Original code 
    !!----------------------------------------------------------------------
-
-   !!----------------------------------------------------------------------
+   
    USE par_oce      ! ocean parameters
 
@@ -13,9 +12,4 @@
    PRIVATE
 
-#if defined key_trdvor
-   LOGICAL, PUBLIC, PARAMETER ::   lk_trdvor = .TRUE.    !: momentum trend flag
-#else
-   LOGICAL, PUBLIC, PARAMETER ::   lk_trdvor = .FALSE.   !: momentum trend flag
-#endif
    !                                               !!* vorticity trends index
    INTEGER, PUBLIC, PARAMETER ::   jpltot_vor = 11  !: Number of vorticity trend terms
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdf_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdf_oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdf_oce.F90	(revision 5075)
@@ -40,4 +40,5 @@
    REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   avtb_2d        !: horizontal shape of background Kz profile
    REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   bfrua, bfrva   !: Bottom friction coefficients set in zdfbfr
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:)   ::   tfrua, tfrva   !: top friction coefficients set in zdfbfr
    REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   avmu , avmv    !: vertical viscosity coef at uw- & vw-pts       [m2/s]
    REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   avm  , avt     !: vertical viscosity & diffusivity coef at w-pt [m2/s]
@@ -57,4 +58,5 @@
       ALLOCATE(avmb(jpk) , bfrua(jpi,jpj) ,                         &
          &     avtb(jpk) , bfrva(jpi,jpj) , avtb_2d(jpi,jpj) ,      &
+         &     tfrua(jpi, jpj), tfrva(jpi, jpj)              ,      &
          &     avmu(jpi,jpj,jpk), avm(jpi,jpj,jpk)           ,      &
          &     avmv(jpi,jpj,jpk), avt(jpi,jpj,jpk)           , STAT = zdf_oce_alloc )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfbfr.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfbfr.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfbfr.F90	(revision 5075)
@@ -41,8 +41,16 @@
    REAL(wp), PUBLIC ::   rn_bfrien    ! local factor to enhance coefficient bfri (PUBLIC for TAM)
    LOGICAL , PUBLIC ::   ln_bfr2d     ! logical switch for 2D enhancement (PUBLIC for TAM)
+   REAL(wp), PUBLIC ::   rn_tfri1     ! top drag coefficient (linear case)  (PUBLIC for TAM)
+   REAL(wp), PUBLIC ::   rn_tfri2     ! top drag coefficient (non linear case) (PUBLIC for TAM)
+   REAL(wp), PUBLIC ::   rn_tfri2_max ! Maximum top drag coefficient (non linear case and ln_loglayer=T) (PUBLIC for TAM)
+   REAL(wp), PUBLIC ::   rn_tfeb2     ! background top turbulent kinetic energy  [m2/s2] (PUBLIC for TAM)
+   REAL(wp), PUBLIC ::   rn_tfrien    ! local factor to enhance coefficient tfri (PUBLIC for TAM)
+   LOGICAL , PUBLIC ::   ln_tfr2d     ! logical switch for 2D enhancement (PUBLIC for TAM)
+
    LOGICAL , PUBLIC ::   ln_loglayer  ! switch for log layer bfr coeff. (PUBLIC for TAM)
    REAL(wp), PUBLIC ::   rn_bfrz0     ! bottom roughness for loglayer bfr coeff (PUBLIC for TAM)
+   REAL(wp), PUBLIC ::   rn_tfrz0     ! bottom roughness for loglayer bfr coeff (PUBLIC for TAM)
    LOGICAL , PUBLIC ::   ln_bfrimp    ! logical switch for implicit bottom friction
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::  bfrcoef2d            ! 2D bottom drag coefficient (PUBLIC for TAM)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:), PUBLIC ::  bfrcoef2d, tfrcoef2d   ! 2D bottom/top drag coefficient (PUBLIC for TAM)
 
    !! * Substitutions
@@ -60,5 +68,5 @@
       !!                ***  FUNCTION zdf_bfr_alloc  ***
       !!----------------------------------------------------------------------
-      ALLOCATE( bfrcoef2d(jpi,jpj), STAT=zdf_bfr_alloc )
+      ALLOCATE( bfrcoef2d(jpi,jpj), tfrcoef2d(jpi,jpj), STAT=zdf_bfr_alloc )
       !
       IF( lk_mpp             )   CALL mpp_sum ( zdf_bfr_alloc )
@@ -88,5 +96,5 @@
       INTEGER  ::   ikbt, ikbu, ikbv             ! local integers
       REAL(wp) ::   zvu, zuv, zecu, zecv, ztmp   ! temporary scalars
-      REAL(wp), POINTER, DIMENSION(:,:) ::  zbfrt
+      REAL(wp), POINTER, DIMENSION(:,:) ::  zbfrt, ztfrt
       !!----------------------------------------------------------------------
       !
@@ -101,23 +109,22 @@
       IF( nn_bfr == 2 ) THEN                 ! quadratic bottom friction only
          !
-         CALL wrk_alloc( jpi, jpj, zbfrt )
+         CALL wrk_alloc( jpi, jpj, zbfrt, ztfrt )
 
          IF ( ln_loglayer.AND.lk_vvl ) THEN ! "log layer" bottom friction coefficient
 
-#  if defined key_vectopt_loop
-            DO jj = 1, 1
-!CDIR NOVERRCHK
-               DO ji = 1, jpij   ! vector opt. (forced unrolling)
-#  else
-!CDIR NOVERRCHK
             DO jj = 1, jpj
-!CDIR NOVERRCHK
                DO ji = 1, jpi
-#  endif
                   ikbt = mbkt(ji,jj)
-! JC: possible WAD implementation should modify line below if layers vanish
+!! JC: possible WAD implementation should modify line below if layers vanish
                   ztmp = tmask(ji,jj,ikbt) * ( vkarmn / LOG( 0.5_wp * fse3t_n(ji,jj,ikbt) / rn_bfrz0 ))**2._wp
                   zbfrt(ji,jj) = MAX(bfrcoef2d(ji,jj), ztmp)
                   zbfrt(ji,jj) = MIN(zbfrt(ji,jj), rn_bfri2_max)
+! (ISF)
+                  ikbt = mikt(ji,jj)
+! JC: possible WAD implementation should modify line below if layers vanish
+                  ztmp = tmask(ji,jj,ikbt) * ( vkarmn / LOG( 0.5_wp * fse3t_n(ji,jj,ikbt) / rn_bfrz0 ))**2._wp
+                  ztfrt(ji,jj) = MAX(tfrcoef2d(ji,jj), ztmp)
+                  ztfrt(ji,jj) = MIN(ztfrt(ji,jj), rn_tfri2_max)
+
                END DO
             END DO
@@ -125,16 +132,9 @@
          ELSE
             zbfrt(:,:) = bfrcoef2d(:,:)
-         ENDIF
-
-# if defined key_vectopt_loop
-         DO jj = 1, 1
-!CDIR NOVERRCHK
-            DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
-# else
-!CDIR NOVERRCHK
+            ztfrt(:,:) = tfrcoef2d(:,:)
+         ENDIF
+
          DO jj = 2, jpjm1
-!CDIR NOVERRCHK
             DO ji = 2, jpim1
-# endif
                ikbu = mbku(ji,jj)         ! ocean bottom level at u- and v-points
                ikbv = mbkv(ji,jj)         ! (deepest ocean u- and v-points)
@@ -150,7 +150,44 @@
                bfrua(ji,jj) = - 0.5_wp * ( zbfrt(ji,jj) + zbfrt(ji+1,jj  ) ) * zecu
                bfrva(ji,jj) = - 0.5_wp * ( zbfrt(ji,jj) + zbfrt(ji  ,jj+1) ) * zecv
+               !
+               ! in case of 2 cell water column, we assume each cell feels the top and bottom friction
+               IF ( miku(ji,jj) + 2 .GE. mbku(ji,jj) ) THEN
+                  bfrua(ji,jj) = - 0.5_wp * ( ( zbfrt(ji,jj) + zbfrt(ji+1,jj  ) )   &
+                               &            + ( ztfrt(ji,jj) + ztfrt(ji+1,jj  ) ) ) &
+                               &          * zecu * (1._wp - umask(ji,jj,1))
+               END IF
+               IF ( mikv(ji,jj) + 2 .GE. mbkv(ji,jj) ) THEN
+                  bfrva(ji,jj) = - 0.5_wp * ( ( zbfrt(ji,jj) + zbfrt(ji  ,jj+1) )   &
+                               &            + ( ztfrt(ji,jj) + ztfrt(ji  ,jj+1) ) ) &
+                               &          * zecv * (1._wp - vmask(ji,jj,1))
+               END IF
+               ! (ISF) ========================================================================
+               ikbu = miku(ji,jj)         ! ocean bottom level at u- and v-points 
+               ikbv = mikv(ji,jj)         ! (deepest ocean u- and v-points)
+               !
+               zvu  = 0.25 * (  vn(ji,jj  ,ikbu) + vn(ji+1,jj  ,ikbu)     &
+                  &           + vn(ji,jj-1,ikbu) + vn(ji+1,jj-1,ikbu)  )
+               zuv  = 0.25 * (  un(ji,jj  ,ikbv) + un(ji-1,jj  ,ikbv)     &
+                  &           + un(ji,jj+1,ikbv) + un(ji-1,jj+1,ikbv)  )
+               !
+               zecu = SQRT(  un(ji,jj,ikbu) * un(ji,jj,ikbu) + zvu*zvu + rn_bfeb2 )
+               zecv = SQRT(  vn(ji,jj,ikbv) * vn(ji,jj,ikbv) + zuv*zuv + rn_bfeb2 )
+               !
+               tfrua(ji,jj) = - 0.5_wp * ( ztfrt(ji,jj) + ztfrt(ji+1,jj  ) ) * zecu * (1._wp - umask(ji,jj,1))
+               tfrva(ji,jj) = - 0.5_wp * ( ztfrt(ji,jj) + ztfrt(ji  ,jj+1) ) * zecv * (1._wp - vmask(ji,jj,1))
+               ! (ISF) END ====================================================================
+               ! in case of 2 cell water column, we assume each cell feels the top and bottom friction
+               IF ( miku(ji,jj) + 2 .GE. mbku(ji,jj) ) THEN
+                  tfrua(ji,jj) = - 0.5_wp * ( ( ztfrt(ji,jj) + ztfrt(ji+1,jj  ) )   &
+                               &            + ( zbfrt(ji,jj) + zbfrt(ji+1,jj  ) ) ) &
+                               &          * zecu * (1._wp - umask(ji,jj,1))
+               END IF
+               IF ( mikv(ji,jj) + 2 .GE. mbkv(ji,jj) ) THEN
+                  tfrva(ji,jj) = - 0.5_wp * ( ( ztfrt(ji,jj) + ztfrt(ji  ,jj+1) )   &
+                               &            + ( zbfrt(ji,jj) + zbfrt(ji  ,jj+1) ) ) &
+                               &          * zecv * (1._wp - vmask(ji,jj,1))
+               END IF
             END DO
          END DO
-
          !
          CALL lbc_lnk( bfrua, 'U', 1. )   ;   CALL lbc_lnk( bfrva, 'V', 1. )      ! Lateral boundary condition
@@ -158,5 +195,5 @@
          IF(ln_ctl)   CALL prt_ctl( tab2d_1=bfrua, clinfo1=' bfr  - u: ', mask1=umask,        &
             &                       tab2d_2=bfrva, clinfo2=       ' v: ', mask2=vmask,ovlap=1 )
-         CALL wrk_dealloc( jpi,jpj,zbfrt )
+         CALL wrk_dealloc( jpi,jpj,zbfrt, ztfrt )
       ENDIF
       !
@@ -183,8 +220,10 @@
       INTEGER   ::   ios
       REAL(wp)  ::   zminbfr, zmaxbfr   ! temporary scalars
+      REAL(wp)  ::   zmintfr, zmaxtfr   ! temporary scalars
       REAL(wp)  ::   ztmp, zfru, zfrv   !    -         -
       !!
       NAMELIST/nambfr/ nn_bfr, rn_bfri1, rn_bfri2, rn_bfri2_max, rn_bfeb2, rn_bfrz0, ln_bfr2d, &
-                    &  rn_bfrien, ln_bfrimp, ln_loglayer
+                    &          rn_tfri1, rn_tfri2, rn_tfri2_max, rn_tfeb2, rn_tfrz0, ln_tfr2d, &
+                    &  rn_bfrien, rn_tfrien, ln_bfrimp, ln_loglayer
       !!----------------------------------------------------------------------
       !
@@ -215,11 +254,18 @@
          bfrua(:,:) = 0.e0
          bfrva(:,:) = 0.e0
+         tfrua(:,:) = 0.e0
+         tfrva(:,:) = 0.e0
          !
       CASE( 1 )
          IF(lwp) WRITE(numout,*) '      linear botton friction'
-         IF(lwp) WRITE(numout,*) '      friction coef.   rn_bfri1  = ', rn_bfri1
+         IF(lwp) WRITE(numout,*) '      bottom friction coef.   rn_bfri1  = ', rn_bfri1
          IF( ln_bfr2d ) THEN
             IF(lwp) WRITE(numout,*) '      read coef. enhancement distribution from file   ln_bfr2d  = ', ln_bfr2d
             IF(lwp) WRITE(numout,*) '      coef rn_bfri2 enhancement factor                rn_bfrien  = ',rn_bfrien
+         ENDIF
+         IF(lwp) WRITE(numout,*) '      top    friction coef.   rn_bfri1  = ', rn_bfri1
+         IF( ln_tfr2d ) THEN
+            IF(lwp) WRITE(numout,*) '      read coef. enhancement distribution from file   ln_tfr2d  = ', ln_tfr2d
+            IF(lwp) WRITE(numout,*) '      coef rn_tfri2 enhancement factor                rn_tfrien  = ',rn_tfrien
          ENDIF
          !
@@ -252,4 +298,18 @@
             IF(lwp) WRITE(numout,*) '      coef rn_bfri2 enhancement factor                rn_bfrien  = ',rn_bfrien
          ENDIF
+         IF(lwp) WRITE(numout,*) '      quadratic top    friction'
+         IF(lwp) WRITE(numout,*) '      friction coef.   rn_bfri2  = ', rn_tfri2
+         IF(lwp) WRITE(numout,*) '      Max. coef. (log case)   rn_tfri2_max  = ', rn_tfri2_max
+         IF(lwp) WRITE(numout,*) '      background tke   rn_tfeb2  = ', rn_tfeb2
+         IF(lwp) WRITE(numout,*) '      log formulation   ln_tfr2d = ', ln_loglayer
+         IF(lwp) WRITE(numout,*) '      bottom roughness  rn_tfrz0 [m] = ', rn_tfrz0
+         IF( rn_tfrz0<=0.e0 ) THEN
+            WRITE(ctmp1,*) '      bottom roughness must be strictly positive'
+            CALL ctl_stop( ctmp1 )
+         ENDIF
+         IF( ln_tfr2d ) THEN
+            IF(lwp) WRITE(numout,*) '      read coef. enhancement distribution from file   ln_tfr2d  = ', ln_tfr2d
+            IF(lwp) WRITE(numout,*) '      coef rn_tfri2 enhancement factor                rn_tfrien  = ',rn_tfrien
+         ENDIF
          !
          IF(ln_bfr2d) THEN
@@ -265,14 +325,6 @@
          !
          IF ( ln_loglayer.AND.(.NOT.lk_vvl) ) THEN ! set "log layer" bottom friction once for all
-#  if defined key_vectopt_loop
-            DO jj = 1, 1
-!CDIR NOVERRCHK
-               DO ji = 1, jpij   ! vector opt. (forced unrolling)
-#  else
-!CDIR NOVERRCHK
             DO jj = 1, jpj
-!CDIR NOVERRCHK
                DO ji = 1, jpi
-#  endif
                   ikbt = mbkt(ji,jj)
                   ztmp = tmask(ji,jj,ikbt) * ( vkarmn / LOG( 0.5_wp * fse3t_n(ji,jj,ikbt) / rn_bfrz0 ))**2._wp
@@ -308,15 +360,9 @@
       zminbfr =  1.e10_wp    ! initialise tracker for minimum of bottom friction coefficient
       zmaxbfr = -1.e10_wp    ! initialise tracker for maximum of bottom friction coefficient
-      !
-#  if defined key_vectopt_loop
-      DO jj = 1, 1
-!CDIR NOVERRCHK
-         DO ji = jpi+2, jpij-jpi-1   ! vector opt. (forced unrolling)
-#  else
-!CDIR NOVERRCHK
+      zmintfr =  1.e10_wp    ! initialise tracker for minimum of bottom friction coefficient
+      zmaxtfr = -1.e10_wp    ! initialise tracker for maximum of bottom friction coefficient
+      !
       DO jj = 2, jpjm1
-!CDIR NOVERRCHK
          DO ji = 2, jpim1
-#  endif
              ikbu = mbku(ji,jj)       ! deepest ocean level at u- and v-points
              ikbv = mbkv(ji,jj)
@@ -352,4 +398,5 @@
          WRITE(numout,*) ' Bottom friction stability check failed at ', ictv, ' V-points '
          WRITE(numout,*) ' Bottom friction coefficient now ranges from: ', zminbfr, ' to ', zmaxbfr
+         WRITE(numout,*) ' Bottom friction coefficient now ranges from: ', zmintfr, ' to ', zmaxtfr
          WRITE(numout,*) ' Bottom friction coefficient will be reduced where necessary'
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfddm.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfddm.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfddm.F90	(revision 5075)
@@ -6,5 +6,6 @@
    !! History :  OPA  ! 2000-08  (G. Madec)  double diffusive mixing
    !!   NEMO     1.0  ! 2002-06  (G. Madec)  F90: Free form and module
-   !!            3.3  !  2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
+   !!            3.3  ! 2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase
+   !!            3.6  ! 2013-04  (G. Madec, F. Roquet) zrau compute locally using interpolation of alpha & beta
    !!----------------------------------------------------------------------
 #if defined key_zdfddm   ||   defined key_esopa
@@ -18,4 +19,6 @@
    USE dom_oce         ! ocean space and time domain variables 
    USE zdf_oce         ! ocean vertical physics variables
+   USE eosbn2         ! equation of state
+   !
    USE in_out_manager  ! I/O manager
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
@@ -34,15 +37,15 @@
    LOGICAL , PUBLIC, PARAMETER ::   lk_zdfddm = .TRUE.  !: double diffusive mixing flag
 
-   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   avs    !: salinity vertical diffusivity coeff. at w-point
-   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   rrau   !: heat/salt buoyancy flux ratio
-
-   !                      !!* Namelist namzdf_ddm : double diffusive mixing *
-   REAL(wp) ::   rn_avts   ! maximum value of avs for salt fingering
-   REAL(wp) ::   rn_hsbfr  ! heat/salt buoyancy flux ratio
+   REAL(wp), PUBLIC, SAVE, ALLOCATABLE, DIMENSION(:,:,:) ::   avs   !: salinity vertical diffusivity coeff. at w-point
+
+   !                       !!* Namelist namzdf_ddm : double diffusive mixing *
+   REAL(wp) ::   rn_avts    ! maximum value of avs for salt fingering
+   REAL(wp) ::   rn_hsbfr   ! heat/salt buoyancy flux ratio
 
    !! * Substitutions
+#  include "domzgr_substitute.h90"
 #  include "vectopt_loop_substitute.h90"
    !!----------------------------------------------------------------------
-   !! NEMO/OPA 4.0 , NEMO Consortium (2011)
+   !! NEMO/OPA 3.7 , NEMO Consortium (2014)
    !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -54,6 +57,5 @@
       !!                ***  ROUTINE zdf_ddm_alloc  ***
       !!----------------------------------------------------------------------
-      ALLOCATE( avs(jpi,jpj,jpk), rrau(jpi,jpj,jpk), STAT= zdf_ddm_alloc )
-      !
+      ALLOCATE( avs(jpi,jpj,jpk) , STAT= zdf_ddm_alloc )
       IF( lk_mpp             )   CALL mpp_sum ( zdf_ddm_alloc )
       IF( zdf_ddm_alloc /= 0 )   CALL ctl_warn('zdf_ddm_alloc: failed to allocate arrays')
@@ -71,16 +73,14 @@
       !!      diffusive mixing (i.e. salt fingering and diffusive layering)
       !!      following Merryfield et al. (1999). The rate of double diffusive 
-      !!      mixing depend on the buoyancy ratio: Rrau=alpha/beta dk[T]/dk[S]
-      !!      which is computed in rn2.F
+      !!      mixing depend on the buoyancy ratio (R=alpha/beta dk[T]/dk[S]):
       !!         * salt fingering (Schmitt 1981):
-      !!      for Rrau > 1 and rn2 > 0 : zavfs = rn_avts / ( 1 + (Rrau/rn_hsbfr)^6 )
-      !!      for Rrau > 1 and rn2 > 0 : zavfs = O
-      !!      otherwise                : zavft = 0.7 zavs / Rrau
+      !!      for R > 1 and rn2 > 0 : zavfs = rn_avts / ( 1 + (R/rn_hsbfr)^6 )
+      !!      for R > 1 and rn2 > 0 : zavfs = O
+      !!      otherwise                : zavft = 0.7 zavs / R
       !!         * diffusive layering (Federov 1988):
-      !!      for 0< Rrau < 1 and rn2 > 0 : zavdt = 1.3635e-6  
-      !!                                 * exp( 4.6 exp(-0.54 (1/Rrau-1) ) )
+      !!      for 0< R < 1 and N^2 > 0 : zavdt = 1.3635e-6 * exp( 4.6 exp(-0.54 (1/R-1) ) )
       !!      otherwise                   : zavdt = 0 
-      !!      for .5 < Rrau < 1 and rn2 > 0 : zavds = zavdt (1.885 Rrau -0.85)
-      !!      for  0 < Rrau <.5 and rn2 > 0 : zavds = zavdt 0.15 Rrau      
+      !!      for .5 < R < 1 and N^2 > 0 : zavds = zavdt (1.885 R -0.85)
+      !!      for  0 < R <.5 and N^2 > 0 : zavds = zavdt 0.15 R      
       !!      otherwise                     : zavds = 0 
       !!         * update the eddy diffusivity:
@@ -96,14 +96,16 @@
       !
       INTEGER  ::   ji, jj , jk     ! dummy loop indices
-      REAL(wp) ::   zinr, zrr       ! temporary scalars
-      REAL(wp) ::   zavft, zavfs    !    -         -
-      REAL(wp) ::   zavdt, zavds    !    -         -
-      REAL(wp), POINTER, DIMENSION(:,:) ::   zmsks, zmskf, zmskd1, zmskd2, zmskd3
+      REAL(wp) ::   zaw, zbw, zrw   ! local scalars
+      REAL(wp) ::   zdt, zds
+      REAL(wp) ::   zinr, zrr       !   -      -
+      REAL(wp) ::   zavft, zavfs    !   -      -
+      REAL(wp) ::   zavdt, zavds    !   -      -
+      REAL(wp), POINTER, DIMENSION(:,:) ::   zrau, zmsks, zmskf, zmskd1, zmskd2, zmskd3
       !!----------------------------------------------------------------------
       !
       IF( nn_timing == 1 )  CALL timing_start('zdf_ddm')
       !
-      CALL wrk_alloc( jpi,jpj, zmsks, zmskf, zmskd1, zmskd2, zmskd3 )
-
+      CALL wrk_alloc( jpi,jpj, zrau, zmsks, zmskf, zmskd1, zmskd2, zmskd3 )
+      !
       !                                                ! ===============
       DO jk = 2, jpkm1                                 ! Horizontal slab
@@ -111,5 +113,20 @@
          ! Define the mask 
          ! ---------------
-         rrau(:,:,jk) = MAX( 1.e-20, rrau(:,:,jk) )         ! only retains positive value of rrau
+         DO jj = 1, jpj                                ! R=zrau = (alpha / beta) (dk[t] / dk[s])
+            DO ji = 1, jpi
+               zrw =   ( fsdepw(ji,jj,jk  ) - fsdept(ji,jj,jk) )   &
+                  &  / ( fsdept(ji,jj,jk-1) - fsdept(ji,jj,jk) ) 
+               !
+               zaw = (  rab_n(ji,jj,jk,jp_tem) * (1. - zrw) + rab_n(ji,jj,jk-1,jp_tem) * zrw  )  &
+                   &    * tmask(ji,jj,jk) * tmask(ji,jj,jk-1)
+               zbw = (  rab_n(ji,jj,jk,jp_sal) * (1. - zrw) + rab_n(ji,jj,jk-1,jp_sal) * zrw  )  &
+                   &    * tmask(ji,jj,jk) * tmask(ji,jj,jk-1)
+               !
+               zdt = zaw * ( tsn(ji,jj,jk-1,jp_tem) - tsn(ji,jj,jk,jp_tem) )
+               zds = zbw * ( tsn(ji,jj,jk-1,jp_sal) - tsn(ji,jj,jk,jp_sal) ) 
+               IF( ABS( zds) <= 1.e-20_wp )   zds = 1.e-20_wp
+               zrau(ji,jj) = MAX(  1.e-20, zdt / zds  )    ! only retains positive value of zrau
+            END DO
+         END DO
 
          DO jj = 1, jpj                                     ! indicators:
@@ -119,20 +136,20 @@
                ELSE                                       ;   zmsks(ji,jj) = 1._wp
                ENDIF
-               ! salt fingering indicator: msksf=1 if rrau>1; 0 elsewhere            
-               IF( rrau(ji,jj,jk) <= 1.          ) THEN   ;   zmskf(ji,jj) = 0._wp
+               ! salt fingering indicator: msksf=1 if R>1; 0 elsewhere            
+               IF( zrau(ji,jj) <= 1.             ) THEN   ;   zmskf(ji,jj) = 0._wp
                ELSE                                       ;   zmskf(ji,jj) = 1._wp
                ENDIF
                ! diffusive layering indicators: 
-               !     ! mskdl1=1 if 0<rrau<1; 0 elsewhere
-               IF( rrau(ji,jj,jk) >= 1.          ) THEN   ;   zmskd1(ji,jj) = 0._wp
+               !     ! mskdl1=1 if 0< R <1; 0 elsewhere
+               IF( zrau(ji,jj) >= 1.             ) THEN   ;   zmskd1(ji,jj) = 0._wp
                ELSE                                       ;   zmskd1(ji,jj) = 1._wp
                ENDIF
-               !     ! mskdl2=1 if 0<rrau<0.5; 0 elsewhere
-               IF( rrau(ji,jj,jk) >= 0.5         ) THEN   ;   zmskd2(ji,jj) = 0._wp
+               !     ! mskdl2=1 if 0< R <0.5; 0 elsewhere
+               IF( zrau(ji,jj) >= 0.5            ) THEN   ;   zmskd2(ji,jj) = 0._wp
                ELSE                                       ;   zmskd2(ji,jj) = 1._wp
                ENDIF
-               !   mskdl3=1 if 0.5<rrau<1; 0 elsewhere
-               IF( rrau(ji,jj,jk) <= 0.5 .OR. rrau(ji,jj,jk) >= 1. ) THEN   ;   zmskd3(ji,jj) = 0._wp
-               ELSE                                                         ;   zmskd3(ji,jj) = 1._wp
+               !   mskdl3=1 if 0.5< R <1; 0 elsewhere
+               IF( zrau(ji,jj) <= 0.5 .OR. zrau(ji,jj) >= 1. ) THEN   ;   zmskd3(ji,jj) = 0._wp
+               ELSE                                                   ;   zmskd3(ji,jj) = 1._wp
                ENDIF
             END DO
@@ -149,7 +166,7 @@
 !CDIR NOVERRCHK
             DO ji = 1, jpi
-               zinr = 1./rrau(ji,jj,jk)
+               zinr = 1._wp / zrau(ji,jj)
                ! salt fingering
-               zrr = rrau(ji,jj,jk)/rn_hsbfr
+               zrr = zrau(ji,jj) / rn_hsbfr
                zrr = zrr * zrr
                zavfs = rn_avts / ( 1 + zrr*zrr*zrr ) * zmsks(ji,jj) * zmskf(ji,jj)
@@ -157,6 +174,6 @@
                ! diffusive layering
                zavdt = 1.3635e-6 * EXP(  4.6 * EXP( -0.54*(zinr-1.) )  ) * zmsks(ji,jj) * zmskd1(ji,jj)
-               zavds = zavdt * zmsks(ji,jj) * (  (1.85 * rrau(ji,jj,jk) - 0.85 ) * zmskd3(ji,jj)   &
-                  &                            +  0.15 * rrau(ji,jj,jk)          * zmskd2(ji,jj)  )
+               zavds = zavdt * zmsks(ji,jj) * (  ( 1.85 * zrau(ji,jj) - 0.85 ) * zmskd3(ji,jj)   &
+                  &                             +  0.15 * zrau(ji,jj)          * zmskd2(ji,jj)  )
                ! add to the eddy viscosity coef. previously computed
                avs (ji,jj,jk) = avt(ji,jj,jk) + zavfs + zavds
@@ -196,5 +213,5 @@
       ENDIF
       !
-      CALL wrk_dealloc( jpi,jpj, zmsks, zmskf, zmskd1, zmskd2, zmskd3 )
+      CALL wrk_dealloc( jpi,jpj, zrau, zmsks, zmskf, zmskd1, zmskd2, zmskd3 )
       !
       IF( nn_timing == 1 )  CALL timing_stop('zdf_ddm')
@@ -212,6 +229,7 @@
       !!              called by zdf_ddm at the first timestep (nit000)
       !!----------------------------------------------------------------------
+      INTEGER ::   ios   ! local integer
+      !!
       NAMELIST/namzdf_ddm/ rn_avts, rn_hsbfr
-      INTEGER  ::   ios                 ! Local integer output status for namelist read
       !!----------------------------------------------------------------------
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfevd.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfevd.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfevd.F90	(revision 5075)
@@ -78,11 +78,6 @@
          !
          DO jk = 1, jpkm1 
-#if defined key_vectopt_loop
-            DO jj = 1, 1                     ! big loop forced
-               DO ji = jpi+2, jpij   
-#else
             DO jj = 2, jpj             ! no vector opt.
                DO ji = 2, jpi
-#endif
 #if defined key_zdfkpp
                   ! no evd mixing in the boundary layer with KPP
@@ -110,11 +105,6 @@
          DO jk = 1, jpkm1
 !!!         WHERE( rn2(:,:,jk) <= -1.e-12 ) avt(:,:,jk) = tmask(:,:,jk) * avevd   ! agissant sur T SEUL! 
-#if defined key_vectopt_loop
-            DO jj = 1, 1                     ! big loop forced
-               DO ji = 1, jpij   
-#else
             DO jj = 1, jpj             ! loop over the whole domain (no lbc_lnk call)
                DO ji = 1, jpi
-#endif
 #if defined key_zdfkpp
                   ! no evd mixing in the boundary layer with KPP
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfgls.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfgls.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfgls.F90	(revision 5075)
@@ -1258,4 +1258,8 @@
                en  (:,:,:) = rn_emin
                mxln(:,:,:) = 0.001        
+               avt_k (:,:,:) = avt (:,:,:)
+               avm_k (:,:,:) = avm (:,:,:)
+               avmu_k(:,:,:) = avmu(:,:,:)
+               avmv_k(:,:,:) = avmv(:,:,:)
                DO jit = nit000 + 1, nit000 + 10   ;   CALL zdf_gls( jit )   ;   END DO
             ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfini.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfini.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfini.F90	(revision 5075)
@@ -14,4 +14,5 @@
    !!----------------------------------------------------------------------
    USE par_oce         ! mesh and scale factors
+   USE sbc_oce         ! surface module (only for nn_isf in the option compatibility test)
    USE ldftra_oce      ! ocean active tracers: lateral physics
    USE ldfdyn_oce      ! ocean dynamics lateral physics
@@ -117,8 +118,14 @@
       IF( ioptio == 0 .OR. ioptio > 1 .AND. .NOT. lk_esopa )   &
          &   CALL ctl_stop( ' one and only one vertical diffusion option has to be defined ' )
+      IF( ( lk_zdfric .OR. lk_zdfgls .OR. lk_zdfkpp ) .AND. nn_isf .NE. 0 )   &
+         &   CALL ctl_stop( ' only zdfcst and zdftke were tested with ice shelves cavities ' )
       !
       !                               ! ... Convection
       IF(lwp) WRITE(numout,*)
       IF(lwp) WRITE(numout,*) '   convection :'
+      !
+      IF( ln_zdfnpc )   CALL ctl_stop( ' zdf_init: non penetrative convective scheme is not working',   &
+         &                                       ' set ln_zdfnpc to FALSE' )
+      !
       ioptio = 0
       IF( ln_zdfnpc ) THEN
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfkpp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfkpp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfkpp.F90	(revision 5075)
@@ -26,14 +26,15 @@
    USE phycst         ! physical constants
    USE eosbn2         ! equation of state
-   USE zdfddm         ! double diffusion mixing
+   USE zdfddm         ! double diffusion mixing (avs array)
+   USE lib_mpp        ! MPP library
+   USE trd_oce        ! ocean trends definition
+   USE trdtra         ! tracers trends
+   !
    USE in_out_manager ! I/O manager
-   USE lib_mpp        ! MPP library
-   USE wrk_nemo       ! work arrays
    USE lbclnk         ! ocean lateral boundary conditions (or mpp link)
    USE prtctl         ! Print control
-   USE trdmod_oce     ! ocean trends definition
-   USE trdtra         ! tracers trends
+   USE wrk_nemo       ! work arrays
    USE timing         ! Timing
-   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)  
+   USE lib_fortran    ! Fortran utilities (allows no signed zero when 'key_nosignedzero' defined)
 
    IMPLICIT NONE
@@ -246,8 +247,8 @@
       REAL(wp) ::   zdelta, zdelta2, zdzup, zdzdn, zdzh, zvath, zgat1, zdat1, zkm1m, zkm1t
 #if defined key_zdfddm
-      REAL(wp) ::   zrrau, zds, zavdds, zavddt,zinr   ! double diffusion mixing
-      REAL(wp), POINTER, DIMENSION(:,:)   ::     zdifs
+      REAL(wp) ::   zrw, zkm1s                    ! local scalars
+      REAL(wp) ::   zrrau, zdt, zds, zavdds, zavddt, zinr   ! double diffusion mixing
+      REAL(wp), POINTER, DIMENSION(:,:)   ::   zdifs
       REAL(wp), POINTER, DIMENSION(:)     ::   za2s, za3s, zkmps
-      REAL(wp) ::                            zkm1s
       REAL(wp), POINTER, DIMENSION(:,:)   ::   zblcs
       REAL(wp), POINTER, DIMENSION(:,:,:) ::   zdiffus
@@ -274,19 +275,17 @@
 #endif
 
-      zviscos(:,:,:) = 0.
-      zblcm  (:,:  ) = 0. 
-      zdiffut(:,:,:) = 0.
-      zblct  (:,:  ) = 0. 
+      zviscos(:,:,:) = 0._wp
+      zblcm  (:,:  ) = 0._wp
+      zdiffut(:,:,:) = 0._wp
+      zblct  (:,:  ) = 0._wp 
 #if defined key_zdfddm
-      zdiffus(:,:,:) = 0.
-      zblcs  (:,:  ) = 0. 
-#endif
-      ghats(:,:,:) = 0.
-     
-      zBo   (:,:) = 0.
-      zBosol(:,:) = 0.
-      zustar(:,:) = 0.
-
-
+      zdiffus(:,:,:) = 0._wp
+      zblcs  (:,:  ) = 0._wp 
+#endif
+      ghats  (:,:,:) = 0._wp
+      zBo    (:,:  ) = 0._wp
+      zBosol (:,:  ) = 0._wp
+      zustar (:,:  ) = 0._wp
+      !
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       ! I. Interior diffusivity and viscosity at w points ( T interfaces)
@@ -332,19 +331,28 @@
                   avt (ji,jj,jk) =  avt (ji,jj,jk) + rn_difri * zfri    
                ENDIF
+               !
 #if defined key_zdfddm 
-               avs (ji,jj,jk) =  avt (ji,jj,jk)              
+               !
                !  Double diffusion mixing ; NOT IN ROUTINE ZDFDDM.F90
-               ! ------------------------------------------------------------------
-               ! only retains positive value of rrau
-               zrrau = MAX( rrau(ji,jj,jk), epsln )
-               zds   = tsn(ji,jj,jk-1,jp_sal) - tsn(ji,jj,jk,jp_sal)
-               IF( zrrau > 1. .AND. zds > 0.) THEN
-                  !
-                  ! Salt fingering case.
-                  !---------------------
-                  ! Compute interior diffusivity for double diffusive mixing of
-                  ! salinity. Upper bound "zrrau" by "Rrho0"; (Rrho0=1.9, difcoefnuf=0.001).
-                  ! After that set interior diffusivity for double diffusive mixing
-                  ! of temperature
+               ! -------------------------
+               avs (ji,jj,jk) =  avt (ji,jj,jk)   
+
+               ! R=zrau = (alpha / beta) (dk[t] / dk[s])
+               zrw =   ( fsdepw(ji,jj,jk  ) - fsdept(ji,jj,jk) )   &
+                  &  / ( fsdept(ji,jj,jk-1) - fsdept(ji,jj,jk) ) 
+               !
+               zaw = (  rab_n(ji,jj,jk,jp_tem) * (1. - zrw) + rab_n(ji,jj,jk-1,jp_tem) * zrw  ) * tmask(ji,jj,jk)
+               zbw = (  rab_n(ji,jj,jk,jp_sal) * (1. - zrw) + rab_n(ji,jj,jk-1,jp_sal) * zrw  ) * tmask(ji,jj,jk)
+               !
+               zdt = zaw * ( tsn(ji,jj,jk-1,jp_tem) - tsn(ji,jj,jk,jp_tem) )
+               zds = zbw * ( tsn(ji,jj,jk-1,jp_sal) - tsn(ji,jj,jk,jp_sal) ) 
+               IF( ABS( zds) <= 1.e-20_wp )   zds = 1.e-20_wp
+               zrrau = MAX(  epsln , zdt / zds  )    ! only retains positive value of zrau
+               !
+               IF( zrrau > 1. .AND. zds > 0.) THEN                        ! Salt fingering case.
+                  !                                                       !---------------------
+                  ! Compute interior diffusivity for double diffusive mixing of salinity. 
+                  ! Upper bound "zrrau" by "Rrho0"; (Rrho0=1.9, difcoefnuf=0.001).
+                  ! After that set interior diffusivity for double diffusive mixing of temperature
                   zavdds = MIN( zrrau, Rrho0 )
                   zavdds = ( zavdds - 1.0 ) / ( Rrho0 - 1.0 )
@@ -353,18 +361,14 @@
                   zavdds = difssf * zavdds 
                   zavddt = 0.7 * zavdds
-               ELSEIF( zrrau < 1. .AND. zrrau > 0. .AND. zds < 0.) THEN
                   !
-                  ! Diffusive convection case.
-                  !---------------------------
-                  ! Compute interior diffusivity for double diffusive mixing of
-                  ! temperature (Marmorino and Caldwell, 1976); 
+               ELSEIF( zrrau < 1. .AND. zrrau > 0. .AND. zds < 0.) THEN   ! Diffusive convection case.
+                  !                                                       !---------------------------
+                  ! Compute interior diffusivity for double diffusive mixing of temperature (Marmorino and Caldwell, 1976); 
                   ! Compute interior diffusivity for double diffusive mixing of salinity 
                   zinr   = 1. / zrrau
                   zavddt = 0.909 * EXP( 4.6 * EXP( -0.54* ( zinr - 1. ) ) ) 
                   zavddt = difsdc * zavddt
-                  IF( zrrau < 0.5) THEN
-                     zavdds = zavddt * 0.15 * zrrau
-                  ELSE
-                     zavdds = zavddt * (1.85 * zrrau - 0.85 ) 
+                  IF( zrrau < 0.5) THEN   ;   zavdds = zavddt * 0.15 * zrrau
+                  ELSE                    ;   zavdds = zavddt * (1.85 * zrrau - 0.85 ) 
                   ENDIF
                ELSE
@@ -385,44 +389,10 @@
       !---------------------------------------------------------------------
       DO jj = 2, jpjm1
-         DO ji = fs_2, fs_jpim1     
-            IF( nn_eos < 1) THEN   
-               zt     = tsn(ji,jj,1,jp_tem)
-               zs     = tsn(ji,jj,1,jp_sal) - 35.0
-               zh     = fsdept(ji,jj,1)
-               !  potential volumic mass
-               zrhos  = rhop(ji,jj,1)
-               zalbet = ( ( ( - 0.255019e-07 * zt + 0.298357e-05 ) * zt   &   ! ratio alpha/beta
-                  &                               - 0.203814e-03 ) * zt   &
-                  &                               + 0.170907e-01 ) * zt   &
-                  &   + 0.665157e-01                                      &
-                  &   +     ( - 0.678662e-05 * zs                         &
-                  &           - 0.846960e-04 * zt + 0.378110e-02 ) * zs   &
-                  &   +   ( ( - 0.302285e-13 * zh                         &
-                  &           - 0.251520e-11 * zs                         &
-                  &           + 0.512857e-12 * zt * zt           ) * zh   &
-                  &           - 0.164759e-06 * zs                         &
-                  &        +(   0.791325e-08 * zt - 0.933746e-06 ) * zt   &
-                  &                               + 0.380374e-04 ) * zh
-
-               zbeta  = ( ( -0.415613e-09 * zt + 0.555579e-07 ) * zt      &   ! beta
-                  &                            - 0.301985e-05 ) * zt      &
-                  &   + 0.785567e-03                                      &
-                  &   + (     0.515032e-08 * zs                           &
-                  &         + 0.788212e-08 * zt - 0.356603e-06 ) * zs     &
-                  &   +(  (   0.121551e-17 * zh                           &
-                  &         - 0.602281e-15 * zs                           &
-                  &         - 0.175379e-14 * zt + 0.176621e-12 ) * zh     &
-                  &                             + 0.408195e-10   * zs     &
-                  &     + ( - 0.213127e-11 * zt + 0.192867e-09 ) * zt     &
-                  &                             - 0.121555e-07 ) * zh
-
-               zthermal = zbeta * zalbet / ( rcp * zrhos + epsln )
-               zhalin   = zbeta * tsn(ji,jj,1,jp_sal) * rcs
-            ELSE
-               zrhos    = rhop(ji,jj,1) + rau0 * ( 1. - tmask(ji,jj,1) )
-               zthermal = rn_alpha / ( rcp * zrhos + epsln )
-               zhalin   = rn_beta * tsn(ji,jj,1,jp_sal) * rcs
-               zbeta    = rn_beta
-            ENDIF
+         DO ji = fs_2, fs_jpim1           
+            zrhos    = rau0 * ( 1._wp + rhd(ji,jj,1) ) * tmask(ji,jj,1)
+            zthermal = rab_n(ji,jj,1,jp_tem) / ( rcp * zrhos + epsln )
+            zbeta    = rab_n(ji,jj,1,jp_sal)
+            zhalin   = zbeta * tsn(ji,jj,1,jp_sal) * rcs
+            !
             ! Radiative surface buoyancy force
             zBosol(ji,jj) = grav * zthermal * qsr(ji,jj)
@@ -435,6 +405,6 @@
             ws0(ji,jj) = - ( ( emp(ji,jj)-rnf(ji,jj) ) * tsn(ji,jj,1,jp_sal)                          &
                &             + sfx(ji,jj)                                     ) * rcs * tmask(ji,jj,1) 
-         ENDDO
-      ENDDO
+         END DO
+      END DO
 
       zflageos = 0.5 + SIGN( 0.5, nn_eos - 1. ) 
@@ -447,6 +417,6 @@
             ! Friction velocity (zustar), at T-point : LMD94 eq. 2
             zustar(ji,jj) = SQRT( taum(ji,jj) / ( zrhos +  epsln ) )
-         ENDDO
-      ENDDO
+         END DO
+      END DO
 
 !CDIR NOVERRCHK  
@@ -1270,6 +1240,6 @@
          ztrds(:,:,:) = tsa(:,:,:,jp_sal) - ztrds(:,:,:)
 !!bug gm jpttdzdf ==> jpttkpp
-         CALL trd_tra( kt, 'TRA', jp_tem, jptra_trd_zdf, ztrdt )
-         CALL trd_tra( kt, 'TRA', jp_sal, jptra_trd_zdf, ztrds )
+         CALL trd_tra( kt, 'TRA', jp_tem, jptra_zdf, ztrdt )
+         CALL trd_tra( kt, 'TRA', jp_sal, jptra_zdf, ztrds )
          DEALLOCATE( ztrdt )      ;     DEALLOCATE( ztrds )
       ENDIF
@@ -1340,5 +1310,5 @@
          IF( l_trdtrc ) THEN         ! save the non-local tracer flux trends for diagnostic
             ztrtrd(:,:,:) = tra(:,:,:,jn) - ztrtrd(:,:,:)
-            CALL trd_tra( kt, 'TRC', jn, jptra_trd_zdf, ztrtrd(:,:,:) )
+            CALL trd_tra( kt, 'TRC', jn, jptra_zdf, ztrtrd(:,:,:) )
          ENDIF
          !
@@ -1375,4 +1345,5 @@
       !!----------------------------------------------------------------------
       INTEGER  ::   ji, jj, jk     ! dummy loop indices
+      INTEGER  ::   ios            ! local integer
 #if ! defined key_kppcustom
       INTEGER  ::   jm             ! dummy loop indices     
@@ -1382,5 +1353,4 @@
       REAL(wp) ::   zustar, zucube, zustvk, zeta, zehat   ! tempory scalars
 #endif
-      INTEGER  ::   ios            ! Local integer output status for namelist read
       REAL(wp) ::   zhbf           ! tempory scalars
       LOGICAL  ::   ll_kppcustom   ! 1st ocean level taken as surface layer
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfmxl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfmxl.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdfmxl.F90	(revision 5075)
@@ -6,4 +6,6 @@
    !! History :  1.0  ! 2003-08  (G. Madec)  original code
    !!            3.2  ! 2009-07  (S. Masson, G. Madec)  IOM + merge of DO-loop
+   !!            3.7  ! 2012-03  (G. Madec)  make public the density criteria for trdmxl 
+   !!             -   ! 2014-02  (F. Roquet)  mixed layer depth calculated using N2 instead of rhop 
    !!----------------------------------------------------------------------
    !!   zdf_mxl      : Compute the turbocline and mixed layer depths.
@@ -14,4 +16,5 @@
    USE in_out_manager  ! I/O manager
    USE prtctl          ! Print control
+   USE phycst          ! physical constants
    USE iom             ! I/O library
    USE lib_mpp         ! MPP library
@@ -25,11 +28,11 @@
    PUBLIC   zdf_mxl       ! called by step.F90
 
-   REAL(wp), PUBLIC ::   rho_c = 0.01_wp    ! density criterion for mixed layer depth
-   REAL(wp), PUBLIC ::   avt_c = 5.e-4_wp   ! Kz criterion for the turbocline depth
-
    INTEGER , PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   nmln    !: number of level in the mixed layer (used by TOP)
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hmld    !: mixing layer depth (turbocline)      [m]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hmlp    !: mixed layer depth  (rho=rho0+zdcrit) [m]
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   hmlpt   !: mixed layer depth at t-points        [m]
+
+   REAL(wp), PUBLIC ::   rho_c = 0.01_wp    !: density criterion for mixed layer depth
+   REAL(wp)         ::   avt_c = 5.e-4_wp   ! Kz criterion for the turbocline depth
 
    !! * Substitutions
@@ -70,13 +73,14 @@
       !!      eddy diffusivity coefficient (resulting from the vertical physics
       !!      alone, not the isopycnal part, see trazdf.F) fall below a given
-      !!      value defined locally (avt_c here taken equal to 5 cm/s2)
+      !!      value defined locally (avt_c here taken equal to 5 cm/s2 by default)
       !!
       !! ** Action  :   nmln, hmld, hmlp, hmlpt
       !!----------------------------------------------------------------------
       INTEGER, INTENT(in) ::   kt   ! ocean time-step index
-      !!
-      INTEGER  ::   ji, jj, jk          ! dummy loop indices
-      INTEGER  ::   iikn, iiki          ! temporary integer within a do loop
-      INTEGER, POINTER, DIMENSION(:,:) ::   imld                ! temporary workspace
+      !
+      INTEGER  ::   ji, jj, jk   ! dummy loop indices
+      INTEGER  ::   iikn, iiki, ikt, imkt   ! local integer
+      REAL(wp) ::   zN2_c        ! local scalar
+      INTEGER, POINTER, DIMENSION(:,:) ::   imld   ! 2D workspace
       !!----------------------------------------------------------------------
       !
@@ -94,11 +98,24 @@
 
       ! w-level of the mixing and mixed layers
-      nmln(:,:) = mbkt(:,:) + 1        ! Initialization to the number of w ocean point
-      imld(:,:) = mbkt(:,:) + 1
-      DO jk = jpkm1, nlb10, -1         ! from the bottom to nlb10
+      nmln(:,:)  = nlb10               ! Initialization to the number of w ocean point
+      hmlp(:,:)  = 0._wp               ! here hmlp used as a dummy variable, integrating vertically N^2
+      zN2_c = grav * rho_c * r1_rau0   ! convert density criteria into N^2 criteria
+      DO jk = nlb10, jpkm1
+         DO jj = 1, jpj                ! Mixed layer level: w-level 
+            DO ji = 1, jpi
+               ikt = mbkt(ji,jj)
+               hmlp(ji,jj) = hmlp(ji,jj) + MAX( rn2b(ji,jj,jk) , 0._wp ) * fse3w(ji,jj,jk)
+               IF( hmlp(ji,jj) < zN2_c )   nmln(ji,jj) = MIN( jk , ikt ) + 1   ! Mixed layer level
+            END DO
+         END DO
+      END DO
+      !
+      ! w-level of the turbocline
+      imld(:,:) = mbkt(:,:) + 1        ! Initialization to the number of w ocean point
+      DO jk = jpkm1, nlb10, -1         ! from the bottom to nlb10 
          DO jj = 1, jpj
             DO ji = 1, jpi
-               IF( rhop(ji,jj,jk) > rhop(ji,jj,nla10) + rho_c )   nmln(ji,jj) = jk      ! Mixed layer
-               IF( avt (ji,jj,jk) < avt_c                     )   imld(ji,jj) = jk      ! Turbocline 
+               imkt = mikt(ji,jj)
+               IF( avt (ji,jj,jk) < avt_c )   imld(ji,jj) = MAX( imkt, jk )      ! Turbocline 
             END DO
          END DO
@@ -109,7 +126,8 @@
             iiki = imld(ji,jj)
             iikn = nmln(ji,jj)
-            hmld (ji,jj) = fsdepw(ji,jj,iiki  ) * tmask(ji,jj,1)    ! Turbocline depth 
-            hmlp (ji,jj) = fsdepw(ji,jj,iikn  ) * tmask(ji,jj,1)    ! Mixed layer depth
-            hmlpt(ji,jj) = fsdept(ji,jj,iikn-1)                     ! depth of the last T-point inside the mixed layer
+            imkt = mikt(ji,jj)
+            hmld (ji,jj) = ( fsdepw(ji,jj,iiki  ) - fsdepw(ji,jj,imkt )            )   * ssmask(ji,jj)    ! Turbocline depth 
+            hmlp (ji,jj) = ( fsdepw(ji,jj,iikn  ) - fsdepw(ji,jj,MAX( imkt,nla10 ) ) ) * ssmask(ji,jj)    ! Mixed layer depth
+            hmlpt(ji,jj) = ( fsdept(ji,jj,iikn-1) - fsdepw(ji,jj,imkt )            )   * ssmask(ji,jj)    ! depth of the last T-point inside the mixed layer
          END DO
       END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftke.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftke.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftke.F90	(revision 5075)
@@ -241,5 +241,9 @@
       DO jj = 2, jpjm1            ! en(1)   = rn_ebb taum / rau0  (min value rn_emin0)
          DO ji = fs_2, fs_jpim1   ! vector opt.
-            en(ji,jj,1) = MAX( rn_emin0, zbbrau * taum(ji,jj) ) * tmask(ji,jj,1)
+            IF (mikt(ji,jj) .GT. 1) THEN
+               en(ji,jj,mikt(ji,jj))=rn_emin
+            ELSE
+               en(ji,jj,1) = MAX( rn_emin0, zbbrau * taum(ji,jj) ) * tmask(ji,jj,1)
+            END IF
          END DO
       END DO
@@ -291,20 +295,12 @@
          END DO
          !                               ! finite LC depth
-# if defined key_vectopt_loop
-         DO jj = 1, 1
-            DO ji = 1, jpij   ! vector opt. (forced unrolling)
-# else
          DO jj = 1, jpj 
             DO ji = 1, jpi
-# endif
                zhlc(ji,jj) = fsdepw(ji,jj,imlc(ji,jj))
             END DO
          END DO
          zcof = 0.016 / SQRT( zrhoa * zcdrag )
-!CDIR NOVERRCHK
          DO jk = 2, jpkm1         !* TKE Langmuir circulation source term added to en
-!CDIR NOVERRCHK
             DO jj = 2, jpjm1
-!CDIR NOVERRCHK
                DO ji = fs_2, fs_jpim1   ! vector opt.
                   zus  = zcof * SQRT( taum(ji,jj) )           ! Stokes drift
@@ -342,7 +338,7 @@
       END DO
       !
-      DO jk = 2, jpkm1           !* Matrix and right hand side in en
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            DO jk = mikt(ji,jj)+1, jpkm1           !* Matrix and right hand side in en
                zcof   = zfact1 * tmask(ji,jj,jk)
                zzd_up = zcof * ( avm  (ji,jj,jk+1) + avm  (ji,jj,jk  ) )   &  ! upper diagonal
@@ -360,43 +356,26 @@
                !                                   ! right hand side in en
                en(ji,jj,jk) = en(ji,jj,jk) + rdt * (  zesh2  -   avt(ji,jj,jk) * rn2(ji,jj,jk)    &
-                  &                                 + zfact3 * dissl(ji,jj,jk) * en (ji,jj,jk)  ) * tmask(ji,jj,jk)
-            END DO
-         END DO
-      END DO
-      !                          !* Matrix inversion from level 2 (tke prescribed at level 1)
-      DO jk = 3, jpkm1                             ! First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1    ! vector opt.
+                  &                                 + zfact3 * dissl(ji,jj,jk) * en (ji,jj,jk)  ) &
+                  &                                 * tmask(ji,jj,jk) * tmask(ji,jj,jk-1)
+            END DO
+            !                          !* Matrix inversion from level 2 (tke prescribed at level 1)
+            DO jk = mikt(ji,jj)+2, jpkm1                             ! First recurrence : Dk = Dk - Lk * Uk-1 / Dk-1
                zdiag(ji,jj,jk) = zdiag(ji,jj,jk) - zd_lw(ji,jj,jk) * zd_up(ji,jj,jk-1) / zdiag(ji,jj,jk-1)
             END DO
-         END DO
-      END DO
-      DO jj = 2, jpjm1                             ! Second recurrence : Lk = RHSk - Lk / Dk-1 * Lk-1
-         DO ji = fs_2, fs_jpim1    ! vector opt.
-            zd_lw(ji,jj,2) = en(ji,jj,2) - zd_lw(ji,jj,2) * en(ji,jj,1)    ! Surface boudary conditions on tke
-         END DO
-      END DO
-      DO jk = 3, jpkm1
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1    ! vector opt.
+            ! Second recurrence : Lk = RHSk - Lk / Dk-1 * Lk-1
+            zd_lw(ji,jj,mikt(ji,jj)+1) = en(ji,jj,mikt(ji,jj)+1) - zd_lw(ji,jj,mikt(ji,jj)+1) * en(ji,jj,mikt(ji,jj))    ! Surface boudary conditions on tke
+            !
+            DO jk = mikt(ji,jj)+2, jpkm1
                zd_lw(ji,jj,jk) = en(ji,jj,jk) - zd_lw(ji,jj,jk) / zdiag(ji,jj,jk-1) *zd_lw(ji,jj,jk-1)
             END DO
-         END DO
-      END DO
-      DO jj = 2, jpjm1                             ! thrid recurrence : Ek = ( Lk - Uk * Ek+1 ) / Dk
-         DO ji = fs_2, fs_jpim1    ! vector opt.
+            !
+            ! thrid recurrence : Ek = ( Lk - Uk * Ek+1 ) / Dk
             en(ji,jj,jpkm1) = zd_lw(ji,jj,jpkm1) / zdiag(ji,jj,jpkm1)
-         END DO
-      END DO
-      DO jk = jpk-2, 2, -1
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1    ! vector opt.
+            !
+            DO jk = jpk-2, mikt(ji,jj)+1, -1
                en(ji,jj,jk) = ( zd_lw(ji,jj,jk) - zd_up(ji,jj,jk) * en(ji,jj,jk+1) ) / zdiag(ji,jj,jk)
             END DO
-         END DO
-      END DO
-      DO jk = 2, jpkm1                             ! set the minimum value of tke
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+            !
+            DO jk = mikt(ji,jj), jpkm1                             ! set the minimum value of tke
                en(ji,jj,jk) = MAX( en(ji,jj,jk), rn_emin ) * tmask(ji,jj,jk)
             END DO
@@ -412,5 +391,5 @@
                DO ji = fs_2, fs_jpim1   ! vector opt.
                   en(ji,jj,jk) = en(ji,jj,jk) + rn_efr * en(ji,jj,1) * EXP( -fsdepw(ji,jj,jk) / htau(ji,jj) )   &
-                     &                                               * ( 1._wp - fr_i(ji,jj) )  * tmask(ji,jj,jk)
+                     &                                 * ( 1._wp - fr_i(ji,jj) )  * tmask(ji,jj,jk) * tmask(ji,jj,1)
                END DO
             END DO
@@ -421,5 +400,5 @@
                jk = nmln(ji,jj)
                en(ji,jj,jk) = en(ji,jj,jk) + rn_efr * en(ji,jj,1) * EXP( -fsdepw(ji,jj,jk) / htau(ji,jj) )   &
-                  &                                               * ( 1._wp - fr_i(ji,jj) )  * tmask(ji,jj,jk)
+                  &                                 * ( 1._wp - fr_i(ji,jj) )  * tmask(ji,jj,jk) * tmask(ji,jj,1)
             END DO
          END DO
@@ -433,9 +412,9 @@
                   ztx2 = utau(ji-1,jj  ) + utau(ji,jj)
                   zty2 = vtau(ji  ,jj-1) + vtau(ji,jj)
-                  ztau = 0.5_wp * SQRT( ztx2 * ztx2 + zty2 * zty2 )    ! module of the mean stress 
+                  ztau = 0.5_wp * SQRT( ztx2 * ztx2 + zty2 * zty2 ) * tmask(ji,jj,1)    ! module of the mean stress 
                   zdif = taum(ji,jj) - ztau                            ! mean of modulus - modulus of the mean 
                   zdif = rhftau_scl * MAX( 0._wp, zdif + rhftau_add )  ! apply some modifications...
                   en(ji,jj,jk) = en(ji,jj,jk) + zbbrau * zdif * EXP( -fsdepw(ji,jj,jk) / htau(ji,jj) )   &
-                     &                                        * ( 1._wp - fr_i(ji,jj) ) * tmask(ji,jj,jk)
+                     &                        * ( 1._wp - fr_i(ji,jj) ) * tmask(ji,jj,jk) * tmask(ji,jj,jk-1) * tmask(ji,jj,1)
                END DO
             END DO
@@ -506,20 +485,33 @@
       !
       IF( ln_mxl0 ) THEN            ! surface mixing length = F(stress) : l=vkarmn*2.e5*taum/(rau0*g)
-         zraug = vkarmn * 2.e5_wp / ( rau0 * grav )
-         zmxlm(:,:,1) = MAX(  rn_mxl0,  zraug * taum(:,:)  )
-      ELSE                          ! surface set to the minimum value
-         zmxlm(:,:,1) = rn_mxl0
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1
+               IF (mikt(ji,jj) .GT. 1) THEN
+                  zmxlm(ji,jj,mikt(ji,jj)) = rmxl_min
+               ELSE
+                  zraug = vkarmn * 2.e5_wp / ( rau0 * grav )
+                  zmxlm(ji,jj,mikt(ji,jj)) = MAX( rn_mxl0, zraug * taum(ji,jj) )
+               END IF
+            END DO
+         END DO
+      ELSE 
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1                         ! surface set to the minimum value
+               zmxlm(ji,jj,mikt(ji,jj)) = MAX( tmask(ji,jj,1) * rn_mxl0, rmxl_min)
+            END DO
+         END DO
       ENDIF
       zmxlm(:,:,jpk)  = rmxl_min     ! last level set to the interior minium value
       !
 !CDIR NOVERRCHK
-      DO jk = 2, jpkm1              ! interior value : l=sqrt(2*e/n^2)
-!CDIR NOVERRCHK
-         DO jj = 2, jpjm1
-!CDIR NOVERRCHK
-            DO ji = fs_2, fs_jpim1   ! vector opt.
+      DO jj = 2, jpjm1
+!CDIR NOVERRCHK
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            !CDIR NOVERRCHK
+            DO jk = mikt(ji,jj)+1, jpkm1              ! interior value : l=sqrt(2*e/n^2)
                zrn2 = MAX( rn2(ji,jj,jk), rsmall )
                zmxlm(ji,jj,jk) = MAX(  rmxl_min,  SQRT( 2._wp * en(ji,jj,jk) / zrn2 )  )
             END DO
+            zmxld(ji,jj,mikt(ji,jj)) = zmxlm(ji,jj,mikt(ji,jj))   ! surface set to the minimum value 
          END DO
       END DO
@@ -533,8 +525,8 @@
       !
       CASE ( 0 )           ! bounded by the distance to surface and bottom
-         DO jk = 2, jpkm1
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
-                  zemxl = MIN( fsdepw(ji,jj,jk), zmxlm(ji,jj,jk),   &
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               DO jk = mikt(ji,jj)+1, jpkm1
+                  zemxl = MIN( fsdepw(ji,jj,jk) - fsdepw(ji,jj,mikt(ji,jj)), zmxlm(ji,jj,jk),   &
                   &            fsdepw(ji,jj,mbkt(ji,jj)+1) - fsdepw(ji,jj,jk) )
                   zmxlm(ji,jj,jk) = zemxl
@@ -545,7 +537,7 @@
          !
       CASE ( 1 )           ! bounded by the vertical scale factor
-         DO jk = 2, jpkm1
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               DO jk = mikt(ji,jj)+1, jpkm1
                   zemxl = MIN( fse3w(ji,jj,jk), zmxlm(ji,jj,jk) )
                   zmxlm(ji,jj,jk) = zemxl
@@ -556,14 +548,10 @@
          !
       CASE ( 2 )           ! |dk[xml]| bounded by e3t :
-         DO jk = 2, jpkm1         ! from the surface to the bottom :
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               DO jk = mikt(ji,jj)+1, jpkm1         ! from the surface to the bottom :
                   zmxlm(ji,jj,jk) = MIN( zmxlm(ji,jj,jk-1) + fse3t(ji,jj,jk-1), zmxlm(ji,jj,jk) )
                END DO
-            END DO
-         END DO
-         DO jk = jpkm1, 2, -1     ! from the bottom to the surface :
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
+               DO jk = jpkm1, mikt(ji,jj)+1, -1     ! from the bottom to the surface :
                   zemxl = MIN( zmxlm(ji,jj,jk+1) + fse3t(ji,jj,jk+1), zmxlm(ji,jj,jk) )
                   zmxlm(ji,jj,jk) = zemxl
@@ -574,14 +562,10 @@
          !
       CASE ( 3 )           ! lup and ldown, |dk[xml]| bounded by e3t :
-         DO jk = 2, jpkm1         ! from the surface to the bottom : lup
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
+         DO jj = 2, jpjm1
+            DO ji = fs_2, fs_jpim1   ! vector opt.
+               DO jk = mikt(ji,jj)+1, jpkm1         ! from the surface to the bottom : lup
                   zmxld(ji,jj,jk) = MIN( zmxld(ji,jj,jk-1) + fse3t(ji,jj,jk-1), zmxlm(ji,jj,jk) )
                END DO
-            END DO
-         END DO
-         DO jk = jpkm1, 2, -1     ! from the bottom to the surface : ldown
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
+               DO jk = jpkm1, mikt(ji,jj)+1, -1     ! from the bottom to the surface : ldown
                   zmxlm(ji,jj,jk) = MIN( zmxlm(ji,jj,jk+1) + fse3t(ji,jj,jk+1), zmxlm(ji,jj,jk) )
                END DO
@@ -628,18 +612,20 @@
       CALL lbc_lnk( avm, 'W', 1. )      ! Lateral boundary conditions (sign unchanged)
       !
-      DO jk = 2, jpkm1            !* vertical eddy viscosity at u- and v-points
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1   ! vector opt.
+            DO jk = miku(ji,jj)+1, jpkm1            !* vertical eddy viscosity at u- and v-points
+               avmu(ji,jj,jk) = 0.5 * ( avm(ji,jj,jk) + avm(ji+1,jj  ,jk) ) * umask(ji,jj,jk)
+            END DO
+            DO jk = mikv(ji,jj)+1, jpkm1
+               avmv(ji,jj,jk) = 0.5 * ( avm(ji,jj,jk) + avm(ji  ,jj+1,jk) ) * vmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      CALL lbc_lnk( avmu, 'U', 1. )   ;   CALL lbc_lnk( avmv, 'V', 1. )      ! Lateral boundary conditions
+      !
+      IF( nn_pdl == 1 ) THEN      !* Prandtl number case: update avt
          DO jj = 2, jpjm1
             DO ji = fs_2, fs_jpim1   ! vector opt.
-               avmu(ji,jj,jk) = 0.5 * ( avm(ji,jj,jk) + avm(ji+1,jj  ,jk) ) * umask(ji,jj,jk)
-               avmv(ji,jj,jk) = 0.5 * ( avm(ji,jj,jk) + avm(ji  ,jj+1,jk) ) * vmask(ji,jj,jk)
-            END DO
-         END DO
-      END DO
-      CALL lbc_lnk( avmu, 'U', 1. )   ;   CALL lbc_lnk( avmv, 'V', 1. )      ! Lateral boundary conditions
-      !
-      IF( nn_pdl == 1 ) THEN      !* Prandtl number case: update avt
-         DO jk = 2, jpkm1
-            DO jj = 2, jpjm1
-               DO ji = fs_2, fs_jpim1   ! vector opt.
+               DO jk = mikt(ji,jj)+1, jpkm1
                   zcoef = avm(ji,jj,jk) * 2._wp * fse3w(ji,jj,jk) * fse3w(ji,jj,jk)
                   !                                          ! shear
@@ -655,6 +641,6 @@
                   avt(ji,jj,jk)   = MAX( zpdlr * avt(ji,jj,jk), avtb_2d(ji,jj) * avtb(jk) ) * tmask(ji,jj,jk)
 # if defined key_c1d
-                  e_pdl(ji,jj,jk) = zpdlr * tmask(ji,jj,jk)    ! c1d configuration : save masked Prandlt number
-                  e_ric(ji,jj,jk) = zri * tmask(ji,jj,jk)                            ! c1d config. : save Ri
+                  e_pdl(ji,jj,jk) = zpdlr * tmask(ji,jj,jk)  ! c1d configuration : save masked Prandlt number
+                  e_ric(ji,jj,jk) = zri   * tmask(ji,jj,jk)  ! c1d config. : save Ri
 # endif
               END DO
@@ -740,10 +726,8 @@
       !
       !                               !* Check of some namelist values
-      IF( nn_mxl  < 0  .OR.  nn_mxl  > 3 )   CALL ctl_stop( 'bad flag: nn_mxl is  0, 1 or 2 ' )
-      IF( nn_pdl  < 0  .OR.  nn_pdl  > 1 )   CALL ctl_stop( 'bad flag: nn_pdl is  0 or 1    ' )
-      IF( nn_htau < 0  .OR.  nn_htau > 1 )   CALL ctl_stop( 'bad flag: nn_htau is 0, 1 or 2 ' )
-#if ! key_coupled
-      IF( nn_etau == 3 )   CALL ctl_stop( 'nn_etau == 3 : HF taum only known in coupled mode' )
-#endif
+      IF( nn_mxl  < 0   .OR.  nn_mxl  > 3 )   CALL ctl_stop( 'bad flag: nn_mxl is  0, 1 or 2 ' )
+      IF( nn_pdl  < 0   .OR.  nn_pdl  > 1 )   CALL ctl_stop( 'bad flag: nn_pdl is  0 or 1    ' )
+      IF( nn_htau < 0   .OR.  nn_htau > 1 )   CALL ctl_stop( 'bad flag: nn_htau is 0, 1 or 2 ' )
+      IF( nn_etau == 3 .AND. .NOT. lk_cpl )   CALL ctl_stop( 'nn_etau == 3 : HF taum only known in coupled mode' )
 
       IF( ln_mxl0 ) THEN
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftmx.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftmx.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/ZDF/zdftmx.F90	(revision 5075)
@@ -126,5 +126,5 @@
       zkz(:,:) = 0.e0               !* Associated potential energy consummed over the whole water column
       DO jk = 2, jpkm1
-         zkz(:,:) = zkz(:,:) + fse3w(:,:,jk) * MAX( 0.e0, rn2(:,:,jk) ) * rau0 * zav_tide(:,:,jk)* tmask(:,:,jk)
+         zkz(:,:) = zkz(:,:) + fse3w(:,:,jk) * MAX( 0.e0, rn2(:,:,jk) ) * rau0 * zav_tide(:,:,jk)* tmask(:,:,jk) * tmask(:,:,jk-1)
       END DO
 
@@ -135,6 +135,10 @@
       END DO
 
-      DO jk = 2, jpkm1              !* Mutiply by zkz to recover en_tmx, BUT bound by 30/6 ==> zav_tide bound by 300 cm2/s
-         zav_tide(:,:,jk) = zav_tide(:,:,jk) * MIN( zkz(:,:), 30./6. )   !kz max = 300 cm2/s
+      DO jj = 1, jpj                !* Here zkz should be equal to en_tmx ==> multiply by en_tmx/zkz to recover en_tmx
+         DO ji = 1, jpi
+            DO jk = mikt(ji,jj)+1, jpkm1     !* Mutiply by zkz to recover en_tmx, BUT bound by 30/6 ==> zav_tide bound by 300 cm2/s
+               zav_tide(ji,jj,jk) = zav_tide(ji,jj,jk) * MIN( zkz(ji,jj), 30./6. )   !kz max = 300 cm2/s
+            END DO
+         END DO
       END DO
 
@@ -162,9 +166,16 @@
       !                          !   Update  mixing coefs  !                          
       !                          ! ----------------------- !
-      DO jk = 2, jpkm1              !* update momentum & tracer diffusivity with tidal mixing
-         avt(:,:,jk) = avt(:,:,jk) + zav_tide(:,:,jk)
-         avm(:,:,jk) = avm(:,:,jk) + zav_tide(:,:,jk)
-         DO jj = 2, jpjm1
-            DO ji = fs_2, fs_jpim1  ! vector opt.
+      DO jj = 1, jpj                !* Here zkz should be equal to en_tmx ==> multiply by en_tmx/zkz to recover en_tmx
+         DO ji = 1, jpi
+            DO jk = mikt(ji,jj)+1, jpkm1              !* update momentum & tracer diffusivity with tidal mixing
+               avt(ji,jj,jk) = avt(ji,jj,jk) + zav_tide(ji,jj,jk)
+               avm(ji,jj,jk) = avm(ji,jj,jk) + zav_tide(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+      
+      DO jj = 2, jpjm1
+         DO ji = fs_2, fs_jpim1  ! vector opt.
+            DO jk = mikt(ji,jj)+1, jpkm1              !* update momentum & tracer diffusivity with tidal mixing
                avmu(ji,jj,jk) = avmu(ji,jj,jk) + 0.5 * ( zav_tide(ji,jj,jk) + zav_tide(ji+1,jj  ,jk) ) * umask(ji,jj,jk)
                avmv(ji,jj,jk) = avmv(ji,jj,jk) + 0.5 * ( zav_tide(ji,jj,jk) + zav_tide(ji  ,jj+1,jk) ) * vmask(ji,jj,jk)
@@ -237,6 +248,6 @@
       zsum2(:,:) = 0.e0
       DO jk= 2, jpk
-         zsum1(:,:) = zsum1(:,:) + zempba_3d_1(:,:,jk) * fse3w(:,:,jk)
-         zsum2(:,:) = zsum2(:,:) + zempba_3d_2(:,:,jk) * fse3w(:,:,jk)                
+         zsum1(:,:) = zsum1(:,:) + zempba_3d_1(:,:,jk) * fse3w(:,:,jk) * tmask(:,:,jk) * tmask(:,:,jk-1)
+         zsum2(:,:) = zsum2(:,:) + zempba_3d_2(:,:,jk) * fse3w(:,:,jk) * tmask(:,:,jk) * tmask(:,:,jk-1)               
       END DO
       DO jj = 1, jpj
@@ -274,5 +285,5 @@
       zkz(:,:) = 0.e0               ! Associated potential energy consummed over the whole water column
       DO jk = 2, jpkm1
-         zkz(:,:) = zkz(:,:) + fse3w(:,:,jk) * MAX( 0.e0, rn2(:,:,jk) ) * rau0 * zavt_itf(:,:,jk) * tmask(:,:,jk)
+         zkz(:,:) = zkz(:,:) + fse3w(:,:,jk) * MAX( 0.e0, rn2(:,:,jk) ) * rau0 * zavt_itf(:,:,jk) * tmask(:,:,jk) * tmask(:,:,jk-1)
       END DO
 
@@ -284,5 +295,5 @@
 
       DO jk = 2, jpkm1              ! Mutiply by zkz to recover en_tmx, BUT bound by 30/6 ==> zavt_itf bound by 300 cm2/s
-         zavt_itf(:,:,jk) = zavt_itf(:,:,jk) * MIN( zkz(:,:), 120./10. )   ! kz max = 120 cm2/s
+         zavt_itf(:,:,jk) = zavt_itf(:,:,jk) * MIN( zkz(:,:), 120./10. ) * tmask(:,:,jk) * tmask(:,:,jk-1)   ! kz max = 120 cm2/s
       END DO
 
@@ -414,10 +425,12 @@
       ! only the energy available for mixing is taken into account,
       ! (mixing efficiency tidal dissipation efficiency)
-      en_tmx(:,:) = - rn_tfe * rn_me * ( zem2(:,:) * 1.25 + zek1(:,:) ) * tmask(:,:,1)
-
+      en_tmx(:,:) = - rn_tfe * rn_me * ( zem2(:,:) * 1.25 + zek1(:,:) ) * ssmask(:,:)
+
+!============
+!TG: Bug for VVL? Should this section be moved out of _init and be updated at every timestep?
       ! Vertical structure (az_tmx)
       DO jj = 1, jpj                ! part independent of the level
          DO ji = 1, jpi
-            zhdep(ji,jj) = fsdepw(ji,jj,mbkt(ji,jj)+1)       ! depth of the ocean
+            zhdep(ji,jj) = gdepw_0(ji,jj,mbkt(ji,jj)+1)       ! depth of the ocean
             zfact(ji,jj) = rau0 * rn_htmx * ( 1. - EXP( -zhdep(ji,jj) / rn_htmx ) )
             IF( zfact(ji,jj) /= 0 )   zfact(ji,jj) = en_tmx(ji,jj) / zfact(ji,jj)
@@ -427,8 +440,9 @@
          DO jj = 1, jpj
             DO ji = 1, jpi
-               az_tmx(ji,jj,jk) = zfact(ji,jj) * EXP( -( zhdep(ji,jj)-fsdepw(ji,jj,jk) ) / rn_htmx ) * tmask(ji,jj,jk)
-            END DO
-         END DO
-      END DO
+               az_tmx(ji,jj,jk) = zfact(ji,jj) * EXP( -( zhdep(ji,jj)-gdepw_0(ji,jj,jk) ) / rn_htmx ) * tmask(ji,jj,jk)
+            END DO
+         END DO
+      END DO
+!===========
 
       IF( nprint == 1 .AND. lwp ) THEN
@@ -443,7 +457,7 @@
          ztpc = 0.e0
          zpc(:,:,:) = MAX(rn_n2min,rn2(:,:,:)) * zav_tide(:,:,:)
-         DO jk= 2, jpkm1
-            DO jj = 1, jpj
-               DO ji = 1, jpi
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               DO jk= mikt(ji,jj)+1, jpkm1
                   ztpc = ztpc + fse3w(ji,jj,jk) * e1t(ji,jj) * e2t(ji,jj) * zpc(ji,jj,jk) * tmask(ji,jj,jk) * tmask_i(ji,jj)
                END DO
@@ -459,10 +473,10 @@
          zav_tide(:,:,:) = MIN( zav_tide(:,:,:), 60.e-4 )   
          zkz(:,:) = 0.e0
-         DO jk = 2, jpkm1
-         DO jj = 1, jpj
-            DO ji = 1, jpi
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               DO jk = mikt(ji,jj)+1, jpkm1
                zkz(ji,jj) = zkz(ji,jj) + fse3w(ji,jj,jk) * MAX( 0.e0, rn2(ji,jj,jk) ) * rau0 * zav_tide(ji,jj,jk)* tmask(ji,jj,jk)
-            END DO
-         END DO
+               END DO
+            END DO
          END DO
          ! Here zkz should be equal to en_tmx ==> multiply by en_tmx/zkz
@@ -484,6 +498,10 @@
          WRITE(numout,*) '          Min de zkz ', ztpc, ' Max = ', maxval(zkz(:,:) )
 
-         DO jk = 2, jpkm1
-            zav_tide(:,:,jk) = zav_tide(:,:,jk) * MIN( zkz(:,:), 30./6. )   !kz max = 300 cm2/s
+         DO jj = 1, jpj
+            DO ji = 1, jpi
+               DO jk = mikt(ji,jj)+1, jpkm1
+                  zav_tide(ji,jj,jk) = zav_tide(ji,jj,jk) * MIN( zkz(ji,jj), 30./6. )   !kz max = 300 cm2/s
+               END DO
+            END DO
          END DO
          ztpc = 0.e0
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/nemogcm.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/nemogcm.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/nemogcm.F90	(revision 5075)
@@ -42,5 +42,4 @@
    !!----------------------------------------------------------------------
    USE step_oce        ! module used in the ocean time stepping module
-   USE sbc_oce         ! surface boundary condition: ocean
    USE cla             ! cross land advection               (tra_cla routine)
    USE domcfg          ! domain configuration               (dom_cfg routine)
@@ -51,7 +50,7 @@
 #endif
    USE tideini         ! tidal components initialization   (tide_ini routine)
-   USE bdyini          ! open boundary cond. initialization (bdy_init routine)
-   USE bdydta          ! open boundary cond. initialization (bdy_dta_init routine)
-   USE bdytides        ! open boundary cond. initialization (bdytide_init routine)
+   USE bdyini          ! open boundary cond. setting       (bdy_init routine)
+   USE bdydta          ! open boundary cond. setting   (bdy_dta_init routine)
+   USE bdytides        ! open boundary cond. setting   (bdytide_init routine)
    USE istate          ! initial state setting          (istate_init routine)
    USE ldfdyn          ! lateral viscosity setting      (ldfdyn_init routine)
@@ -59,5 +58,5 @@
    USE zdfini          ! vertical physics setting          (zdf_init routine)
    USE phycst          ! physical constant                  (par_cst routine)
-   USE trdmod          ! momentum/tracers trends       (trd_mod_init routine)
+   USE trdini          ! dyn/tra trends initialization     (trd_init routine)
    USE asminc          ! assimilation increments     
    USE asmbkg          ! writing out state trajectory
@@ -69,9 +68,5 @@
    USE icbini          ! handle bergs, initialisation
    USE icbstp          ! handle bergs, calving, themodynamics and transport
-#if defined key_oasis3
    USE cpl_oasis3      ! OASIS3 coupling
-#elif defined key_oasis4
-   USE cpl_oasis4      ! OASIS4 coupling (not working)
-#endif
    USE c1d             ! 1D configuration
    USE step_c1d        ! Time stepping loop for the 1D configuration
@@ -86,5 +81,5 @@
    USE sbctide, ONLY: lk_tide
    USE crsini          ! initialise grid coarsening utility
-   USE lbcnfd, ONLY: isendto, nsndto ! Setup of north fold exchanges 
+   USE lbcnfd, ONLY: isendto, nsndto, nfsloop, nfeloop ! Setup of north fold exchanges 
 
    IMPLICIT NONE
@@ -121,5 +116,4 @@
       !!----------------------------------------------------------------------
       !
-
 #if defined key_agrif
       CALL Agrif_Init_Grids()      ! AGRIF: set the meshes
@@ -139,5 +133,4 @@
 # endif
 #endif
-
       ! check that all process are still there... If some process have an error,
       ! they will never enter in step and other processes will wait until the end of the cpu time!
@@ -166,5 +159,4 @@
 
          DO WHILE ( istp <= nitend .AND. nstop == 0 )
-
 #if defined key_agrif
             CALL Agrif_Step( stp )           ! AGRIF: time stepping
@@ -172,5 +164,4 @@
             CALL stp( istp )                 ! standard time stepping
 #endif
-
             istp = istp + 1
             IF( lk_mpp )   CALL mpp_max( nstop )
@@ -201,15 +192,14 @@
       !
       CALL nemo_closefile
+      !
 #if defined key_iomput
       CALL xios_finalize                ! end mpp communications with xios
-# if defined key_oasis3 || defined key_oasis4
-      CALL cpl_prism_finalize           ! end coupling and mpp communications with OASIS
-# endif
+      IF( lk_cpl ) CALL cpl_finalize    ! end coupling and mpp communications with OASIS
 #else
-# if defined key_oasis3 || defined key_oasis4
-      CALL cpl_prism_finalize           ! end coupling and mpp communications with OASIS
-# else
-      IF( lk_mpp )   CALL mppstop       ! end mpp communications
-# endif
+      IF( lk_cpl ) THEN 
+         CALL cpl_finalize              ! end coupling and mpp communications with OASIS
+      ELSE
+         IF( lk_mpp )   CALL mppstop    ! end mpp communications
+      ENDIF
 #endif
       !
@@ -227,6 +217,6 @@
       INTEGER ::   ios
       CHARACTER(len=80), DIMENSION(16) ::   cltxt
-      !!
-      NAMELIST/namctl/ ln_ctl, nn_print, nn_ictls, nn_ictle,   &
+      !
+      NAMELIST/namctl/ ln_ctl  , nn_print, nn_ictls, nn_ictle,   &
          &             nn_isplt, nn_jsplt, nn_jctls, nn_jctle,   &
          &             nn_bench, nn_timing
@@ -281,22 +271,22 @@
 #if defined key_iomput
       IF( Agrif_Root() ) THEN
-# if defined key_oasis3 || defined key_oasis4
-         CALL cpl_prism_init( ilocal_comm )      ! nemo local communicator given by oasis
-         CALL xios_initialize( "oceanx",local_comm=ilocal_comm )
-# else
-         CALL  xios_initialize( "nemo",return_comm=ilocal_comm )
-# endif
+         IF( lk_cpl ) THEN
+            CALL cpl_init( ilocal_comm )                               ! nemo local communicator given by oasis
+            CALL xios_initialize( "oceanx",local_comm=ilocal_comm )    ! send nemo communicator to xios
+         ELSE
+            CALL  xios_initialize( "nemo",return_comm=ilocal_comm )    ! nemo local communicator given by xios
+         ENDIF
       ENDIF
       narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop, ilocal_comm )   ! Nodes selection
 #else
-# if defined key_oasis3 || defined key_oasis4
-      IF( Agrif_Root() ) THEN
-         CALL cpl_prism_init( ilocal_comm )                 ! nemo local communicator given by oasis
-      ENDIF
-      narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop, ilocal_comm )   ! Nodes selection (control print return in cltxt)
-# else
-      ilocal_comm = 0
-      narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop )                 ! Nodes selection (control print return in cltxt)
-# endif
+      IF( lk_cpl ) THEN
+         IF( Agrif_Root() ) THEN
+            CALL cpl_init( ilocal_comm )                       ! nemo local communicator given by oasis
+         ENDIF
+         narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop, ilocal_comm )   ! Nodes selection (control print return in cltxt)
+      ELSE
+         ilocal_comm = 0
+         narea = mynode( cltxt, numnam_ref, numnam_cfg, numond , nstop )                ! Nodes selection (control print return in cltxt)
+      ENDIF
 #endif
       narea = narea + 1                                     ! mynode return the rank of proc (0 --> jpnij -1 )
@@ -393,8 +383,8 @@
       IF( lk_tide       )   CALL    tide_init( nit000 )    ! Initialisation of the tidal harmonics
 
-      IF( lk_bdy        )   CALL      bdy_init  ! Open boundaries initialisation
-      IF( lk_bdy        )   CALL  bdy_dta_init  ! Open boundaries initialisation of external data arrays
+      IF( lk_bdy        )   CALL     bdy_init   ! Open boundaries initialisation
+      IF( lk_bdy        )   CALL bdy_dta_init   ! Open boundaries initialisation of external data arrays
       IF( lk_bdy .AND. lk_tide )   &
-         &                  CALL  bdytide_init  ! Open boundaries initialisation of tidal harmonic forcing
+         &                  CALL bdytide_init   ! Open boundaries initialisation of tidal harmonic forcing
 
                             CALL dyn_nept_init  ! simplified form of Neptune effect
@@ -406,9 +396,6 @@
                             CALL     sbc_init   ! Forcings : surface module
       !                                         ! Vertical physics
-
                             CALL     zdf_init      ! namelist read
-
                             CALL zdf_bfr_init      ! bottom friction
-
       IF( lk_zdfric     )   CALL zdf_ric_init      ! Richardson number dependent Kz
       IF( lk_zdftke     )   CALL zdf_tke_init      ! TKE closure scheme
@@ -449,7 +436,5 @@
                             CALL     trc_init
 #endif
-      !
- 
-                                            ! Diagnostics
+      !                                     ! Diagnostics
       IF( lk_floats     )   CALL     flo_init   ! drifting Floats
       IF( lk_diaar5     )   CALL dia_ar5_init   ! ar5 diag
@@ -457,9 +442,10 @@
       IF( lk_diadct     )   CALL dia_dct_init   ! Sections tranports
                             CALL dia_hsb_init   ! heat content, salt content and volume budgets
-                            CALL trd_mod_init   ! Mixed-layer/Vorticity/Integral constraints trends
+                            CALL     trd_init   ! Mixed-layer/Vorticity/Integral constraints trends
       IF( lk_diaobs     ) THEN                  ! Observation & model comparison
                             CALL dia_obs_init            ! Initialize observational data
                             CALL dia_obs( nit000 - 1 )   ! Observation operator for restart
       ENDIF
+
       !                                     ! Assimilation increments
       IF( lk_asminc     )   CALL asm_inc_init   ! Initialize assimilation increments
@@ -568,8 +554,4 @@
       ENDIF
       !
-      IF( lk_c1d .AND. .NOT.lk_iomput )   CALL ctl_stop( 'nemo_ctl: The 1D configuration must be used ',   &
-         &                                               'with the IOM Input/Output manager. '         ,   &
-         &                                               'Compile with key_iomput enabled' )
-      !
       IF( 1_wp /= SIGN(1._wp,-0._wp)  )   CALL ctl_stop( 'nemo_ctl: The intrinsec SIGN function follows ',  &
          &                                               'f2003 standard. '                              ,  &
@@ -663,5 +645,5 @@
       !! ** Method  :
       !!----------------------------------------------------------------------
-      INTEGER, INTENT(in) :: num_pes ! The number of MPI processes we have
+      INTEGER, INTENT(in) ::   num_pes   ! The number of MPI processes we have
       !
       INTEGER, PARAMETER :: nfactmax = 20
@@ -672,9 +654,9 @@
       INTEGER, DIMENSION(nfactmax) :: ifact ! Array of factors
       !!----------------------------------------------------------------------
-
+      !
       ierr = 0
-
+      !
       CALL factorise( ifact, nfactmax, nfact, num_pes, ierr )
-
+      !
       IF( nfact <= 1 ) THEN
          WRITE (numout, *) 'WARNING: factorisation of number of PEs failed'
@@ -718,5 +700,5 @@
       INTEGER, PARAMETER :: ntest = 14
       INTEGER :: ilfax(ntest)
-
+      !
       ! lfax contains the set of allowed factors.
       data (ilfax(jl),jl=1,ntest) / 16384, 8192, 4096, 2048, 1024, 512, 256,  &
@@ -769,4 +751,5 @@
 
 #if defined key_mpp_mpi
+
    SUBROUTINE nemo_northcomms
       !!======================================================================
@@ -803,24 +786,36 @@
           !loop over the other north-fold processes to find the processes
           !managing the points belonging to the sxT-dxT range
-          DO jn = jpnij - jpni +1, jpnij
-             IF ( njmppt(jn) == njmppmax ) THEN
+  
+          DO jn = 1, jpni
                 !sxT is the first point (in the global domain) of the jn
                 !process
-                sxT = nimppt(jn)
+                sxT = nfiimpp(jn, jpnj)
                 !dxT is the last point (in the global domain) of the jn
                 !process
-                dxT = nimppt(jn) + nlcit(jn) - 1
+                dxT = nfiimpp(jn, jpnj) + nfilcit(jn, jpnj) - 1
                 IF ((sxM .gt. sxT) .AND. (sxM .lt. dxT)) THEN
                    nsndto = nsndto + 1
-                   isendto(nsndto) = jn
+                     isendto(nsndto) = jn
                 ELSEIF ((sxM .le. sxT) .AND. (dxM .ge. dxT)) THEN
                    nsndto = nsndto + 1
-                   isendto(nsndto) = jn
+                     isendto(nsndto) = jn
                 ELSEIF ((dxM .lt. dxT) .AND. (sxT .lt. dxM)) THEN
                    nsndto = nsndto + 1
-                   isendto(nsndto) = jn
+                     isendto(nsndto) = jn
                 END IF
-             END IF
           END DO
+          nfsloop = 1
+          nfeloop = nlci
+          DO jn = 2,jpni-1
+           IF(nfipproc(jn,jpnj) .eq. (narea - 1)) THEN
+              IF (nfipproc(jn - 1 ,jpnj) .eq. -1) THEN
+                 nfsloop = nldi
+              ENDIF
+              IF (nfipproc(jn + 1,jpnj) .eq. -1) THEN
+                 nfeloop = nlei
+              ENDIF
+           ENDIF
+        END DO
+
       ENDIF
       l_north_nogather = .TRUE.
@@ -831,4 +826,5 @@
    END SUBROUTINE nemo_northcomms
 #endif
+
    !!======================================================================
 END MODULE nemogcm
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/oce.F90	(revision 5075)
@@ -20,14 +20,13 @@
    !! dynamics and tracer fields                            ! before ! now    ! after  ! the after trends becomes the fields
    !! --------------------------                            ! fields ! fields ! trends ! only after tra_zdf and dyn_spg
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   ub   ,  un    , ua     !: i-horizontal velocity        [m/s]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   vb   ,  vn    , va     !: j-horizontal velocity        [m/s]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   ua_sv,  va_sv          !: Saved trends (time spliting) [m/s2]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::           wn             !: vertical velocity            [m/s]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   rotb ,  rotn           !: relative vorticity           [s-1]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   hdivb,  hdivn          !: horizontal divergence        [s-1]
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   tsb  ,  tsn            !: 4D T-S fields        [Celcius,psu] 
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   rn2b ,  rn2            !: brunt-vaisala frequency**2   [s-2]
-   !
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  tsa             !: 4D T-S trends fields & work array 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   ub   ,  un    , ua     !: i-horizontal velocity          [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   vb   ,  vn    , va     !: j-horizontal velocity          [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   ua_sv,  va_sv          !: Saved trends (time spliting)   [m/s2]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::           wn             !: vertical velocity              [m/s]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   rotb ,  rotn           !: relative vorticity             [s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   hdivb,  hdivn          !: horizontal divergence          [s-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   tsb  ,  tsn   , tsa    !: 4D T-S fields                  [Celcius,psu] 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::   rab_b,  rab_n          !: thermal/haline expansion coef. [Celcius-1,psu-1]
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)   ::   rn2b ,  rn2            !: brunt-vaisala frequency**2     [s-2]
    !
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   rhd    !: in situ density anomalie rhd=(rho-rau0)/rau0  [no units]
@@ -46,4 +45,17 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   gtsu, gtsv   !: horizontal gradient of T, S bottom u-point 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   gru , grv    !: horizontal gradient of rd at bottom u-point
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   aru , arv    
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   gzu , gzv    
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ge3ru, ge3rv   !: horizontal gradient of T, S and rd at top v-point  
+
+   !! (ISF) interpolated gradient (only used for ice shelf case) 
+   !! --------------------- 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   gtui, gtvi   !: horizontal gradient of T, S and rd at top u-point 
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   grui, grvi   !: horizontal gradient of T, S and rd at top v-point  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   arui, arvi   !: horizontal average  of rd          at top v-point  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   gzui, gzvi   !: horizontal gradient of z           at top v-point  
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   ge3rui, ge3rvi   !: horizontal gradient of T, S and rd at top v-point  
+   !! (ISF) ice load
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   riceload
 
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::   rke          !: kinetic energy
@@ -57,6 +69,6 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   snwice_fmass       !: time evolution of mass of snow+ice               [Kg/m2/s]
 
-   !! arrays related to penetration of solar fluxes to calculate the heat budget for sea ice
-   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   oatte, iatte       !: attenuation coef of the input solar flux [unitless]
+   !! Energy budget of the leads (open water embedded in sea ice)
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:)   ::   fraqsr_1lev        !: fraction of solar net radiation absorbed in the first ocean level [-]
 
    !!----------------------------------------------------------------------
@@ -81,8 +93,10 @@
          &      hdivb(jpi,jpj,jpk)      , hdivn(jpi,jpj,jpk)      ,                             &
          &      tsb  (jpi,jpj,jpk,jpts) , tsn  (jpi,jpj,jpk,jpts) , tsa(jpi,jpj,jpk,jpts) ,     &
+         &      rab_b(jpi,jpj,jpk,jpts) , rab_n(jpi,jpj,jpk,jpts) ,                             &
          &      rn2b (jpi,jpj,jpk)      , rn2  (jpi,jpj,jpk)                              , STAT=ierr(1) )
          !
       ALLOCATE(rhd (jpi,jpj,jpk) ,                                         &
          &     rhop(jpi,jpj,jpk) ,                                         &
+         &     rke(jpi,jpj,jpk)  ,                                         &
          &     sshb(jpi,jpj)     , sshn(jpi,jpj)   , ssha(jpi,jpj)   ,     &
          &     ub_b(jpi,jpj)     , un_b(jpi,jpj)   , ua_b(jpi,jpj)   ,     &
@@ -90,9 +104,18 @@
          &     spgu  (jpi,jpj)   , spgv(jpi,jpj)   ,                       &
          &     gtsu(jpi,jpj,jpts), gtsv(jpi,jpj,jpts),                     &
-         &     gru(jpi,jpj)      , grv(jpi,jpj)                      , STAT=ierr(2) )
+         &     aru(jpi,jpj)      , arv(jpi,jpj)      ,                     &
+         &     gzu(jpi,jpj)      , gzv(jpi,jpj)      ,                     &
+         &     gru(jpi,jpj)      , grv(jpi,jpj)      ,                     &
+         &     ge3ru(jpi,jpj)    , ge3rv(jpi,jpj)    ,                     &
+         &     gtui(jpi,jpj,jpts), gtvi(jpi,jpj,jpts),                     &
+         &     arui(jpi,jpj)     , arvi(jpi,jpj)     ,                     &
+         &     gzui(jpi,jpj)     , gzvi(jpi,jpj)     ,                     &
+         &     ge3rui(jpi,jpj)   , ge3rvi(jpi,jpj)   ,                     &
+         &     grui(jpi,jpj)     , grvi(jpi,jpj)     ,                     &
+         &     riceload(jpi,jpj),                             STAT=ierr(2) )
          !
       ALLOCATE( snwice_mass(jpi,jpj) , snwice_mass_b(jpi,jpj), snwice_fmass(jpi,jpj) , STAT=ierr(3) )
          !
-      ALLOCATE( iatte(jpi,jpj) , oatte(jpi,jpj) , STAT=ierr(4) )
+      ALLOCATE( fraqsr_1lev(jpi,jpj) , STAT=ierr(4) )
          !
       oce_alloc = MAXVAL( ierr )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/par_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/par_oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/par_oce.F90	(revision 5075)
@@ -94,10 +94,4 @@
 #endif
 
-#if defined key_vectopt_loop
-   LOGICAL, PUBLIC, PARAMETER ::   lk_vopt_loop = .TRUE.   !: vector optimization flag
-#else
-   LOGICAL, PUBLIC, PARAMETER ::   lk_vopt_loop = .FALSE.  !: vector optimization flag
-#endif
-
    !!----------------------------------------------------------------------
    !! NEMO/OPA 3.3 , NEMO Consortium (2010)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/step.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/step.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/step.F90	(revision 5075)
@@ -24,5 +24,6 @@
    !!             -   !  2010-10  (C. Ethe, G. Madec) reorganisation of initialisation phase + merge TRC-TRA
    !!            3.4  !  2011-04  (G. Madec, C. Ethe) Merge of dtatem and dtasal
-   !!                 !  2012-07  (J. Simeon, G. Madec. C. Ethe) Online coarsening of outputs
+   !!                 !  2012-07  (J. Simeon, G. Madec, C. Ethe) Online coarsening of outputs
+   !!            3.7  !  2014-04  (F. Roquet, G. Madec) New equations of state
    !!----------------------------------------------------------------------
 
@@ -31,4 +32,5 @@
    !!----------------------------------------------------------------------
    USE step_oce         ! time stepping definition modules
+   USE iom
 
    IMPLICIT NONE
@@ -39,7 +41,7 @@
    !! * Substitutions
 #  include "domzgr_substitute.h90"
-#  include "zdfddm_substitute.h90"
-   !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+!!gm   #  include "zdfddm_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/OPA 3.7 , NEMO Consortium (2014)
    !! $Id$
    !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -106,6 +108,9 @@
       ! Ocean physics update                (ua, va, tsa used as workspace)
       !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-                         CALL bn2( tsb, rn2b )        ! before Brunt-Vaisala frequency
-                         CALL bn2( tsn, rn2  )        ! now    Brunt-Vaisala frequency
+      !  THERMODYNAMICS
+                         CALL eos_rab( tsb, rab_b )       ! before local thermal/haline expension ratio at T-points
+                         CALL eos_rab( tsn, rab_n )       ! now    local thermal/haline expension ratio at T-points
+                         CALL bn2    ( tsb, rab_b, rn2b ) ! before Brunt-Vaisala frequency
+                         CALL bn2    ( tsn, rab_n, rn2  ) ! now    Brunt-Vaisala frequency
       !
       !  VERTICAL PHYSICS
@@ -141,6 +146,7 @@
       IF( lk_ldfslp ) THEN                            ! slope of lateral mixing
                          CALL eos( tsb, rhd, gdept_0(:,:,:) )             ! before in situ density
-         IF( ln_zps )    CALL zps_hde( kstp, jpts, tsb, gtsu, gtsv,  &    ! Partial steps: before horizontal gradient
-            &                                      rhd, gru , grv  )      ! of t, s, rd at the last ocean level
+         IF( ln_zps )    CALL zps_hde( kstp, jpts, tsb, gtsu, gtsv,  &        ! Partial steps: before horizontal gradient
+            &                                      rhd, gru , grv , aru , arv , gzu , gzv , ge3ru , ge3rv ,   &             !
+            &                               gtui, gtvi, grui, grvi, arui, arvi, gzui, gzvi, ge3rui, ge3rvi  )  ! of t, s, rd at the last ocean level
          IF( ln_traldf_grif ) THEN                           ! before slope for Griffies operator
                          CALL ldf_slp_grif( kstp )
@@ -170,7 +176,8 @@
           ! Note that the computation of vertical velocity above, hence "after" sea level
           ! is necessary to compute momentum advection for the rhs of barotropic loop:
-                                  CALL eos    ( tsn, rhd, rhop, fsdept_n(:,:,:) ) ! now in situ density for hpg computation
-          IF( ln_zps      )       CALL zps_hde( kstp, jpts, tsn, gtsu, gtsv,  &   ! zps: now hor. derivative
-                &                                          rhd, gru , grv  )      ! of t, s, rd at the last ocean level
+                            CALL eos    ( tsn, rhd, rhop, fsdept_n(:,:,:) ) ! now in situ density for hpg computation
+            IF( ln_zps )    CALL zps_hde( kstp, jpts, tsn, gtsu, gtsv,  &        ! Partial steps: before horizontal gradient
+               &                                      rhd, gru , grv , aru , arv , gzu , gzv , ge3ru , ge3rv ,   &             !
+               &                               gtui, gtvi, grui, grvi, arui, arvi, gzui, gzvi, ge3rui, ge3rvi  )  ! of t, s, rd at the last ocean level
 
                                   ua(:,:,:) = 0.e0             ! set dynamics trends to zero
@@ -203,5 +210,5 @@
       IF( lk_floats  )   CALL flo_stp( kstp )         ! drifting Floats
       IF( lk_diahth  )   CALL dia_hth( kstp )         ! Thermocline depth (20 degres isotherm depth)
-      IF( lk_diafwb  )   CALL dia_fwb( kstp )         ! Fresh water budget diagnostics
+      IF( .NOT. lk_cpl ) CALL dia_fwb( kstp )         ! Fresh water budget diagnostics
       IF( ln_diaptr  )   CALL dia_ptr( kstp )         ! Poleward TRansports diagnostics
       IF( lk_diadct  )   CALL dia_dct( kstp )         ! Transports
@@ -219,4 +226,5 @@
                          CALL trc_stp( kstp )         ! time-stepping
 #endif
+
 
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@@ -245,12 +253,13 @@
                              CALL tra_nxt( kstp )                ! tracer fields at next time step
                              CALL eos    ( tsa, rhd, rhop, fsdept_n(:,:,:) )  ! Time-filtered in situ density for hpg computation
-         IF( ln_zps      )   CALL zps_hde( kstp, jpts, tsa, gtsu, gtsv,  &    ! zps: time filtered hor. derivative
-            &                                          rhd, gru , grv  )      ! of t, s, rd at the last ocean level
-
+         IF( ln_zps      )   CALL zps_hde( kstp, jpts, tsa, gtsu, gtsv,  &        ! Partial steps: before horizontal gradient
+            &                                      rhd, gru , grv , aru , arv , gzu , gzv , ge3ru , ge3rv ,   &             !
+            &                               gtui, gtvi, grui, grvi, arui, arvi, gzui, gzvi, ge3rui, ge3rvi  )  ! of t, s, rd at the last ocean level
       ELSE                                                  ! centered hpg  (eos then time stepping)
          IF ( .NOT. lk_dynspg_ts ) THEN                     ! eos already called in time-split case
-                                CALL eos    ( tsn, rhd, rhop, fsdept_n(:,:,:) )  ! now in situ density for hpg computation
-            IF( ln_zps      )   CALL zps_hde( kstp, jpts, tsn, gtsu, gtsv,  &    ! zps: now hor. derivative
-            &                                          rhd, gru , grv  )      ! of t, s, rd at the last ocean level
+                             CALL eos    ( tsn, rhd, rhop, fsdept_n(:,:,:) )  ! now in situ density for hpg computation
+         IF( ln_zps      )   CALL zps_hde( kstp, jpts, tsn, gtsu, gtsv,  &        ! Partial steps: before horizontal gradient
+         &                                      rhd, gru , grv , aru , arv , gzu , gzv , ge3ru , ge3rv ,   &             !
+         &                               gtui, gtvi, grui, grvi, arui, arvi, gzui, gzvi, ge3rui, ge3rvi  )  ! of t, s, rd at the last ocean level
          ENDIF
          IF( ln_zdfnpc   )   CALL tra_npc( kstp )                ! update after fields by non-penetrative convection
@@ -302,5 +311,4 @@
       IF( lk_diaobs  )         CALL dia_obs( kstp )         ! obs-minus-model (assimilation) diagnostics (call after dynamics update)
 
-      IF( lrst_oce .AND. ln_diahsb )   CALL dia_hsb_rst( kstp, 'WRITE' )
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
       ! Control and restarts
@@ -314,17 +322,7 @@
                  CALL iom_close( numror )     ! close input  ocean restart file
          IF(lwm) CALL FLUSH    ( numond )     ! flush output namelist oce
-         IF(lwm) CALL FLUSH    ( numoni )     ! flush output namelist ice    
+         IF( lwm.AND.numoni /= -1 ) CALL FLUSH    ( numoni )     ! flush output namelist ice    
       ENDIF
       IF( lrst_oce         )   CALL rst_write    ( kstp )   ! write output ocean restart file
-
-      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-      ! Trends                              (ua, va, tsa used as workspace)
-      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-      IF( nstop == 0 ) THEN
-         IF( lk_trddyn     )   CALL trd_dwr( kstp )         ! trends: dynamics
-         IF( lk_trdtra     )   CALL trd_twr( kstp )         ! trends: active tracers
-         IF( lk_trdmld     )   CALL trd_mld( kstp )         ! trends: Mixed-layer
-         IF( lk_trdvor     )   CALL trd_vor( kstp )         ! trends: vorticity budget
-      ENDIF
 
       !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/step_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/step_oce.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/step_oce.F90	(revision 5075)
@@ -25,5 +25,5 @@
    USE sbcrnf           ! surface boundary condition: runoff variables
    USE sbccpl           ! surface boundary condition: coupled formulation (call send at end of step)
-   USE cpl_oasis3, ONLY : lk_cpl
+   USE sbc_oce          ! surface boundary condition: ocean
    USE sbctide          ! Tide initialisation
 
@@ -84,10 +84,4 @@
 
    USE diawri           ! Standard run outputs             (dia_wri routine)
-   USE trdicp           ! Ocean momentum/tracers trends    (trd_wri routine)
-   USE trdmld           ! mixed-layer trends               (trd_mld routine)
-   USE trdmld_rst       ! restart for mixed-layer trends
-   USE trdmod_oce       ! ocean momentum/tracers trends
-   USE trdmod           ! momentum/tracers trends
-   USE trdvor           ! vorticity budget                 (trd_vor routine)
    USE diaptr           ! poleward transports              (dia_ptr routine)
    USE diadct           ! sections transports              (dia_dct routine)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/vectopt_loop_substitute.h90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/vectopt_loop_substitute.h90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/OPA_SRC/vectopt_loop_substitute.h90	(revision 5075)
@@ -2,17 +2,17 @@
    !!                   ***  vectopt_loop_substitute  ***
    !!----------------------------------------------------------------------
-   !! ** purpose :   substitute the inner loop starting and inding indices 
-   !!      to allow unrolling of do-loop using CPP macro.
+   !! ** purpose :   substitute the inner loop start/end indices with CPP macro
+   !!                allow unrolling of do-loop (useful with vector processors)
    !!----------------------------------------------------------------------
    !!----------------------------------------------------------------------
-   !! NEMO/OPA 3.3 , NEMO Consortium (2010)
+   !! NEMO/OPA 3.7 , NEMO Consortium (2014)
    !! $Id$ 
    !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
    !!----------------------------------------------------------------------
 #if defined key_vectopt_loop
-#  define fs_2     1
-#  define fs_jpim1 jpi
+#  define   fs_2       1
+#  define   fs_jpim1   jpi
 #else
-#  define fs_2     2
-#  define fs_jpim1 jpim1
+#  define   fs_2       2
+#  define   fs_jpim1   jpim1
 #endif
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/SAS_SRC/sbcssm.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/SAS_SRC/sbcssm.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/SAS_SRC/sbcssm.F90	(revision 5075)
@@ -166,8 +166,4 @@
       !! note that we need sbc_ssm called first in sbc
       !
-      IF( ln_cpl ) THEN
-         IF( lwp ) WRITE(numout,*) 'Coupled mode not sensible with StandAlone Surface scheme'
-         ln_cpl = .FALSE.
-      ENDIF
       IF( ln_apr_dyn ) THEN
          IF( lwp ) WRITE(numout,*) 'No atmospheric gradient needed with StandAlone Surface scheme'
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/C14b/trcsms_c14b.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/C14b/trcsms_c14b.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/C14b/trcsms_c14b.F90	(revision 5075)
@@ -18,6 +18,6 @@
    USE par_trc       ! TOP parameters
    USE trc           ! TOP variables
-   USE trdmod_oce
-   USE trdmod_trc
+   USE trd_oce
+   USE trdtrc
    USE iom           ! I/O library
 
@@ -290,17 +290,17 @@
       ENDIF
       !    
-      IF( ln_diatrc ) THEN
-         IF( lk_iomput ) THEN
-            CALL iom_put( "qtrC14b"  , qtr_c14  )
-            CALL iom_put( "qintC14b" , qint_c14 )
-            CALL iom_put( "fdecay"   , zdecay   )
-          ELSE
+      IF( lk_iomput ) THEN
+        CALL iom_put( "qtrC14b"  , qtr_c14  )
+        CALL iom_put( "qintC14b" , qint_c14 )
+        CALL iom_put( "fdecay"   , zdecay   )
+      ELSE
+         IF( ln_diatrc ) THEN
             trc2d(:,:  ,jp_c14b0_2d     ) = qtr_c14 (:,:)
             trc2d(:,:  ,jp_c14b0_2d + 1 ) = qint_c14(:,:)
             trc3d(:,:,:,jp_c14b0_3d     ) = zdecay  (:,:,:)
-          ENDIF
-      ENDIF
-
-      IF( l_trdtrc )  CALL trd_mod_trc( tra(:,:,:,jpc14), jpc14, jptra_trd_sms, kt )   ! save trends
+         ENDIF
+      ENDIF
+
+      IF( l_trdtrc )  CALL trd_trc( tra(:,:,:,jpc14), jpc14, jptra_sms, kt )   ! save trends
 
       CALL wrk_dealloc( jpi, jpj,      zatmbc14 )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/C14b/trcwri_c14b.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/C14b/trcwri_c14b.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/C14b/trcwri_c14b.F90	(revision 5075)
@@ -37,9 +37,5 @@
       DO jn = jp_c14b0, jp_c14b1
          cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
-         IF( lk_vvl ) THEN
-            CALL iom_put( cltra, trn(:,:,:,jn) * fse3t_n(:,:,:) )
-         ELSE
-            CALL iom_put( cltra, trn(:,:,:,jn) )
-         ENDIF
+         CALL iom_put( cltra, trn(:,:,:,jn) )
       END DO
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/CFC/trcsms_cfc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/CFC/trcsms_cfc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/CFC/trcsms_cfc.F90	(revision 5075)
@@ -18,6 +18,6 @@
    USE par_trc       ! TOP parameters
    USE trc           ! TOP variables
-   USE trdmod_oce
-   USE trdmod_trc
+   USE trd_oce
+   USE trdtrc
    USE iom           ! I/O library
 
@@ -185,21 +185,19 @@
             CALL iom_rstput( kt, nitrst, numrtw, 'qint_'//ctrcnm(jn), qint_cfc(:,:,jn) )
          END DO
-      ENDIF
-      !                                              
-      IF( ln_diatrc ) THEN
-        !
-        IF( lk_iomput ) THEN
-           CALL iom_put( "qtrCFC11"  , qtr_cfc (:,:,1) )
-           CALL iom_put( "qintCFC11" , qint_cfc(:,:,1) )
-        ELSE
-           trc2d(:,:,jp_cfc0_2d    ) = qtr_cfc (:,:,1)
-           trc2d(:,:,jp_cfc0_2d + 1) = qint_cfc(:,:,1)
-        END IF
-        !
+      ENDIF                                            
+      !
+      IF( lk_iomput ) THEN
+         CALL iom_put( "qtrCFC11"  , qtr_cfc (:,:,1) )
+         CALL iom_put( "qintCFC11" , qint_cfc(:,:,1) )
+      ELSE
+         IF( ln_diatrc ) THEN
+            trc2d(:,:,jp_cfc0_2d    ) = qtr_cfc (:,:,1)
+            trc2d(:,:,jp_cfc0_2d + 1) = qint_cfc(:,:,1)
+         END IF
       END IF
- 
+      !
       IF( l_trdtrc ) THEN
           DO jn = jp_cfc0, jp_cfc1
-            CALL trd_mod_trc( tra(:,:,:,jn), jn, jptra_trd_sms, kt )   ! save trends
+            CALL trd_trc( tra(:,:,:,jn), jn, jptra_sms, kt )   ! save trends
           END DO
       END IF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/CFC/trcwri_cfc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/CFC/trcwri_cfc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/CFC/trcwri_cfc.F90	(revision 5075)
@@ -37,9 +37,5 @@
       DO jn = jp_cfc0, jp_cfc1
          cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
-         IF( lk_vvl ) THEN
-            CALL iom_put( cltra, trn(:,:,:,jn) * fse3t_n(:,:,:) )
-         ELSE
-            CALL iom_put( cltra, trn(:,:,:,jn) )
-         ENDIF
+         CALL iom_put( cltra, trn(:,:,:,jn) )
       END DO
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/MY_TRC/trcsms_my_trc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/MY_TRC/trcsms_my_trc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/MY_TRC/trcsms_my_trc.F90	(revision 5075)
@@ -16,6 +16,6 @@
    USE oce_trc         ! Ocean variables
    USE trc             ! TOP variables
-   USE trdmod_oce
-   USE trdmod_trc
+   USE trd_oce
+   USE trdtrc
 
    IMPLICIT NONE
@@ -65,5 +65,5 @@
           DO jn = jp_myt0, jp_myt1
             ztrmyt(:,:,:) = tra(:,:,:,jn)
-            CALL trd_mod_trc( ztrmyt, jn, jptra_trd_sms, kt )   ! save trends
+            CALL trd_trc( ztrmyt, jn, jptra_sms, kt )   ! save trends
           END DO
           CALL wrk_dealloc( jpi, jpj, jpk, ztrmyt )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/MY_TRC/trcwri_my_trc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/MY_TRC/trcwri_my_trc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/MY_TRC/trcwri_my_trc.F90	(revision 5075)
@@ -37,9 +37,5 @@
       DO jn = jp_myt0, jp_myt1
          cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
-         IF( lk_vvl ) THEN
-            CALL iom_put( cltra, trn(:,:,:,jn) * fse3t_n(:,:,:) )
-         ELSE
-            CALL iom_put( cltra, trn(:,:,:,jn) )
-         ENDIF
+         CALL iom_put( cltra, trn(:,:,:,jn) )
       END DO
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zbio.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zbio.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zbio.F90	(revision 5075)
@@ -21,6 +21,6 @@
    USE lbclnk          ! 
    USE prtctl_trc      ! Print control for debbuging
-   USE trdmod_oce
-   USE trdmod_trc
+   USE trd_oce
+   USE trdtrc
    USE iom
    
@@ -110,5 +110,5 @@
       IF( nn_timing == 1 )  CALL timing_start('p2z_bio')
       !
-      IF( ln_diatrc ) THEN
+      IF( ln_diatrc .OR. lk_iomput ) THEN
          CALL wrk_alloc( jpi, jpj,     17, zw2d )
          CALL wrk_alloc( jpi, jpj, jpk, 3, zw3d )
@@ -122,5 +122,5 @@
 
       xksi(:,:) = 0.e0        ! zooplakton closure ( fbod)
-      IF( ln_diatrc ) THEN
+      IF( ln_diatrc .OR. lk_iomput ) THEN
          zw2d  (:,:,:) = 0.e0
          zw3d(:,:,:,:) = 0.e0
@@ -239,5 +239,5 @@
                   !  trend number 17 in p2zexp
                 ENDIF
-                IF( ln_diatrc ) THEN
+                IF( ln_diatrc .OR. lk_iomput ) THEN
                   ! convert fluxes in per day
                   ze3t = fse3t(ji,jj,jk) * 86400.
@@ -360,5 +360,5 @@
                   !  trend number 17 in p2zexp 
                 ENDIF
-                IF( ln_diatrc ) THEN
+                IF( ln_diatrc .OR. lk_iomput ) THEN
                   ! convert fluxes in per day
                   ze3t = fse3t(ji,jj,jk) * 86400.
@@ -390,6 +390,5 @@
       END DO
 
-      IF( ln_diatrc ) THEN
-         !
+      IF( ln_diatrc .OR. lk_iomput ) THEN
          DO jl = 1, 17 
             CALL lbc_lnk( zw2d(:,:,jl),'T', 1. )
@@ -398,28 +397,30 @@
             CALL lbc_lnk( zw3d(:,:,:,jl),'T', 1. )
          END DO
-         IF( lk_iomput ) THEN
+      ENDIF
+      IF( lk_iomput ) THEN
             ! Save diagnostics
-            CALL iom_put( "TNO3PHY", zw2d(:,:,1) )
-            CALL iom_put( "TNH4PHY", zw2d(:,:,2) )
-            CALL iom_put( "TPHYDOM", zw2d(:,:,3) )
-            CALL iom_put( "TPHYNH4", zw2d(:,:,4) )
-            CALL iom_put( "TPHYZOO", zw2d(:,:,5) )
-            CALL iom_put( "TPHYDET", zw2d(:,:,6) )
-            CALL iom_put( "TDETZOO", zw2d(:,:,7) )
-            CALL iom_put( "TZOODET", zw2d(:,:,8) )
-            CALL iom_put( "TZOOBOD", zw2d(:,:,9) )
-            CALL iom_put( "TZOONH4", zw2d(:,:,10) )
-            CALL iom_put( "TZOODOM", zw2d(:,:,11) )
-            CALL iom_put( "TNH4NO3", zw2d(:,:,12) )
-            CALL iom_put( "TDOMNH4", zw2d(:,:,13) )
-            CALL iom_put( "TDETNH4", zw2d(:,:,14) )
-            CALL iom_put( "TPHYTOT", zw2d(:,:,15) )
-            CALL iom_put( "TZOOTOT", zw2d(:,:,16) )
-            ! 
-            CALL iom_put( "FNO3PHY", zw3d(:,:,:,1) )
-            CALL iom_put( "FNH4PHY", zw3d(:,:,:,2) )
-            CALL iom_put( "FNH4NO3", zw3d(:,:,:,3) )
-            !
-         ELSE
+        CALL iom_put( "TNO3PHY", zw2d(:,:,1) )
+        CALL iom_put( "TNH4PHY", zw2d(:,:,2) )
+        CALL iom_put( "TPHYDOM", zw2d(:,:,3) )
+        CALL iom_put( "TPHYNH4", zw2d(:,:,4) )
+        CALL iom_put( "TPHYZOO", zw2d(:,:,5) )
+        CALL iom_put( "TPHYDET", zw2d(:,:,6) )
+        CALL iom_put( "TDETZOO", zw2d(:,:,7) )
+        CALL iom_put( "TZOODET", zw2d(:,:,8) )
+        CALL iom_put( "TZOOBOD", zw2d(:,:,9) )
+        CALL iom_put( "TZOONH4", zw2d(:,:,10) )
+        CALL iom_put( "TZOODOM", zw2d(:,:,11) )
+        CALL iom_put( "TNH4NO3", zw2d(:,:,12) )
+        CALL iom_put( "TDOMNH4", zw2d(:,:,13) )
+        CALL iom_put( "TDETNH4", zw2d(:,:,14) )
+        CALL iom_put( "TPHYTOT", zw2d(:,:,15) )
+        CALL iom_put( "TZOOTOT", zw2d(:,:,16) )
+         ! 
+        CALL iom_put( "FNO3PHY", zw3d(:,:,:,1) )
+        CALL iom_put( "FNH4PHY", zw3d(:,:,:,2) )
+        CALL iom_put( "FNH4NO3", zw3d(:,:,:,3) )
+         !
+       ELSE
+          IF( ln_diatrc ) THEN
             !
             trc2d(:,:,jp_pcs0_2d    ) = zw2d(:,:,1) 
@@ -457,5 +458,5 @@
       IF( l_trdtrc ) THEN
          DO jl = jp_pcs0_trd, jp_pcs1_trd
-            CALL trd_mod_trc( trbio(:,:,:,jl), jl, kt )   ! handle the trend
+            CALL trd_trc( trbio(:,:,:,jl), jl, kt )   ! handle the trend
          END DO
       ENDIF
@@ -467,5 +468,5 @@
       ENDIF
       !
-      IF( ln_diatrc ) THEN
+      IF( ln_diatrc .OR. lk_iomput ) THEN
          CALL wrk_dealloc( jpi, jpj,     17, zw2d )
          CALL wrk_dealloc( jpi, jpj, jpk, 3, zw3d )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zexp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zexp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zexp.F90	(revision 5075)
@@ -22,6 +22,6 @@
    USE lbclnk
    USE prtctl_trc      ! Print control for debbuging
-   USE trdmod_oce
-   USE trdmod_trc
+   USE trd_oce
+   USE trdtrc
    USE iom
 
@@ -127,8 +127,8 @@
  
       ! Oa & Ek: diagnostics depending on jpdia2d !          left as example
-      IF( ln_diatrc ) THEN
-         IF( lk_iomput ) THEN   ;   CALL iom_put( "SEDPOC" , sedpocn )
-         ELSE                   ;   trc2d(:,:,jp_pcs0_2d + 18) = sedpocn(:,:)
-         ENDIF
+      IF( lk_iomput ) THEN  
+         CALL iom_put( "SEDPOC" , sedpocn )
+      ELSE
+         IF( ln_diatrc )           trc2d(:,:,jp_pcs0_2d + 18) = sedpocn(:,:)
       ENDIF
 
@@ -164,5 +164,5 @@
          ztrbio(:,:,:) = tra(:,:,:,jpno3) - ztrbio(:,:,:)
          jl = jp_pcs0_trd + 16
-         CALL trd_mod_trc( ztrbio, jl, kt )   ! handle the trend
+         CALL trd_trc( ztrbio, jl, kt )   ! handle the trend
          CALL wrk_dealloc( jpi, jpj, jpk, ztrbio )   ! temporary save of trends
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zopt.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zopt.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zopt.F90	(revision 5075)
@@ -128,5 +128,5 @@
               IF( etot(ji,jj,jk) >= zpar100(ji,jj) )   neln(ji,jj) = jk + 1 
               !                                       ! nb. this is to ensure compatibility with
-              !                                       ! nmld_trc definition in trd_mld_trc_zint
+              !                                       ! nmld_trc definition in trd_mxl_trc_zint
            END DO
          END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsed.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsed.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsed.F90	(revision 5075)
@@ -18,6 +18,6 @@
    USE sms_pisces
    USE lbclnk
-   USE trdmod_oce
-   USE trdmod_trc
+   USE trd_oce
+   USE trdtrc
    USE iom
    USE prtctl_trc      ! Print control for debbuging
@@ -108,16 +108,24 @@
       END DO
 
-      IF( ln_diatrc ) THEN 
-         CALL wrk_alloc( jpi, jpj, zw2d )
-         zw2d(:,:) =  ztra(:,:,1) * fse3t(:,:,1) * 86400.
-         DO jk = 2, jpkm1
-            zw2d(:,:) = zw2d(:,:) + ztra(:,:,jk) * fse3t(:,:,jk) * 86400.
-         END DO
-         IF( lk_iomput )  THEN
-           CALL iom_put( "TDETSED", zw2d )
-         ELSE
-           trc2d(:,:,jp_pcs0_2d + 7) = zw2d(:,:)
+      IF( lk_iomput )  THEN
+         IF( iom_use( "TDETSED" ) ) THEN
+            CALL wrk_alloc( jpi, jpj, zw2d )
+            zw2d(:,:) =  ztra(:,:,1) * fse3t(:,:,1) * 86400.
+            DO jk = 2, jpkm1
+               zw2d(:,:) = zw2d(:,:) + ztra(:,:,jk) * fse3t(:,:,jk) * 86400.
+            END DO
+            CALL iom_put( "TDETSED", zw2d )
+            CALL wrk_dealloc( jpi, jpj, zw2d )
          ENDIF
-         CALL wrk_dealloc( jpi, jpj, zw2d )
+      ELSE
+         IF( ln_diatrc ) THEN 
+            CALL wrk_alloc( jpi, jpj, zw2d )
+            zw2d(:,:) =  ztra(:,:,1) * fse3t(:,:,1) * 86400.
+            DO jk = 2, jpkm1
+               zw2d(:,:) = zw2d(:,:) + ztra(:,:,jk) * fse3t(:,:,jk) * 86400.
+            END DO
+            trc2d(:,:,jp_pcs0_2d + 7) = zw2d(:,:)
+            CALL wrk_dealloc( jpi, jpj, zw2d )
+         ENDIF
       ENDIF
       !
@@ -128,5 +136,5 @@
          ztrbio(:,:,:) = tra(:,:,:,jpdet) - ztrbio(:,:,:)
          jl = jp_pcs0_trd + 7
-         CALL trd_mod_trc( ztrbio, jl, kt )   ! handle the trend
+         CALL trd_trc( ztrbio, jl, kt )   ! handle the trend
          CALL wrk_dealloc( jpi, jpj, jpk, ztrbio )
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsms.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsms.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P2Z/p2zsms.F90	(revision 5075)
@@ -20,8 +20,8 @@
    USE p2zsed
    USE p2zexp
-   USE trdmod_oce
-   USE trdmod_trc_oce
-   USE trdmod_trc
-   USE trdmld_trc
+   USE trd_oce
+   USE trdtrc_oce
+   USE trdtrc
+   USE trdmxl_trc
 
    IMPLICIT NONE
@@ -61,9 +61,9 @@
       IF( l_trdtrc ) THEN
          DO jn = jp_pcs0, jp_pcs1
-           CALL trd_mod_trc( tra(:,:,:,jn), jn, jptra_trd_sms, kt )   ! save trends
+           CALL trd_trc( tra(:,:,:,jn), jn, jptra_sms, kt )   ! save trends
          END DO
       END IF
 
-      IF( lk_trdmld_trc )  CALL trd_mld_bio( kt )   ! trends: Mixed-layer
+      IF( lk_trdmxl_trc )  CALL trd_mxl_bio( kt )   ! trends: Mixed-layer
       !
       IF ( lwm .AND. kt == nittrc000 ) CALL FLUSH    ( numonp )     ! flush output namelist PISCES
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zfechem.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zfechem.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zfechem.F90	(revision 5075)
@@ -244,5 +244,5 @@
                ztrc   = ( trn(ji,jj,jk,jppoc) + trn(ji,jj,jk,jpgoc) + trn(ji,jj,jk,jpcal) + trn(ji,jj,jk,jpgsi) ) * 1.e6 
 #endif
-               IF( ln_dust )  zdust  = dust(ji,jj) / ( wdust * rday ) * tmask(ji,jj,jk) ! dust in kg/m2/s
+               IF( ln_dust )  zdust  = dust(ji,jj) / ( wdust / rday ) * tmask(ji,jj,jk) ! dust in kg/m2/s
                zlam1b = 3.e-5 + xlamdust * zdust + xlam1 * ztrc
                zscave = zfeequi * zlam1b * zstep
@@ -299,17 +299,15 @@
       !  Output of some diagnostics variables
       !     ---------------------------------
-      IF( ln_diatrc .AND. lk_iomput ) THEN
-         IF( jnt == nrdttrc ) THEN
-            CALL iom_put("Fe3"    , zFe3   (:,:,:)       * tmask(:,:,:) )   ! Fe3+
-            CALL iom_put("FeL1"   , zFeL1  (:,:,:)       * tmask(:,:,:) )   ! FeL1
-            CALL iom_put("TL1"    , zTL1   (:,:,:)       * tmask(:,:,:) )   ! TL1
-            CALL iom_put("Totlig" , ztotlig(:,:,:)       * tmask(:,:,:) )   ! TL
-            CALL iom_put("Biron"  , biron  (:,:,:) * 1e9 * tmask(:,:,:) )   ! biron
-            IF( ln_fechem ) THEN
-               CALL iom_put("Fe2" , zFe2   (:,:,:)       * tmask(:,:,:) )   ! Fe2+
-               CALL iom_put("FeL2", zFeL2  (:,:,:)       * tmask(:,:,:) )   ! FeL2
-               CALL iom_put("FeP" , zFeP   (:,:,:)       * tmask(:,:,:) )   ! FeP
-               CALL iom_put("TL2" , zTL2   (:,:,:)       * tmask(:,:,:) )   ! TL2
-            ENDIF
+      IF( lk_iomput .AND. jnt == nrdttrc ) THEN
+         IF( iom_use("Fe3")    )  CALL iom_put("Fe3"    , zFe3   (:,:,:)       * tmask(:,:,:) )   ! Fe3+
+         IF( iom_use("FeL1")   )  CALL iom_put("FeL1"   , zFeL1  (:,:,:)       * tmask(:,:,:) )   ! FeL1
+         IF( iom_use("TL1")    )  CALL iom_put("TL1"    , zTL1   (:,:,:)       * tmask(:,:,:) )   ! TL1
+         IF( iom_use("Totlig") )  CALL iom_put("Totlig" , ztotlig(:,:,:)       * tmask(:,:,:) )   ! TL
+         IF( iom_use("Biron")  )  CALL iom_put("Biron"  , biron  (:,:,:) * 1e9 * tmask(:,:,:) )   ! biron
+         IF( ln_fechem ) THEN
+            IF( iom_use("Fe2")  ) CALL iom_put("Fe2"    , zFe2   (:,:,:)       * tmask(:,:,:) )   ! Fe2+
+            IF( iom_use("FeL2") ) CALL iom_put("FeL2"   , zFeL2  (:,:,:)       * tmask(:,:,:) )   ! FeL2
+            IF( iom_use("FeP")  ) CALL iom_put("FeP"    , zFeP   (:,:,:)       * tmask(:,:,:) )   ! FeP
+            IF( iom_use("TL2")  ) CALL iom_put("TL2"    , zTL2   (:,:,:)       * tmask(:,:,:) )   ! TL2
          ENDIF
       ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zflx.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zflx.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zflx.F90	(revision 5075)
@@ -89,5 +89,5 @@
       REAL(wp) ::   zyr_dec, zdco2dt
       CHARACTER (len=25) :: charout
-      REAL(wp), POINTER, DIMENSION(:,:) :: zkgco2, zkgo2, zh2co3, zoflx 
+      REAL(wp), POINTER, DIMENSION(:,:) :: zkgco2, zkgo2, zh2co3, zoflx, zw2d 
       !!---------------------------------------------------------------------
       !
@@ -196,7 +196,9 @@
       END DO
 
-      t_oce_co2_flx = t_oce_co2_flx + glob_sum( oce_co2(:,:) )      ! Cumulative Total Flux of Carbon
-      t_atm_co2_flx = glob_sum( satmco2(:,:) * e1e2t(:,:) )         ! Total atmospheric pCO2
-
+      t_oce_co2_flx     = glob_sum( oce_co2(:,:) )                    !  Total Flux of Carbon
+      t_oce_co2_flx_cum = t_oce_co2_flx_cum + t_oce_co2_flx       !  Cumulative Total Flux of Carbon
+!      t_atm_co2_flx     = glob_sum( satmco2(:,:) * e1e2t(:,:) )       ! Total atmospheric pCO2
+      t_atm_co2_flx     =  atcco2      ! Total atmospheric pCO2
+ 
       IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
          WRITE(charout, FMT="('flx ')")
@@ -205,12 +207,32 @@
       ENDIF
 
-      IF( ln_diatrc ) THEN
-         IF( lk_iomput ) THEN
-            CALL iom_put( "Cflx" , oce_co2(:,:) / e1e2t(:,:) / rfact ) 
-            CALL iom_put( "Oflx" , zoflx(:,:) * 1000 * tmask(:,:,1)  )
-            CALL iom_put( "Kg"   , zkgco2(:,:) * tmask(:,:,1) )
-            CALL iom_put( "Dpco2", ( satmco2(:,:) * patm(:,:) - zh2co3(:,:) / ( chemc(:,:,1) + rtrn ) ) * tmask(:,:,1) )
-            CALL iom_put( "Dpo2" , ( atcox * patm(:,:) - trn(:,:,1,jpoxy) / ( chemc(:,:,2) + rtrn ) ) * tmask(:,:,1) )
-         ELSE
+      IF( lk_iomput ) THEN
+         CALL wrk_alloc( jpi, jpj, zw2d )  
+         IF( iom_use( "Cflx"  ) )  THEN
+            zw2d(:,:) = oce_co2(:,:) / e1e2t(:,:) / rfact
+            CALL iom_put( "Cflx"     , zw2d ) 
+         ENDIF
+         IF( iom_use( "Oflx"  ) )  THEN
+            zw2d(:,:) =  zoflx(:,:) * 1000 * tmask(:,:,1)
+            CALL iom_put( "Oflx" , zw2d )
+         ENDIF
+         IF( iom_use( "Kg"    ) )  THEN
+            zw2d(:,:) =  zkgco2(:,:) * tmask(:,:,1)
+            CALL iom_put( "Kg"   , zw2d )
+         ENDIF
+         IF( iom_use( "Dpco2" ) ) THEN
+           zw2d(:,:) = ( satmco2(:,:) * patm(:,:) - zh2co3(:,:) / ( chemc(:,:,1) + rtrn ) ) * tmask(:,:,1)
+           CALL iom_put( "Dpco2" ,  zw2d )
+         ENDIF
+         IF( iom_use( "Dpo2" ) )  THEN
+           zw2d(:,:) = ( atcox * patm(:,:) - trn(:,:,1,jpoxy) / ( chemc(:,:,2) + rtrn ) ) * tmask(:,:,1)
+           CALL iom_put( "Dpo2"  , zw2d )
+         ENDIF
+         IF( iom_use( "tcflx" ) )  CALL iom_put( "tcflx"    , t_oce_co2_flx * rfact2r )   ! molC/s
+         CALL iom_put( "tcflxcum" , t_oce_co2_flx_cum )      ! molC
+         !
+         CALL wrk_dealloc( jpi, jpj, zw2d )
+      ELSE
+         IF( ln_diatrc ) THEN
             trc2d(:,:,jp_pcs0_2d    ) = oce_co2(:,:) / e1e2t(:,:) / rfact 
             trc2d(:,:,jp_pcs0_2d + 1) = zoflx(:,:) * 1000 * tmask(:,:,1) 
@@ -290,6 +312,6 @@
       !
       oce_co2(:,:)  = 0._wp                ! Initialization of Flux of Carbon
+      t_oce_co2_flx = 0._wp
       t_atm_co2_flx = 0._wp
-      t_oce_co2_flx = 0._wp
       !
       CALL p4z_patm( nit000 )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlim.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlim.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlim.F90	(revision 5075)
@@ -187,14 +187,12 @@
       END DO
       !
-      IF( ln_diatrc .AND. lk_iomput .AND. jnt == nrdttrc ) THEN        ! save output diagnostics
-        !
-        CALL iom_put( "xfracal", xfracal(:,:,:) * tmask(:,:,:) )  ! euphotic layer deptht
-        CALL iom_put( "LNnut"  , xlimphy(:,:,:) * tmask(:,:,:) )  ! Nutrient limitation term
-        CALL iom_put( "LDnut"  , xlimdia(:,:,:) * tmask(:,:,:) )  ! Nutrient limitation term
-        CALL iom_put( "LNFe"   , xlimnfe(:,:,:) * tmask(:,:,:) )  ! Iron limitation term
-        CALL iom_put( "LDFe"   , xlimdfe(:,:,:) * tmask(:,:,:) )  ! Iron limitation term
-        !
+      !
+      IF( lk_iomput .AND. jnt == nrdttrc ) THEN        ! save output diagnostics
+        IF( iom_use( "xfracal" ) ) CALL iom_put( "xfracal", xfracal(:,:,:) * tmask(:,:,:) )  ! euphotic layer deptht
+        IF( iom_use( "LNnut"   ) ) CALL iom_put( "LNnut"  , xlimphy(:,:,:) * tmask(:,:,:) )  ! Nutrient limitation term
+        IF( iom_use( "LDnut"   ) ) CALL iom_put( "LDnut"  , xlimdia(:,:,:) * tmask(:,:,:) )  ! Nutrient limitation term
+        IF( iom_use( "LNFe"    ) ) CALL iom_put( "LNFe"   , xlimnfe(:,:,:) * tmask(:,:,:) )  ! Iron limitation term
+        IF( iom_use( "LDFe"    ) ) CALL iom_put( "LDFe"   , xlimdfe(:,:,:) * tmask(:,:,:) )  ! Iron limitation term
       ENDIF
-
       !
       IF( nn_timing == 1 )  CALL timing_stop('p4z_lim')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlys.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlys.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zlys.F90	(revision 5075)
@@ -146,18 +146,14 @@
       END DO
       !
-      IF( ln_diatrc )  THEN
-         !
-         IF( lk_iomput ) THEN
-            zrfact2 = 1.e3 * rfact2r
-            CALL iom_put( "PH"    , -1. * LOG10( hi(:,:,:) )                * tmask(:,:,:) )
-            CALL iom_put( "CO3"   ,        zco3    (:,:,:) * 1e+3           * tmask(:,:,:) )
-            CALL iom_put( "CO3sat",        aksp    (:,:,:) * 1e+3 / calcon  * tmask(:,:,:) )
-            CALL iom_put( "DCAL"  ,        zcaldiss(:,:,:) * zrfact2        * tmask(:,:,:) )
-         ELSE
-            trc3d(:,:,:,jp_pcs0_3d    ) = -1. * LOG10( hi(:,:,:) ) * tmask(:,:,:)
-            trc3d(:,:,:,jp_pcs0_3d + 1) = zco3(:,:,:)              * tmask(:,:,:)
-            trc3d(:,:,:,jp_pcs0_3d + 2) = aksp(:,:,:) / calcon     * tmask(:,:,:)
-         ENDIF
-         !
+
+      IF( lk_iomput ) THEN
+         IF( iom_use( "PH"     ) ) CALL iom_put( "PH"    , -1. * LOG10( hi(:,:,:) )          * tmask(:,:,:) )
+         IF( iom_use( "CO3"    ) ) CALL iom_put( "CO3"   , zco3(:,:,:) * 1.e+3               * tmask(:,:,:) )
+         IF( iom_use( "CO3sat" ) ) CALL iom_put( "CO3sat", aksp(:,:,:) * 1.e+3 / calcon      * tmask(:,:,:) )
+         IF( iom_use( "DCAL"   ) ) CALL iom_put( "DCAL"  , zcaldiss(:,:,:) * 1.e+3 * rfact2r * tmask(:,:,:) )
+      ELSE
+         trc3d(:,:,:,jp_pcs0_3d    ) = -1. * LOG10( hi(:,:,:) ) * tmask(:,:,:)
+         trc3d(:,:,:,jp_pcs0_3d + 1) = zco3(:,:,:)              * tmask(:,:,:)
+         trc3d(:,:,:,jp_pcs0_3d + 2) = aksp(:,:,:) / calcon     * tmask(:,:,:)
       ENDIF
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmeso.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmeso.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmeso.F90	(revision 5075)
@@ -83,6 +83,5 @@
       REAL(wp) :: zgrazfffp, zgrazfffg, zgrazffep, zgrazffeg
       CHARACTER (len=25) :: charout
-      REAL(wp) :: zrfact2
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zgrazing
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zgrazing, zw3d
 
       !!---------------------------------------------------------------------
@@ -90,5 +89,5 @@
       IF( nn_timing == 1 )  CALL timing_start('p4z_meso')
       !
-      IF( ln_diatrc .AND. lk_iomput ) THEN
+      IF( lk_iomput ) THEN
          CALL wrk_alloc( jpi, jpj, jpk, zgrazing )
          zgrazing(:,:,:) = 0._wp
@@ -163,5 +162,5 @@
               zfrac     = zproport * grazflux  * zstep * wsbio4(ji,jj,jk)      &
                &          * trn(ji,jj,jk,jpgoc) * trn(ji,jj,jk,jpmes)          &
-               &          * ( 0.1 + 3.9 * zratio2 / ( 1.**2 + zratio2 ) )
+               &          * ( 0.2 + 3.8 * zratio2 / ( 1.**2 + zratio2 ) )
               zfracfe   = zfrac * trn(ji,jj,jk,jpbfe) / (trn(ji,jj,jk,jpgoc) + rtrn)
 
@@ -186,5 +185,5 @@
 
               ! Total grazing ( grazing by microzoo is already computed in p4zmicro )
-              IF( ln_diatrc .AND. lk_iomput )  zgrazing(ji,jj,jk) = zgraztot
+              IF( lk_iomput )  zgrazing(ji,jj,jk) = zgraztot
 
               !    Mesozooplankton efficiency
@@ -249,8 +248,15 @@
       END DO
       !
-      IF( ln_diatrc .AND. lk_iomput .AND. jnt == nrdttrc ) THEN
-         zrfact2 = 1.e3 * rfact2r
-         CALL iom_put( "GRAZ2", zgrazing(:,:,:) * zrfact2 * tmask(:,:,:) )  ! Total grazing of phyto by zooplankton
-         CALL iom_put( "PCAL" , prodcal(:,:,:)  * zrfact2 * tmask(:,:,:) )  ! Calcite production
+      IF( lk_iomput .AND. jnt == nrdttrc ) THEN
+         CALL wrk_alloc( jpi, jpj, jpk, zw3d )
+         IF( iom_use( "GRAZ2" ) ) THEN
+            zw3d(:,:,:) = zgrazing(:,:,:) * 1.e+3 * rfact2r * tmask(:,:,:)  !   Total grazing of phyto by zooplankton
+            CALL iom_put( "GRAZ2", zw3d )
+         ENDIF
+         IF( iom_use( "PCAL" ) ) THEN
+            zw3d(:,:,:) = prodcal(:,:,:) * 1.e+3 * rfact2r * tmask(:,:,:)   !  Calcite production
+            CALL iom_put( "PCAL", zw3d )  
+         ENDIF
+         CALL wrk_dealloc( jpi, jpj, jpk, zw3d )
       ENDIF
       !
@@ -261,5 +267,5 @@
       ENDIF
       !
-      IF( ln_diatrc .AND. lk_iomput )  CALL wrk_dealloc( jpi, jpj, jpk, zgrazing )
+      IF( lk_iomput )  CALL wrk_dealloc( jpi, jpj, jpk, zgrazing )
       !
       IF( nn_timing == 1 )  CALL timing_stop('p4z_meso')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmicro.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmicro.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zmicro.F90	(revision 5075)
@@ -79,6 +79,5 @@
       REAL(wp) :: zgrazp, zgrazm, zgrazsd
       REAL(wp) :: zgrazmf, zgrazsf, zgrazpf
-      REAL(wp) :: zrfact2
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zgrazing
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zgrazing, zw3d
       CHARACTER (len=25) :: charout
       !!---------------------------------------------------------------------
@@ -86,5 +85,5 @@
       IF( nn_timing == 1 )  CALL timing_start('p4z_micro')
       !
-      IF( ln_diatrc .AND. lk_iomput )  CALL wrk_alloc( jpi, jpj, jpk, zgrazing )
+      IF( lk_iomput )  CALL wrk_alloc( jpi, jpj, jpk, zgrazing )
       !
       DO jk = 1, jpkm1
@@ -137,6 +136,6 @@
                !    Various remineralization and excretion terms
                !    --------------------------------------------
-               zgrasrat  = zgraztotf / ( zgraztot + rtrn )
-               zgrasratn = zgraztotn / ( zgraztot + rtrn )
+               zgrasrat  = ( zgraztotf + rtrn ) / ( zgraztot + rtrn )
+               zgrasratn = ( zgraztotn + rtrn ) / ( zgraztot + rtrn )
                zepshert  =  MIN( 1., zgrasratn, zgrasrat / ferat3)
                zepsherv  = zepshert * MIN( epsher, (1. - unass) * zgrasrat / ferat3, (1. - unass) * zgrasratn )
@@ -191,7 +190,11 @@
       END DO
       !
-      IF( ln_diatrc .AND. lk_iomput .AND. jnt == nrdttrc ) THEN
-         zrfact2 = 1.e3 * rfact2r
-         CALL iom_put( "GRAZ1" , zgrazing(:,:,:) * zrfact2 * tmask(:,:,:) )  ! Total grazing of phyto by zooplankton
+      IF( lk_iomput .AND. jnt == nrdttrc ) THEN
+         CALL wrk_alloc( jpi, jpj, jpk, zw3d )
+         IF( iom_use( "GRAZ1" ) ) THEN
+            zw3d(:,:,:) = zgrazing(:,:,:) * 1.e+3 * rfact2r * tmask(:,:,:)  !  Total grazing of phyto by zooplankton
+            CALL iom_put( "GRAZ1", zw3d )
+         ENDIF
+         CALL wrk_dealloc( jpi, jpj, jpk, zw3d )
       ENDIF
       !
@@ -202,5 +205,5 @@
       ENDIF
       !
-      IF( ln_diatrc .AND. lk_iomput )  CALL wrk_dealloc( jpi, jpj, jpk, zgrazing )
+      IF( lk_iomput )  CALL wrk_dealloc( jpi, jpj, jpk, zgrazing )
       !
       IF( nn_timing == 1 )  CALL timing_stop('p4z_micro')
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zopt.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zopt.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zopt.F90	(revision 5075)
@@ -205,5 +205,5 @@
               IF( etot(ji,jj,jk) * tmask(ji,jj,jk) >= 0.0043 * qsr(ji,jj) )  THEN
                  neln(ji,jj) = jk+1                    ! Euphotic level : 1rst T-level strictly below Euphotic layer
-                 !                                     ! nb: ensure the compatibility with nmld_trc definition in trd_mld_trc_zint
+                 !                                     ! nb: ensure the compatibility with nmld_trc definition in trd_mxl_trc_zint
                  heup(ji,jj) = fsdepw(ji,jj,jk+1)      ! Euphotic layer depth
               ENDIF
@@ -252,16 +252,14 @@
       END DO
 
-      IF( ln_diatrc ) THEN        ! save output diagnostics
-        !
-        IF( lk_iomput ) THEN
-           IF( jnt == nrdttrc ) THEN
-              CALL iom_put( "Heup", heup(:,:  ) * tmask(:,:,1) )  ! euphotic layer deptht
-              CALL iom_put( "PAR" , emoy(:,:,:) * tmask(:,:,:) )  ! Photosynthetically Available Radiation
-           ENDIF
-        ELSE
-           trc2d(:,:,  jp_pcs0_2d + 10) = heup(:,:  ) * tmask(:,:,1)  
-           trc3d(:,:,:,jp_pcs0_3d + 3)  = etot(:,:,:) * tmask(:,:,:)
+      IF( lk_iomput ) THEN
+        IF( jnt == nrdttrc  ) THEN
+           IF( iom_use( "Heup" ) ) CALL iom_put( "Heup", heup(:,:  ) * tmask(:,:,1) )  ! euphotic layer deptht
+           IF( iom_use( "PAR"  ) ) CALL iom_put( "PAR" , emoy(:,:,:) * tmask(:,:,:) )  ! Photosynthetically Available Radiation
         ENDIF
-        !
+      ELSE
+         IF( ln_diatrc ) THEN        ! save output diagnostics
+            trc2d(:,:,  jp_pcs0_2d + 10) = heup(:,:  ) * tmask(:,:,1)  
+            trc3d(:,:,:,jp_pcs0_3d + 3)  = etot(:,:,:) * tmask(:,:,:)
+         ENDIF
       ENDIF
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zprod.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zprod.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zprod.F90	(revision 5075)
@@ -83,8 +83,8 @@
       REAL(wp) ::   zpislopen  , zpislope2n
       REAL(wp) ::   zrum, zcodel, zargu, zval
-      REAL(wp) ::   zrfact2
+      REAL(wp) ::   zfact
       CHARACTER (len=25) :: charout
-      REAL(wp), POINTER, DIMENSION(:,:  ) :: zmixnano, zmixdiat, zstrn
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zpislopead, zpislopead2, zprdia, zprbio, zprdch, zprnch, zysopt   
+      REAL(wp), POINTER, DIMENSION(:,:  ) :: zmixnano, zmixdiat, zstrn, zw2d
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zpislopead, zpislopead2, zprdia, zprbio, zprdch, zprnch, zysopt, zw3d   
       REAL(wp), POINTER, DIMENSION(:,:,:) :: zprorca, zprorcad, zprofed, zprofen, zprochln, zprochld, zpronew, zpronewd
       !!---------------------------------------------------------------------
@@ -412,51 +412,143 @@
      END DO
 
-     ! Total primary production per year
-     tpp = tpp + glob_sum( ( zprorca(:,:,:) + zprorcad(:,:,:) ) * cvol(:,:,:) )
-
-     IF( ln_diatrc ) THEN
-         !
-         zrfact2 = 1.e3 * rfact2r  ! conversion from mol/L/timestep into mol/m3/s
-         IF( lk_iomput ) THEN
-           IF( jnt == nrdttrc ) THEN
-              CALL iom_put( "PPPHY"  , zprorca (:,:,:) * zrfact2 * tmask(:,:,:) )  ! primary production by nanophyto
-              CALL iom_put( "PPPHY2" , zprorcad(:,:,:) * zrfact2 * tmask(:,:,:) )  ! primary production by diatom
-              CALL iom_put( "PPNEWN" , zpronew (:,:,:) * zrfact2 * tmask(:,:,:) )  ! new primary production by nanophyto
-              CALL iom_put( "PPNEWD" , zpronewd(:,:,:) * zrfact2 * tmask(:,:,:) )  ! new primary production by diatom
-              CALL iom_put( "PBSi"   , zprorcad(:,:,:) * zrfact2 * tmask(:,:,:) * zysopt(:,:,:) ) ! biogenic silica production
-              CALL iom_put( "PFeD"   , zprofed (:,:,:) * zrfact2 * tmask(:,:,:) )  ! biogenic iron production by diatom
-              CALL iom_put( "PFeN"   , zprofen (:,:,:) * zrfact2 * tmask(:,:,:) )  ! biogenic iron production by nanophyto
-              CALL iom_put( "Mumax"  , prmax(:,:,:) * tmask(:,:,:) )  ! Maximum growth rate
-              CALL iom_put( "MuN"    , zprbio(:,:,:) * xlimphy(:,:,:) * tmask(:,:,:) )  ! Realized growth rate for nanophyto
-              CALL iom_put( "MuD"    , zprdia(:,:,:) * xlimdia(:,:,:) * tmask(:,:,:) )  ! Realized growth rate for diatoms
-              CALL iom_put( "LNlight", zprbio (:,:,:) / (prmax(:,:,:) + rtrn) * tmask(:,:,:) )  ! light limitation term
-              CALL iom_put( "LDlight", zprdia (:,:,:) / (prmax(:,:,:) + rtrn) * tmask(:,:,:) )  ! light limitation term
-           ENDIF
-         ELSE
-              trc3d(:,:,:,jp_pcs0_3d + 4)  = zprorca (:,:,:) * zrfact2 * tmask(:,:,:)
-              trc3d(:,:,:,jp_pcs0_3d + 5)  = zprorcad(:,:,:) * zrfact2 * tmask(:,:,:)
-              trc3d(:,:,:,jp_pcs0_3d + 6)  = zpronew (:,:,:) * zrfact2 * tmask(:,:,:)
-              trc3d(:,:,:,jp_pcs0_3d + 7)  = zpronewd(:,:,:) * zrfact2 * tmask(:,:,:)
-              trc3d(:,:,:,jp_pcs0_3d + 8)  = zprorcad(:,:,:) * zrfact2 * tmask(:,:,:) * zysopt(:,:,:)
-              trc3d(:,:,:,jp_pcs0_3d + 9)  = zprofed (:,:,:) * zrfact2 * tmask(:,:,:)
+
+    ! Total primary production per year
+    IF( iom_use( "tintpp" ) .OR. ( ln_check_mass .AND. kt == nitend .AND. jnt == nrdttrc )  )  &
+         & tpp = glob_sum( ( zprorca(:,:,:) + zprorcad(:,:,:) ) * cvol(:,:,:) )
+
+    IF( lk_iomput ) THEN
+       IF( jnt == nrdttrc ) THEN
+          CALL wrk_alloc( jpi, jpj,      zw2d )
+          CALL wrk_alloc( jpi, jpj, jpk, zw3d )
+          zfact = 1.e+3 * rfact2r  !  conversion from mol/l/kt to  mol/m3/s
+          !
+          IF( iom_use( "PPPHY" ) .OR. iom_use( "PPPHY2" ) )  THEN
+              zw3d(:,:,:) = zprorca (:,:,:) * zfact * tmask(:,:,:)  ! primary production by nanophyto
+              CALL iom_put( "PPPHY"  , zw3d )
+              !
+              zw3d(:,:,:) = zprorcad(:,:,:) * zfact * tmask(:,:,:)  ! primary production by diatomes
+              CALL iom_put( "PPPHY2"  , zw3d )
+          ENDIF
+          IF( iom_use( "PPNEWN" ) .OR. iom_use( "PPNEWD" ) )  THEN
+              zw3d(:,:,:) = zpronew (:,:,:) * zfact * tmask(:,:,:)  ! new primary production by nanophyto
+              CALL iom_put( "PPNEWN"  , zw3d )
+              !
+              zw3d(:,:,:) = zpronewd(:,:,:) * zfact * tmask(:,:,:)  ! new primary production by diatomes
+              CALL iom_put( "PPNEWD"  , zw3d )
+          ENDIF
+          IF( iom_use( "PBSi" ) )  THEN
+              zw3d(:,:,:) = zprorcad(:,:,:) * zfact * tmask(:,:,:) * zysopt(:,:,:) ! biogenic silica production
+              CALL iom_put( "PBSi"  , zw3d )
+          ENDIF
+          IF( iom_use( "PFeN" ) .OR. iom_use( "PFeD" ) )  THEN
+              zw3d(:,:,:) = zprofen(:,:,:) * zfact * tmask(:,:,:)  ! biogenic iron production by nanophyto
+              CALL iom_put( "PFeN"  , zw3d )
+              !
+              zw3d(:,:,:) = zprofed(:,:,:) * zfact * tmask(:,:,:)  ! biogenic iron production by  diatomes
+              CALL iom_put( "PFeD"  , zw3d )
+          ENDIF
+          IF( iom_use( "Mumax" ) )  THEN
+              zw3d(:,:,:) = prmax(:,:,:) * tmask(:,:,:)   ! Maximum growth rate
+              CALL iom_put( "Mumax"  , zw3d )
+          ENDIF
+          IF( iom_use( "MuN" ) .OR. iom_use( "MuD" ) )  THEN
+              zw3d(:,:,:) = zprbio(:,:,:) * xlimphy(:,:,:) * tmask(:,:,:)  ! Realized growth rate for nanophyto
+              CALL iom_put( "MuN"  , zw3d )
+              !
+              zw3d(:,:,:) =  zprdia(:,:,:) * xlimdia(:,:,:) * tmask(:,:,:)  ! Realized growth rate for diatoms
+              CALL iom_put( "MuD"  , zw3d )
+          ENDIF
+          IF( iom_use( "LNlight" ) .OR. iom_use( "LDlight" ) )  THEN
+              zw3d(:,:,:) = zprbio (:,:,:) / (prmax(:,:,:) + rtrn) * tmask(:,:,:) ! light limitation term
+              CALL iom_put( "LNlight"  , zw3d )
+              !
+              zw3d(:,:,:) =  zprdia (:,:,:) / (prmax(:,:,:) + rtrn) * tmask(:,:,:)  ! light limitation term
+              CALL iom_put( "LDlight"  , zw3d )
+          ENDIF
+          IF( iom_use( "TPP" ) )  THEN
+              zw3d(:,:,:) = ( zprorca(:,:,:) + zprorcad(:,:,:) ) * zfact * tmask(:,:,:)  ! total primary production
+              CALL iom_put( "TPP"  , zw3d )
+          ENDIF
+          IF( iom_use( "TPNEW" ) )  THEN
+              zw3d(:,:,:) = ( zpronew(:,:,:) + zpronewd(:,:,:) ) * zfact * tmask(:,:,:)  ! total new production
+              CALL iom_put( "TPNEW"  , zw3d )
+          ENDIF
+          IF( iom_use( "TPBFE" ) )  THEN
+              zw3d(:,:,:) = ( zprofen(:,:,:) + zprofed(:,:,:) ) * zfact * tmask(:,:,:)  ! total biogenic iron production
+              CALL iom_put( "TPBFE"  , zw3d )
+          ENDIF
+          IF( iom_use( "INTPPPHY" ) .OR. iom_use( "INTPPPHY2" ) ) THEN  
+             zw2d(:,:) = 0.
+             DO jk = 1, jpkm1
+               zw2d(:,:) = zw2d(:,:) + zprorca (:,:,jk) * fse3t(:,:,jk) * zfact * tmask(:,:,jk)  ! vert. integrated  primary produc. by nano
+             ENDDO
+             CALL iom_put( "INTPPPHY" , zw2d )
+             !
+             zw2d(:,:) = 0.
+             DO jk = 1, jpkm1
+                zw2d(:,:) = zw2d(:,:) + zprorcad(:,:,jk) * fse3t(:,:,jk) * zfact * tmask(:,:,jk) ! vert. integrated  primary produc. by diatom
+             ENDDO
+             CALL iom_put( "INTPPPHY2" , zw2d )
+          ENDIF
+          IF( iom_use( "INTPP" ) ) THEN   
+             zw2d(:,:) = 0.
+             DO jk = 1, jpkm1
+                zw2d(:,:) = zw2d(:,:) + ( zprorca(:,:,jk) + zprorcad(:,:,jk) ) * fse3t(:,:,jk) * zfact * tmask(:,:,jk) ! vert. integrated pp
+             ENDDO
+             CALL iom_put( "INTPP" , zw2d )
+          ENDIF
+          IF( iom_use( "INTPNEW" ) ) THEN    
+             zw2d(:,:) = 0.
+             DO jk = 1, jpkm1
+                zw2d(:,:) = zw2d(:,:) + ( zpronew(:,:,jk) + zpronewd(:,:,jk) ) * fse3t(:,:,jk) * zfact * tmask(:,:,jk)  ! vert. integrated new prod
+             ENDDO
+             CALL iom_put( "INTPNEW" , zw2d )
+          ENDIF
+          IF( iom_use( "INTPBFE" ) ) THEN           !   total biogenic iron production  ( vertically integrated )
+             zw2d(:,:) = 0.
+             DO jk = 1, jpkm1
+                zw2d(:,:) = zw2d(:,:) + ( zprofen(:,:,jk) + zprofed(:,:,jk) ) * fse3t(:,:,jk) * zfact * tmask(:,:,jk) ! vert integr. bfe prod
+             ENDDO
+            CALL iom_put( "INTPBFE" , zw2d )
+          ENDIF
+          IF( iom_use( "INTPBSI" ) ) THEN           !   total biogenic silica production  ( vertically integrated )
+             zw2d(:,:) = 0.
+             DO jk = 1, jpkm1
+                zw2d(:,:) = zw2d(:,:) + zprorcad(:,:,jk) * zysopt(:,:,jk) * fse3t(:,:,jk) * zfact * tmask(:,:,jk)  ! vert integr. bsi prod
+             ENDDO
+             CALL iom_put( "INTPBSI" , zw2d )
+          ENDIF
+          IF( iom_use( "tintpp" ) )  CALL iom_put( "tintpp" , tpp * zfact )  !  global total integrated primary production molC/s
+          !
+          CALL wrk_dealloc( jpi, jpj,      zw2d )
+          CALL wrk_dealloc( jpi, jpj, jpk, zw3d )
+       ENDIF
+     ELSE
+        IF( ln_diatrc ) THEN
+           zfact = 1.e+3 * rfact2r
+           trc3d(:,:,:,jp_pcs0_3d + 4)  = zprorca (:,:,:) * zfact * tmask(:,:,:)
+           trc3d(:,:,:,jp_pcs0_3d + 5)  = zprorcad(:,:,:) * zfact * tmask(:,:,:)
+           trc3d(:,:,:,jp_pcs0_3d + 6)  = zpronew (:,:,:) * zfact * tmask(:,:,:)
+           trc3d(:,:,:,jp_pcs0_3d + 7)  = zpronewd(:,:,:) * zfact * tmask(:,:,:)
+           trc3d(:,:,:,jp_pcs0_3d + 8)  = zprorcad(:,:,:) * zfact * tmask(:,:,:) * zysopt(:,:,:)
+           trc3d(:,:,:,jp_pcs0_3d + 9)  = zprofed (:,:,:) * zfact * tmask(:,:,:)
 #  if ! defined key_kriest
-              trc3d(:,:,:,jp_pcs0_3d + 10) = zprofen (:,:,:) * zrfact2 * tmask(:,:,:)
+           trc3d(:,:,:,jp_pcs0_3d + 10) = zprofen (:,:,:) * zfact * tmask(:,:,:)
 #  endif
-         ENDIF
-         !
-      ENDIF
-
-      IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
+        ENDIF
+     ENDIF
+
+     IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
          WRITE(charout, FMT="('prod')")
          CALL prt_ctl_trc_info(charout)
          CALL prt_ctl_trc(tab4d=tra, mask=tmask, clinfo=ctrcnm)
-      ENDIF
-      !
-      CALL wrk_dealloc( jpi, jpj,      zmixnano, zmixdiat, zstrn                                                  )
-      CALL wrk_dealloc( jpi, jpj, jpk, zpislopead, zpislopead2, zprdia, zprbio, zprdch, zprnch, zysopt            ) 
-      CALL wrk_dealloc( jpi, jpj, jpk, zprorca, zprorcad, zprofed, zprofen, zprochln, zprochld, zpronew, zpronewd )
-      !
-      IF( nn_timing == 1 )  CALL timing_stop('p4z_prod')
-      !
+     ENDIF
+     !
+     CALL wrk_dealloc( jpi, jpj,      zmixnano, zmixdiat, zstrn                                                  )
+     CALL wrk_dealloc( jpi, jpj, jpk, zpislopead, zpislopead2, zprdia, zprbio, zprdch, zprnch, zysopt            ) 
+     CALL wrk_dealloc( jpi, jpj, jpk, zprorca, zprorcad, zprofed, zprofen, zprochln, zprochld, zpronew, zpronewd )
+     !
+     IF( nn_timing == 1 )  CALL timing_stop('p4z_prod')
+     !
    END SUBROUTINE p4z_prod
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zrem.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zrem.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zrem.F90	(revision 5075)
@@ -78,8 +78,8 @@
       REAL(wp) ::   zofer2
 #endif
-      REAL(wp) ::   zonitr, zstep, zrfact2
+      REAL(wp) ::   zonitr, zstep, zfact
       CHARACTER (len=25) :: charout
-      REAL(wp), POINTER, DIMENSION(:,:  ) :: ztempbac 
-      REAL(wp), POINTER, DIMENSION(:,:,:) :: zdepbac, zolimi, zdepprod
+      REAL(wp), POINTER, DIMENSION(:,:  ) :: ztempbac
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zdepbac, zolimi, zdepprod, zw3d
       !!---------------------------------------------------------------------
       !
@@ -315,9 +315,19 @@
       END DO
 
-      IF( ln_diatrc .AND. lk_iomput .AND. jnt == nrdttrc ) THEN
-          zrfact2 = 1.e3 * rfact2r
-          CALL iom_put( "REMIN" , zolimi(:,:,:) * tmask(:,:,:) * zrfact2 )  ! Remineralisation rate
-          CALL iom_put( "DENIT" , denitr(:,:,:) * rdenit * rno3 * tmask(:,:,:) * zrfact2  )  ! Denitrification
-      ENDIF
+      IF( jnt == nrdttrc ) THEN
+          CALL wrk_alloc( jpi, jpj, jpk, zw3d )
+          zfact = 1.e+3 * rfact2r  !  conversion from mol/l/kt to  mol/m3/s
+          !
+          IF( iom_use( "REMIN" ) )  THEN
+              zw3d(:,:,:) = zolimi(:,:,:) * tmask(:,:,:) * zfact !  Remineralisation rate
+              CALL iom_put( "REMIN"  , zw3d )
+          ENDIF
+          IF( iom_use( "DENIT" ) )  THEN
+              zw3d(:,:,:) = denitr(:,:,:) * rdenit * rno3 * tmask(:,:,:) * zfact ! Denitrification
+              CALL iom_put( "DENIT"  , zw3d )
+          ENDIF
+          !
+          CALL wrk_dealloc( jpi, jpj, jpk, zw3d )
+       ENDIF
 
       IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsbc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsbc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsbc.F90	(revision 5075)
@@ -80,5 +80,4 @@
    REAL(wp), PUBLIC :: rivdininput, rivdipinput, rivdsiinput
 
-   REAL(wp) :: ryyss                    !: number of seconds per year 
 
    !!* Substitution
@@ -207,6 +206,4 @@
       !
       IF( nn_timing == 1 )  CALL timing_start('p4z_sbc_init')
-      !
-      ryyss   = nyear_len(1) * rday    ! number of seconds per year and per month
       !
       !                            !* set file information
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsed.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsed.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsed.F90	(revision 5075)
@@ -33,7 +33,4 @@
 
    !! * Module variables
-   REAL(wp) :: ryyss                    !: number of seconds per year 
-   REAL(wp) :: r1_ryyss                 !: inverse of ryyss
-   REAL(wp) :: rmtss                    !: number of seconds per month
    REAL(wp) :: r1_rday                  !: inverse of rday
 
@@ -84,8 +81,5 @@
       !
       IF( kt == nittrc000 .AND. jnt == 1 )  THEN
-         ryyss    = nyear_len(1) * rday    ! number of seconds per year and per month
-         rmtss    = ryyss / raamo
          r1_rday  = 1. / rday
-         r1_ryyss = 1. / ryyss
          IF( ln_check_mass .AND. lwp)  &
            &  CALL ctl_opn( numnit, 'nitrogen.budget', 'REPLACE', 'FORMATTED', 'SEQUENTIAL', -1, 6, .FALSE., narea )
@@ -99,4 +93,8 @@
       zdenit2d(:,:) = 0.e0
       zbureff (:,:) = 0.e0
+      zwork1  (:,:) = 0.e0
+      zwork2  (:,:) = 0.e0
+      zwork3  (:,:) = 0.e0
+      zwork4  (:,:) = 0.e0
 
       ! Iron input/uptake due to sea ice : Crude parameterization based on Lancelot et al.
@@ -117,7 +115,8 @@
          !
          trn(:,:,1,jpfer) = trn(:,:,1,jpfer) + zironice(:,:) 
-         !                                              
-         IF( ln_diatrc .AND. lk_iomput .AND. jnt == nrdttrc )   &
+         ! 
+         IF( lk_iomput .AND. jnt == nrdttrc .AND. iom_use( "Ironice" ) )   &
             &   CALL iom_put( "Ironice", zironice(:,:) * 1.e+3 * rfact2r * fse3t(:,:,1) * tmask(:,:,1) ) ! iron flux from ice
+         !
          CALL wrk_dealloc( jpi, jpj, zironice )
          !                                              
@@ -132,10 +131,10 @@
          !                                              ! Iron and Si deposition at the surface
          IF( ln_solub ) THEN
-            zirondep(:,:,1) = solub(:,:) * dust(:,:) * mfrac * rfact2 / fse3t(:,:,1) / ( 55.85 * rmtss ) + 3.e-10 * r1_ryyss 
+            zirondep(:,:,1) = solub(:,:) * dust(:,:) * mfrac * rfact2 / fse3t(:,:,1) / 55.85 + 3.e-10 * r1_ryyss 
          ELSE
-            zirondep(:,:,1) = dustsolub  * dust(:,:) * mfrac * rfact2 / fse3t(:,:,1) / ( 55.85 * rmtss ) + 3.e-10 * r1_ryyss 
+            zirondep(:,:,1) = dustsolub  * dust(:,:) * mfrac * rfact2 / fse3t(:,:,1) / 55.85 + 3.e-10 * r1_ryyss 
          ENDIF
-         zsidep(:,:) = 8.8 * 0.075 * dust(:,:) * mfrac * rfact2 / fse3t(:,:,1) / ( 28.1  * rmtss )
-         zpdep (:,:) = 0.1 * 0.021 * dust(:,:) * mfrac * rfact2 / fse3t(:,:,1) / ( 31.   * rmtss ) / po4r 
+         zsidep(:,:) = 8.8 * 0.075 * dust(:,:) * mfrac * rfact2 / fse3t(:,:,1) / 28.1 
+         zpdep (:,:) = 0.1 * 0.021 * dust(:,:) * mfrac * rfact2 / fse3t(:,:,1) / 31. / po4r 
          !                                              ! Iron solubilization of particles in the water column
          !                                              ! dust in kg/m2/s ---> 1/55.85 to put in mol/Fe ;  wdust in m/j
@@ -148,15 +147,15 @@
          trn(:,:,1,jpsil) = trn(:,:,1,jpsil) + zsidep  (:,:)
          trn(:,:,:,jpfer) = trn(:,:,:,jpfer) + zirondep(:,:,:) 
-         !                                              
-         IF( ln_diatrc ) THEN
-            zfact = 1.e+3 * rfact2r
-            IF( lk_iomput ) THEN
-               IF( jnt == nrdttrc ) THEN
-                  CALL iom_put( "Irondep", zirondep(:,:,1) * zfact * fse3t(:,:,1) * tmask(:,:,1) ) ! surface downward dust depo of iron
-                  CALL iom_put( "pdust"  , dust(:,:) / ( wdust * rday )  * tmask(:,:,1) ) ! dust concentration at surface
-               ENDIF
-            ELSE
-               trc2d(:,:,jp_pcs0_2d + 11) = zirondep(:,:,1) * zfact * fse3t(:,:,1) * tmask(:,:,1)
+         ! 
+         IF( lk_iomput ) THEN
+            IF( jnt == nrdttrc ) THEN
+                IF( iom_use( "Irondep" ) )   &
+                &  CALL iom_put( "Irondep", zirondep(:,:,1) * 1.e+3 * rfact2r * fse3t(:,:,1) * tmask(:,:,1) ) ! surface downward dust depo of iron
+                IF( iom_use( "pdust" ) )   &
+                &  CALL iom_put( "pdust"  , dust(:,:) / ( wdust * rday )  * tmask(:,:,1) ) ! dust concentration at surface
             ENDIF
+         ELSE                                    
+            IF( ln_diatrc )  &
+              &  trc2d(:,:,jp_pcs0_2d + 11) = zirondep(:,:,1) * 1.e+3 * rfact2r * fse3t(:,:,1) * tmask(:,:,1)
          ENDIF
          CALL wrk_dealloc( jpi, jpj,      zpdep, zsidep )
@@ -188,5 +187,5 @@
          trn(:,:,:,jpfer) = trn(:,:,:,jpfer) + ironsed(:,:,:) * rfact2
          !
-         IF( ln_diatrc .AND. lk_iomput .AND. jnt == nrdttrc )   &
+         IF( lk_iomput .AND. jnt == nrdttrc .AND. iom_use( "Ironsed" ) )   &
             &   CALL iom_put( "Ironsed", ironsed(:,:,:) * 1.e+3 * tmask(:,:,:) ) ! iron inputs from sediments
       ENDIF
@@ -197,8 +196,7 @@
          trn(:,:,:,jpfer) = trn(:,:,:,jpfer) + hydrofe(:,:,:) * rfact2
          !
-         IF( ln_diatrc .AND. lk_iomput .AND. jnt == nrdttrc )   &
+         IF( lk_iomput .AND. jnt == nrdttrc .AND. iom_use( "HYDR" ) )   &
             &   CALL iom_put( "HYDR", hydrofe(:,:,:) * 1.e+3 * tmask(:,:,:) ) ! hydrothermal iron input
       ENDIF
-
 
       ! OA: Warning, the following part is necessary, especially with Kriest
@@ -250,16 +248,18 @@
       DO jj = 1, jpj
          DO ji = 1, jpi
-            ikt = mbkt(ji,jj) 
+            IF( tmask(ji,jj,1) == 1 ) THEN
+               ikt = mbkt(ji,jj) 
 # if defined key_kriest
-            zwork1(ji,jj) = trn(ji,jj,ikt,jpgsi) * zwscal (ji,jj)
-            zwork2(ji,jj) = trn(ji,jj,ikt,jppoc) * zwsbio3(ji,jj)
+               zwork1(ji,jj) = trn(ji,jj,ikt,jpgsi) * zwscal (ji,jj)
+               zwork2(ji,jj) = trn(ji,jj,ikt,jppoc) * zwsbio3(ji,jj)
 # else
-            zwork1(ji,jj) = trn(ji,jj,ikt,jpgsi) * zwsbio4(ji,jj)
-            zwork2(ji,jj) = trn(ji,jj,ikt,jpgoc) * zwsbio4(ji,jj) + trn(ji,jj,ikt,jppoc) * zwsbio3(ji,jj) 
+               zwork1(ji,jj) = trn(ji,jj,ikt,jpgsi) * zwsbio4(ji,jj)
+               zwork2(ji,jj) = trn(ji,jj,ikt,jpgoc) * zwsbio4(ji,jj) + trn(ji,jj,ikt,jppoc) * zwsbio3(ji,jj) 
 # endif
-            ! For calcite, burial efficiency is made a function of saturation
-            zfactcal      = MIN( excess(ji,jj,ikt), 0.2 )
-            zfactcal      = MIN( 1., 1.3 * ( 0.2 - zfactcal ) / ( 0.4 - zfactcal ) )
-            zwork3(ji,jj) = trn(ji,jj,ikt,jpcal) * zwscal(ji,jj) * 2.e0 * zfactcal
+               ! For calcite, burial efficiency is made a function of saturation
+               zfactcal      = MIN( excess(ji,jj,ikt), 0.2 )
+               zfactcal      = MIN( 1., 1.3 * ( 0.2 - zfactcal ) / ( 0.4 - zfactcal ) )
+               zwork3(ji,jj) = trn(ji,jj,ikt,jpcal) * zwscal(ji,jj) * 2.e0 * zfactcal
+            ENDIF
          END DO
       END DO
@@ -381,28 +381,35 @@
       END DO
 
- 
-      IF( ln_check_mass ) THEN
-        ! Global budget of N SMS : denitrification in the water column and in the sediment
-         !                          nitrogen fixation by the diazotrophs
-         ! --------------------------------------------------------------------------------
-         zrdenittot   = glob_sum ( denitr(:,:,:) * rdenit * xnegtr(:,:,:) * cvol(:,:,:) )
-         zsdenittot   = glob_sum ( zwork4(:,:)   * e1e2t(:,:) )
-         znitrpottot  = glob_sum ( znitrpot(:,:,:) * nitrfix              * cvol(:,:,:) )
-         IF( kt == nitend .AND. jnt == nrdttrc ) THEN
-            zfact = 1.e+3 * rfact2r * rno3 * ryyss * 14. / 1e12
-            IF(lwp) WRITE(numnit,9100) ndastp, znitrpottot * nitrfix * zfact, zrdenittot * zfact , zsdenittot * zfact
+      ! Global budget of N SMS : denitrification in the water column and in the sediment
+      !                          nitrogen fixation by the diazotrophs
+      ! --------------------------------------------------------------------------------
+      zrdenittot   = glob_sum ( denitr(:,:,:) * rdenit * xnegtr(:,:,:) * cvol(:,:,:) )
+      zsdenittot   = glob_sum ( zwork4(:,:)   * e1e2t(:,:) )
+      znitrpottot  = glob_sum ( znitrpot(:,:,:) * nitrfix              * cvol(:,:,:) )
+      zfact = 1.e+3 * rfact2r * rno3 * 14. / 1.e12 * ryyss   ! conversion molC/l/kt ----> TgN/m3/year
+      !
+      IF( ln_check_mass .AND. ( kt == nitend .AND. jnt == nrdttrc ) .AND. ( lwp )  )  &
+         &  WRITE(numnit,9100) ndastp, znitrpottot * zfact  , &
+         &                             zrdenittot  * zfact  , &
+         &                             zsdenittot  * zfact
+      !
+      IF( lk_iomput ) THEN
+         IF( jnt == nrdttrc ) THEN
+            zfact = 1.e+3 * rfact2r * rno3  !  conversion from molC/l/kt  to molN/m3/s
+            IF( iom_use("Nfix"   ) ) CALL iom_put( "Nfix"  , znitrpot(:,:,:) * nitrfix * zfact * tmask(:,:,:) )  ! nitrogen fixation 
+            IF( iom_use("Sdenit" ) ) CALL iom_put( "Sdenit", zwork4(:,:) * zfact * tmask(:,:,1) )  ! Nitrate reduction in the sediments
+            IF( iom_use("tnfix"  ) ) CALL iom_put( "tnfix"  , znitrpottot * zfact  )               ! Global  nitrogen fixation
+            IF( iom_use("tdenit" ) ) CALL iom_put( "tdenit" , zrdenittot  * zfact  )               ! Total denitrification
+            IF( iom_use("INTNFIX") ) THEN   ! nitrogen fixation rate in ocean ( vertically integrated )
+               zwork1(:,:) = 0.
+               DO jk = 1, jpkm1
+                 zwork1(:,:) = zwork1(:,:) + znitrpot(:,:,jk) * nitrfix * zfact * fse3t(:,:,jk) * tmask(:,:,jk)
+               ENDDO
+               CALL iom_put( "INTNFIX" , zwork1 ) 
+            ENDIF
          ENDIF
-       ENDIF
-      !
-      IF( ln_diatrc ) THEN
-         zfact = 1.e+3 * rfact2r
-         IF( lk_iomput ) THEN
-            IF( jnt == nrdttrc ) THEN
-               CALL iom_put( "Nfix"  , znitrpot(:,:,:) * nitrfix * rno3 * zfact * tmask(:,:,:) )  ! nitrogen fixation 
-               CALL iom_put( "Sdenit", zwork4(:,:)               * rno3 * zfact * tmask(:,:,1) )  ! Nitrate reduction in the sediments
-            ENDIF
-         ELSE
-            trc2d(:,:,jp_pcs0_2d + 12) = znitrpot(:,:,1) * nitrfix * zfact * fse3t(:,:,1) * tmask(:,:,1)
-         ENDIF
+      ELSE
+         IF( ln_diatrc )  &
+            &  trc2d(:,:,jp_pcs0_2d + 12) = znitrpot(:,:,1) * nitrfix * rno3 * 1.e+3 * rfact2r * fse3t(:,:,1) * tmask(:,:,1)
       ENDIF
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsink.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsink.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsink.F90	(revision 5075)
@@ -41,5 +41,5 @@
 #endif
 
-   INTEGER  :: iksed  = 10
+   INTEGER  :: ik100
 
 #if  defined key_kriest
@@ -94,7 +94,7 @@
       REAL(wp) ::   zagg , zaggfe, zaggdoc, zaggdoc2, zaggdoc3
       REAL(wp) ::   zfact, zwsmax, zmax, zstep
-      REAL(wp) ::   zrfact2
-      INTEGER  ::   ik1
       CHARACTER (len=25) :: charout
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zw3d
+      REAL(wp), POINTER, DIMENSION(:,:  ) :: zw2d
       !!---------------------------------------------------------------------
       !
@@ -235,24 +235,61 @@
       END DO
 
-     ! Total primary production per year
-     t_oce_co2_exp = t_oce_co2_exp + glob_sum( ( sinking(:,:,iksed+1) + sinking2(:,:,iksed+1) ) * e1e2t(:,:) * tmask(:,:,1) )
+
+     ! Total carbon export per year
+     IF( iom_use( "tcexp" ) .OR. ( ln_check_mass .AND. kt == nitend .AND. jnt == nrdttrc )  )  &
+        &   t_oce_co2_exp = glob_sum( ( sinking(:,:,ik100) + sinking2(:,:,ik100) ) * e1e2t(:,:) * tmask(:,:,1) )
      !
-     IF( ln_diatrc ) THEN
-         zrfact2 = 1.e3 * rfact2r
-         ik1  = iksed + 1
-         IF( lk_iomput ) THEN
-           IF( jnt == nrdttrc ) THEN
-              CALL iom_put( "EPC100"  , ( sinking(:,:,ik1) + sinking2(:,:,ik1) ) * zrfact2 * tmask(:,:,1) ) ! Export of carbon at 100m
-              CALL iom_put( "EPFE100" , ( sinkfer(:,:,ik1) + sinkfer2(:,:,ik1) ) * zrfact2 * tmask(:,:,1) ) ! Export of iron at 100m
-              CALL iom_put( "EPCAL100",   sinkcal(:,:,ik1)                       * zrfact2 * tmask(:,:,1) ) ! Export of calcite  at 100m
-              CALL iom_put( "EPSI100" ,   sinksil(:,:,ik1)                       * zrfact2 * tmask(:,:,1) ) ! Export of biogenic silica at 100m
-           ENDIF
-         ELSE
-           trc2d(:,:,jp_pcs0_2d + 4) = sinking (:,:,ik1) * zrfact2 * tmask(:,:,1)
-           trc2d(:,:,jp_pcs0_2d + 5) = sinking2(:,:,ik1) * zrfact2 * tmask(:,:,1)
-           trc2d(:,:,jp_pcs0_2d + 6) = sinkfer (:,:,ik1) * zrfact2 * tmask(:,:,1)
-           trc2d(:,:,jp_pcs0_2d + 7) = sinkfer2(:,:,ik1) * zrfact2 * tmask(:,:,1)
-           trc2d(:,:,jp_pcs0_2d + 8) = sinksil (:,:,ik1) * zrfact2 * tmask(:,:,1)
-           trc2d(:,:,jp_pcs0_2d + 9) = sinkcal (:,:,ik1) * zrfact2 * tmask(:,:,1)
+     IF( lk_iomput ) THEN
+       IF( jnt == nrdttrc ) THEN
+          CALL wrk_alloc( jpi, jpj,      zw2d )
+          CALL wrk_alloc( jpi, jpj, jpk, zw3d )
+          zfact = 1.e+3 * rfact2r  !  conversion from mol/l/kt to  mol/m3/s
+          !
+          IF( iom_use( "EPC100" ) )  THEN
+              zw2d(:,:) = ( sinking(:,:,ik100) + sinking2(:,:,ik100) ) * zfact * tmask(:,:,1) ! Export of carbon at 100m
+              CALL iom_put( "EPC100"  , zw2d )
+          ENDIF
+          IF( iom_use( "EPFE100" ) )  THEN
+              zw2d(:,:) = ( sinkfer(:,:,ik100) + sinkfer2(:,:,ik100) ) * zfact * tmask(:,:,1) ! Export of iron at 100m
+              CALL iom_put( "EPFE100"  , zw2d )
+          ENDIF
+          IF( iom_use( "EPCAL100" ) )  THEN
+              zw2d(:,:) = sinkcal(:,:,ik100) * zfact * tmask(:,:,1) ! Export of calcite at 100m
+              CALL iom_put( "EPCAL100"  , zw2d )
+          ENDIF
+          IF( iom_use( "EPSI100" ) )  THEN
+              zw2d(:,:) =  sinksil(:,:,ik100) * zfact * tmask(:,:,1) ! Export of bigenic silica at 100m
+              CALL iom_put( "EPSI100"  , zw2d )
+          ENDIF
+          IF( iom_use( "EXPC" ) )  THEN
+              zw3d(:,:,:) = ( sinking(:,:,:) + sinking2(:,:,:) ) * zfact * tmask(:,:,:) ! Export of carbon in the water column
+              CALL iom_put( "EXPC"  , zw3d )
+          ENDIF
+          IF( iom_use( "EXPFE" ) )  THEN
+              zw3d(:,:,:) = ( sinkfer(:,:,:) + sinkfer2(:,:,:) ) * zfact * tmask(:,:,:) ! Export of iron 
+              CALL iom_put( "EXPFE"  , zw3d )
+          ENDIF
+          IF( iom_use( "EXPCAL" ) )  THEN
+              zw3d(:,:,:) = sinkcal(:,:,:) * zfact * tmask(:,:,:) ! Export of calcite 
+              CALL iom_put( "EXPCAL"  , zw3d )
+          ENDIF
+          IF( iom_use( "EXPSI" ) )  THEN
+              zw3d(:,:,:) = sinksil(:,:,:) * zfact * tmask(:,:,:) ! Export of bigenic silica
+              CALL iom_put( "EXPSI"  , zw3d )
+          ENDIF
+          IF( iom_use( "tcexp" ) )  CALL iom_put( "tcexp" , t_oce_co2_exp * zfact )   ! molC/s
+          ! 
+          CALL wrk_dealloc( jpi, jpj,      zw2d )
+          CALL wrk_dealloc( jpi, jpj, jpk, zw3d )
+        ENDIF
+      ELSE
+         IF( ln_diatrc ) THEN
+            zfact = 1.e3 * rfact2r
+            trc2d(:,:,jp_pcs0_2d + 4) = sinking (:,:,ik100) * zfact * tmask(:,:,1)
+            trc2d(:,:,jp_pcs0_2d + 5) = sinking2(:,:,ik100) * zfact * tmask(:,:,1)
+            trc2d(:,:,jp_pcs0_2d + 6) = sinkfer (:,:,ik100) * zfact * tmask(:,:,1)
+            trc2d(:,:,jp_pcs0_2d + 7) = sinkfer2(:,:,ik100) * zfact * tmask(:,:,1)
+            trc2d(:,:,jp_pcs0_2d + 8) = sinksil (:,:,ik100) * zfact * tmask(:,:,1)
+            trc2d(:,:,jp_pcs0_2d + 9) = sinkcal (:,:,ik100) * zfact * tmask(:,:,1)
          ENDIF
       ENDIF
@@ -272,5 +309,14 @@
       !!                  ***  ROUTINE p4z_sink_init  ***
       !!----------------------------------------------------------------------
-
+      INTEGER :: jk
+
+      ik100 = 10        !  last level where depth less than 100 m
+      DO jk = jpkm1, 1, -1
+         IF( gdept_1d(jk) > 100. )  ik100 = jk - 1
+      END DO
+      IF (lwp) WRITE(numout,*)
+      IF (lwp) WRITE(numout,*) ' Level corresponding to 100m depth ',  ik100 + 1
+      IF (lwp) WRITE(numout,*)
+      !
       t_oce_co2_exp = 0._wp
       !
@@ -300,8 +346,10 @@
       REAL(wp) :: zdiv , zdiv1, zdiv2, zdiv3, zdiv4, zdiv5
       REAL(wp) :: zval1, zval2, zval3, zval4
-      REAL(wp) :: zrfact2
+      REAL(wp) :: zfact
       INTEGER  :: ik1
       CHARACTER (len=25) :: charout
       REAL(wp), POINTER, DIMENSION(:,:,:) :: znum3d 
+      REAL(wp), POINTER, DIMENSION(:,:,:) :: zw3d
+      REAL(wp), POINTER, DIMENSION(:,:  ) :: zw2d
       !!---------------------------------------------------------------------
       !
@@ -477,35 +525,77 @@
 
      ! Total primary production per year
-     t_oce_co2_exp = t_oce_co2_exp + glob_sum( ( sinking(:,:,:) ) * cvol(:,:,:) )
+     t_oce_co2_exp = t_oce_co2_exp + glob_sum( ( sinking(:,:,ik100) * e1e2t(:,:) * tmask(:,:,1) )
      !
-      IF( ln_diatrc ) THEN
-         !
-         ik1 = iksed + 1
-         zrfact2 = 1.e3 * rfact2r
-         IF( jnt == nrdttrc ) THEN
-           CALL iom_put( "POCFlx"  , sinking (:,:,:)      * zrfact2 * tmask(:,:,:) )  ! POC export
-           CALL iom_put( "NumFlx"  , sinking2 (:,:,:)     * zrfact2 * tmask(:,:,:) )  ! Num export
-           CALL iom_put( "SiFlx"   , sinksil (:,:,:)      * zrfact2 * tmask(:,:,:) )  ! Silica export
-           CALL iom_put( "CaCO3Flx", sinkcal (:,:,:)      * zrfact2 * tmask(:,:,:) )  ! Calcite export
-           CALL iom_put( "xnum"    , znum3d  (:,:,:)                * tmask(:,:,:) )  ! Number of particles in aggregats
-           CALL iom_put( "W1"      , wsbio3  (:,:,:)                * tmask(:,:,:) )  ! sinking speed of POC
-           CALL iom_put( "W2"      , wsbio4  (:,:,:)                * tmask(:,:,:) )  ! sinking speed of aggregats
+     IF( lk_iomput ) THEN
+        IF( jnt == nrdttrc ) THEN
+          CALL wrk_alloc( jpi, jpj,      zw2d )
+          CALL wrk_alloc( jpi, jpj, jpk, zw3d )
+          zfact = 1.e+3 * rfact2r  !  conversion from mol/l/kt to  mol/m3/s
+          !
+          IF( iom_use( "EPC100" ) )  THEN
+              zw2d(:,:) = sinking(:,:,ik100) * zfact * tmask(:,:,1) ! Export of carbon at 100m
+              CALL iom_put( "EPC100"  , zw2d )
+          ENDIF
+          IF( iom_use( "EPN100" ) )  THEN
+              zw2d(:,:) = sinking2(:,:,ik100) * zfact * tmask(:,:,1) ! Export of number of aggregates ?
+              CALL iom_put( "EPN100"  , zw2d )
+          ENDIF
+          IF( iom_use( "EPCAL100" ) )  THEN
+              zw2d(:,:) = sinkcal(:,:,ik100) * zfact * tmask(:,:,1) ! Export of calcite at 100m
+              CALL iom_put( "EPCAL100"  , zw2d )
+          ENDIF
+          IF( iom_use( "EPSI100" ) )  THEN
+              zw2d(:,:) = sinksil(:,:,ik100) * zfact * tmask(:,:,1) ! Export of bigenic silica at 100m
+              CALL iom_put( "EPSI100"  , zw2d )
+          ENDIF
+          IF( iom_use( "EXPC" ) )  THEN
+              zw3d(:,:,:) = sinking(:,:,:) * zfact * tmask(:,:,:) ! Export of carbon in the water column
+              CALL iom_put( "EXPC"  , zw3d )
+          ENDIF
+          IF( iom_use( "EXPN" ) )  THEN
+              zw3d(:,:,:) = sinking(:,:,:) * zfact * tmask(:,:,:) ! Export of carbon in the water column
+              CALL iom_put( "EXPN"  , zw3d )
+          ENDIF
+          IF( iom_use( "EXPCAL" ) )  THEN
+              zw3d(:,:,:) = sinkcal(:,:,:) * zfact * tmask(:,:,:) ! Export of calcite 
+              CALL iom_put( "EXPCAL"  , zw3d )
+          ENDIF
+          IF( iom_use( "EXPSI" ) )  THEN
+              zw3d(:,:,:) = sinksil(:,:,:) * zfact * tmask(:,:,:) ! Export of bigenic silica
+              CALL iom_put( "EXPSI"  , zw3d )
+          ENDIF
+          IF( iom_use( "XNUM" ) )  THEN
+              zw3d(:,:,:) =  znum3d(:,:,:) * tmask(:,:,:) !  Number of particles on aggregats
+              CALL iom_put( "XNUM"  , zw3d )
+          ENDIF
+          IF( iom_use( "WSC" ) )  THEN
+              zw3d(:,:,:) = wsbio3(:,:,:) * tmask(:,:,:) ! Sinking speed of carbon particles
+              CALL iom_put( "WSC"  , zw3d )
+          ENDIF
+          IF( iom_use( "WSN" ) )  THEN
+              zw3d(:,:,:) = wsbio4(:,:,:) * tmask(:,:,:) ! Sinking speed of particles number
+              CALL iom_put( "WSN"  , zw3d )
+          ENDIF
+          !
+          CALL wrk_dealloc( jpi, jpj,      zw2d )
+          CALL wrk_dealloc( jpi, jpj, jpk, zw3d )
+      ELSE
+         IF( ln_diatrc ) THEN
+            zfact = 1.e3 * rfact2r
+            trc2d(:,:  ,jp_pcs0_2d + 4)  = sinking (:,:,ik100)  * zfact * tmask(:,:,1)
+            trc2d(:,:  ,jp_pcs0_2d + 5)  = sinking2(:,:,ik100)  * zfact * tmask(:,:,1)
+            trc2d(:,:  ,jp_pcs0_2d + 6)  = sinkfer (:,:,ik100)  * zfact * tmask(:,:,1)
+            trc2d(:,:  ,jp_pcs0_2d + 7)  = sinksil (:,:,ik100)  * zfact * tmask(:,:,1)
+            trc2d(:,:  ,jp_pcs0_2d + 8)  = sinkcal (:,:,ik100)  * zfact * tmask(:,:,1)
+            trc3d(:,:,:,jp_pcs0_3d + 11) = sinking (:,:,:)      * zfact * tmask(:,:,:)
+            trc3d(:,:,:,jp_pcs0_3d + 12) = sinking2(:,:,:)      * zfact * tmask(:,:,:)
+            trc3d(:,:,:,jp_pcs0_3d + 13) = sinksil (:,:,:)      * zfact * tmask(:,:,:)
+            trc3d(:,:,:,jp_pcs0_3d + 14) = sinkcal (:,:,:)      * zfact * tmask(:,:,:)
+            trc3d(:,:,:,jp_pcs0_3d + 15) = znum3d  (:,:,:)              * tmask(:,:,:)
+            trc3d(:,:,:,jp_pcs0_3d + 16) = wsbio3  (:,:,:)              * tmask(:,:,:)
+            trc3d(:,:,:,jp_pcs0_3d + 17) = wsbio4  (:,:,:)              * tmask(:,:,:)
          ENDIF
-# if ! defined key_iomput
-         trc2d(:,:  ,jp_pcs0_2d + 4)  = sinking (:,:,ik1)    * zrfact2 * tmask(:,:,1)
-         trc2d(:,:  ,jp_pcs0_2d + 5)  = sinking2(:,:,ik1)    * zrfact2 * tmask(:,:,1)
-         trc2d(:,:  ,jp_pcs0_2d + 6)  = sinkfer (:,:,ik1)    * zrfact2 * tmask(:,:,1)
-         trc2d(:,:  ,jp_pcs0_2d + 7)  = sinksil (:,:,ik1)    * zrfact2 * tmask(:,:,1)
-         trc2d(:,:  ,jp_pcs0_2d + 8)  = sinkcal (:,:,ik1)    * zrfact2 * tmask(:,:,1)
-         trc3d(:,:,:,jp_pcs0_3d + 11) = sinking (:,:,:)      * zrfact2 * tmask(:,:,:)
-         trc3d(:,:,:,jp_pcs0_3d + 12) = sinking2(:,:,:)      * zrfact2 * tmask(:,:,:)
-         trc3d(:,:,:,jp_pcs0_3d + 13) = sinksil (:,:,:)      * zrfact2 * tmask(:,:,:)
-         trc3d(:,:,:,jp_pcs0_3d + 14) = sinkcal (:,:,:)      * zrfact2 * tmask(:,:,:)
-         trc3d(:,:,:,jp_pcs0_3d + 15) = znum3d  (:,:,:)                * tmask(:,:,:)
-         trc3d(:,:,:,jp_pcs0_3d + 16) = wsbio3  (:,:,:)                * tmask(:,:,:)
-         trc3d(:,:,:,jp_pcs0_3d + 17) = wsbio4  (:,:,:)                * tmask(:,:,:)
-# endif
-        !
       ENDIF
+
       !
       IF(ln_ctl)   THEN  ! print mean trends (used for debugging)
@@ -663,4 +753,12 @@
       END DO
       !
+      ik100 = 10        !  last level where depth less than 100 m
+      DO jk = jpkm1, 1, -1
+         IF( gdept_1d(jk) > 100. )  iksed = jk - 1
+      END DO
+      IF (lwp) WRITE(numout,*)
+      IF (lwp) WRITE(numout,*) ' Level corresponding to 100m depth ',  ik100 + 1
+      IF (lwp) WRITE(numout,*)
+      !
       t_oce_co2_exp = 0._wp
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsms.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsms.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/P4Z/p4zsms.F90	(revision 5075)
@@ -11,5 +11,5 @@
    !!   'key_pisces'                                       PISCES bio-model
    !!----------------------------------------------------------------------
-   !!   p4zsms        :  Time loop of passive tracers sms
+   !!   p4zsms         :  Time loop of passive tracers sms
    !!----------------------------------------------------------------------
    USE oce_trc         !  shared variables between ocean and passive tracers
@@ -25,6 +25,6 @@
    USE p4zint          !  time interpolation
    USE iom             !  I/O manager
-   USE trdmod_oce      !  Ocean trends variables
-   USE trdmod_trc      !  TOP trends variables
+   USE trd_oce         !  Ocean trends variables
+   USE trdtrc          !  TOP trends variables
    USE sedmodel        !  Sediment model
    USE prtctl_trc      !  print control for debugging
@@ -33,6 +33,6 @@
    PRIVATE
 
-   PUBLIC   p4z_sms_init    ! called in p4zsms.F90
-   PUBLIC   p4z_sms    ! called in p4zsms.F90
+   PUBLIC   p4z_sms_init   ! called in p4zsms.F90
+   PUBLIC   p4z_sms        ! called in p4zsms.F90
 
    REAL(wp) :: alkbudget, no3budget, silbudget, ferbudget
@@ -120,5 +120,4 @@
          ENDDO
       ENDIF
-
       CALL p4z_lys( kt )             ! Compute CaCO3 saturation
       CALL p4z_flx( kt )             ! Compute surface fluxes
@@ -146,10 +145,10 @@
             jl = jn + jp_pcs0 - 1
              ztrdpis(:,:,:,jn) = ztrdpis(:,:,:,jn) + tra(:,:,:,jl)
-             CALL trd_mod_trc( ztrdpis(:,:,:,jn), jn, jptra_trd_sms, kt )   ! save trends
+             CALL trd_trc( ztrdpis(:,:,:,jn), jn, jptra_sms, kt )   ! save trends
           END DO
           CALL wrk_dealloc( jpi, jpj, jpk, jp_pisces, ztrdpis ) 
       END IF
       !
-      CALL p4z_chk_mass( kt ) ! Mass conservation checking
+      IF( lk_iomput .OR. ln_check_mass )  CALL p4z_chk_mass( kt ) ! Mass conservation checking
 
       IF ( lwm .AND. kt == nittrc000 ) CALL FLUSH    ( numonp )     ! flush output namelist PISCES
@@ -328,4 +327,10 @@
          ENDIF
          !
+         IF( iom_varid( numrtr, 'tcflxcum', ldstop = .FALSE. ) > 0 ) THEN  ! cumulative total flux of carbon
+            CALL iom_get( numrtr, 'tcflxcum' , t_oce_co2_flx_cum  )
+         ELSE
+            t_oce_co2_flx_cum = 0._wp
+         ENDIF
+         !
       ELSEIF( TRIM(cdrw) == 'WRITE' ) THEN
          IF( kt == nitrst ) THEN
@@ -337,4 +342,5 @@
          CALL iom_rstput( kt, nitrst, numrtw, 'Silicalim', xksi(:,:) )
          CALL iom_rstput( kt, nitrst, numrtw, 'Silicamax', xksimax(:,:) )
+         CALL iom_rstput( kt, nitrst, numrtw, 'tcflxcum', t_oce_co2_flx_cum )
       ENDIF
       !
@@ -398,5 +404,6 @@
       !!---------------------------------------------------------------------
       !
-      INTEGER, INTENT( in ) ::   kt      ! ocean time-step index      
+      INTEGER , INTENT( in ) ::   kt      ! ocean time-step index      
+      REAL(wp)               ::  zfact       
       !!
       !!---------------------------------------------------------------------
@@ -409,5 +416,6 @@
       ENDIF
 
-      IF( ln_check_mass .AND. kt == nitend ) THEN      !   Compute the budget of NO3, ALK, Si, Fer
+      IF( iom_use( "pno3tot" ) .OR. ( ln_check_mass .AND. kt == nitend )  ) THEN
+         !   Compute the budget of NO3, ALK, Si, Fer
          no3budget = glob_sum( (   trn(:,:,:,jpno3) + trn(:,:,:,jpnh4)  &
             &                    + trn(:,:,:,jpphy) + trn(:,:,:,jpdia)  &
@@ -417,13 +425,28 @@
             &                    + trn(:,:,:,jpgoc)                     &
 #endif
-            &                    + trn(:,:,:,jpdoc)                     ) * cvol(:,:,:)  ) 
-         ! 
+            &                    + trn(:,:,:,jpdoc)                     ) * cvol(:,:,:)  )
+         !
+         no3budget = no3budget / areatot
+         CALL iom_put( "pno3tot", no3budget )
+      ENDIF
+      !
+      IF( iom_use( "psiltot" ) .OR.  ( ln_check_mass .AND. kt == nitend )  ) THEN
          silbudget = glob_sum( (   trn(:,:,:,jpsil) + trn(:,:,:,jpgsi)  &
             &                    + trn(:,:,:,jpdsi)                     ) * cvol(:,:,:)  )
-         ! 
+         !
+         silbudget = silbudget / areatot
+         CALL iom_put( "psiltot", silbudget )
+      ENDIF
+      !
+      IF( iom_use( "palktot" ) .OR.  ( ln_check_mass .AND. kt == nitend )  ) THEN
          alkbudget = glob_sum( (   trn(:,:,:,jpno3) * rno3              &
             &                    + trn(:,:,:,jptal)                     &
             &                    + trn(:,:,:,jpcal) * 2.                ) * cvol(:,:,:)  )
-         ! 
+         !
+         alkbudget = alkbudget / areatot
+         CALL iom_put( "palktot", alkbudget )
+      ENDIF
+      !
+      IF( iom_use( "pfertot" ) .OR.  ( ln_check_mass .AND. kt == nitend )  ) THEN
          ferbudget = glob_sum( (   trn(:,:,:,jpfer) + trn(:,:,:,jpnfe)  &
             &                    + trn(:,:,:,jpdfe)                     &
@@ -434,25 +457,24 @@
             &                    + trn(:,:,:,jpzoo) * ferat3            &
             &                    + trn(:,:,:,jpmes) * ferat3            ) * cvol(:,:,:)  )
-
-         !
+         !
+         ferbudget = ferbudget / areatot
+         CALL iom_put( "pfertot", ferbudget )
+      ENDIF
+      !
+      IF( ln_check_mass .AND. kt == nitend ) THEN   ! Compute the budget of NO3, ALK, Si, Fer
+         zfact = rfact2r * 12. / 1.e15 * ryyss    ! conversion molC/kt --> PgC/year
          t_atm_co2_flx  = t_atm_co2_flx / glob_sum( e1e2t(:,:) )
-         t_oce_co2_flx  = t_oce_co2_flx         * 12. / 1.e15 * (-1 )
-         tpp            = tpp           * 1000. * 12. / 1.E15
-         t_oce_co2_exp  = t_oce_co2_exp * 1000. * 12. / 1.E15
-         !
-         no3budget = no3budget / areatot
-         silbudget = silbudget / areatot
-         alkbudget = alkbudget / areatot
-         ferbudget = ferbudget / areatot
-         !
-         IF(lwp) THEN
-            WRITE(numco2,9000) ndastp, t_atm_co2_flx, t_oce_co2_flx, tpp, t_oce_co2_exp
-            WRITE(numnut,9500) ndastp, alkbudget, no3budget, silbudget, ferbudget
-         ENDIF
-         !
-      ENDIF
-       !
+         t_oce_co2_flx  = t_oce_co2_flx         * zfact * (-1 )
+         tpp            = tpp           * 1000. * zfact
+         t_oce_co2_exp  = t_oce_co2_exp * 1000. * zfact
+         IF( lwp ) WRITE(numco2,9000) ndastp, t_atm_co2_flx, t_oce_co2_flx, tpp, t_oce_co2_exp
+         IF( lwp ) WRITE(numnut,9500) ndastp, alkbudget        * 1.e+06, &
+             &                                no3budget * rno3 * 1.e+06, &
+             &                                silbudget        * 1.e+06, &
+             &                                ferbudget        * 1.e+09
+      ENDIF
+      !
  9000  FORMAT(i8,f10.5,e18.10,f10.5,f10.5)
- 9500  FORMAT(i8,4e18.10)     
+ 9500  FORMAT(i8,4e18.10)
        !
    END SUBROUTINE p4z_chk_mass
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/sms_pisces.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/sms_pisces.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/sms_pisces.F90	(revision 5075)
@@ -36,4 +36,7 @@
    REAL(wp) ::   rfact2, rfact2r   !: ???
    REAL(wp) ::   xstep             !: Time step duration for biology
+   REAL(wp) ::   ryyss             !: number of seconds per year 
+   REAL(wp) ::   r1_ryyss          !: inverse number of seconds per year 
+
 
    !!*  Biological parameters 
@@ -53,4 +56,5 @@
    REAL(wp) ::  t_oce_co2_exp      !: total carbon export
    REAL(wp) ::  t_oce_co2_flx      !: Total ocean carbon flux
+   REAL(wp) ::  t_oce_co2_flx_cum  !: Cumulative Total ocean carbon flux
    REAL(wp) ::  t_atm_co2_flx      !: global mean of atmospheric pco2
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcini_pisces.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcini_pisces.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcini_pisces.F90	(revision 5075)
@@ -100,4 +100,7 @@
       IF( lk_mpp    )   CALL mpp_sum( ierr )
       IF( ierr /= 0 )   CALL ctl_stop( 'STOP', 'pisces_alloc: unable to allocate PISCES arrays' )
+      !
+      ryyss    = nyear_len(1) * rday    ! number of seconds per year
+      r1_ryyss = 1. / ryyss
       !
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcnam_pisces.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcnam_pisces.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcnam_pisces.F90	(revision 5075)
@@ -19,5 +19,5 @@
    USE trc             ! TOP variables
    USE sms_pisces      ! sms trends
-   USE trdmod_trc_oce
+   USE trdtrc_oce
    USE iom             ! I/O manager
 
@@ -123,5 +123,5 @@
 #if defined key_pisces_reduced
 
-      IF( ( .NOT.lk_iomput .AND. ln_diabio ) .OR. lk_trdmld_trc ) THEN
+      IF( ( .NOT.lk_iomput .AND. ln_diabio ) .OR. lk_trdmxl_trc ) THEN
          !
          ! Namelist nampisdbi
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcwri_pisces.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcwri_pisces.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/PISCES/trcwri_pisces.F90	(revision 5075)
@@ -30,7 +30,8 @@
       !! ** Purpose :   output passive tracers fields 
       !!---------------------------------------------------------------------
-      CHARACTER (len=20)   :: cltra
-      REAL(wp)             :: zrfact
-      INTEGER              :: jn
+      CHARACTER (len=20)           :: cltra
+      REAL(wp)                     :: zfact
+      INTEGER                      :: ji, jj, jk, jn
+      REAL(wp), DIMENSION(jpi,jpj) :: zdic, zo2min, zdepo2min
       !!---------------------------------------------------------------------
  
@@ -40,23 +41,43 @@
       DO jn = jp_pcs0, jp_pcs1
          cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
-         IF( lk_vvl ) THEN
-            CALL iom_put( cltra, trn(:,:,:,jn) * fse3t_n(:,:,:) )
-         ELSE
-            CALL iom_put( cltra, trn(:,:,:,jn) )
-         ENDIF
-         CALL iom_put( cltra, trn(:,:,:,jn) * zrfact )
+         CALL iom_put( cltra, trn(:,:,:,jn) )
       END DO
 #else
       DO jn = jp_pcs0, jp_pcs1
-         zrfact = 1.0e+6 
-         IF( jn == jpno3 .OR. jn == jpnh4 ) zrfact = rno3 * 1.0e+6 
-         IF( jn == jppo4  )                 zrfact = po4r * 1.0e+6
+         zfact = 1.0e+6 
+         IF( jn == jpno3 .OR. jn == jpnh4 ) zfact = rno3 * 1.0e+6 
+         IF( jn == jppo4  )                 zfact = po4r * 1.0e+6
          cltra = TRIM( ctrcnm(jn) )                  ! short title for tracer
-         IF( lk_vvl ) THEN
-            CALL iom_put( cltra, trn(:,:,:,jn) * fse3t_n(:,:,:) * zrfact )
-         ELSE
-            CALL iom_put( cltra, trn(:,:,:,jn) * zrfact )
-         ENDIF
+         IF( iom_use( cltra ) )  CALL iom_put( cltra, trn(:,:,:,jn) * zfact )
       END DO
+
+      IF( iom_use( "INTDIC" ) ) THEN                     !   DIC content in kg/m2
+         zdic(:,:) = 0.
+         DO jk = 1, jpkm1
+            zdic(:,:) = zdic(:,:) + trn(:,:,jk,jpdic) * fse3t(:,:,jk) * tmask(:,:,jk) * 12.
+         ENDDO
+         CALL iom_put( 'INTDIC', zdic )     
+      ENDIF
+      !
+      IF( iom_use( "O2MIN" ) .OR. iom_use ( "ZO2MIN" ) ) THEN  ! Oxygen minimum concentration and depth 
+         zo2min   (:,:) = trn(:,:,1,jpoxy) * tmask(:,:,1)
+         zdepo2min(:,:) = fsdepw(:,:,1)    * tmask(:,:,1)
+         DO jk = 2, jpkm1
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( tmask(ji,jj,jk) == 1 ) then
+                     IF( trn(ji,jj,jk,jpoxy) < zo2min(ji,jj) ) then
+                        zo2min   (ji,jj) = trn(ji,jj,jk,jpoxy)
+                        zdepo2min(ji,jj) = fsdepw(ji,jj,jk)
+                     ENDIF
+                  ENDIF
+               END DO
+            END DO
+         END DO
+         !
+         CALL iom_put('O2MIN' , zo2min     )                              ! oxygen minimum concentration
+         CALL iom_put('ZO2MIN', zdepo2min  )                              ! depth of oxygen minimum concentration
+          !
+      ENDIF
 #endif
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcbbl.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcbbl.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcbbl.F90	(revision 5075)
@@ -25,5 +25,5 @@
    USE trabbl              ! 
    USE prtctl_trc          ! Print control for debbuging
-   USE trdmod_oce
+   USE trd_oce
    USE trdtra
 
@@ -93,5 +93,5 @@
         DO jn = 1, jptra
            ztrtrd(:,:,:,jn) = tra(:,:,:,jn) - ztrtrd(:,:,:,jn)
-           CALL trd_tra( kt, 'TRC', jn, jptra_trd_bbl, ztrtrd(:,:,:,jn) )
+           CALL trd_tra( kt, 'TRC', jn, jptra_bbl, ztrtrd(:,:,:,jn) )
         END DO
         CALL wrk_dealloc( jpi, jpj, jpk, jptra, ztrtrd ) ! temporary save of trends
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcdmp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcdmp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcdmp.F90	(revision 5075)
@@ -23,5 +23,5 @@
    USE prtctl_trc      ! Print control for debbuging
    USE trdtra
-   USE trdmod_oce
+   USE trd_oce
 
    IMPLICIT NONE
@@ -75,5 +75,5 @@
       !! ** Action  : - update the tracer trends tra with the newtonian 
       !!                damping trends.
-      !!              - save the trends ('key_trdmld_trc')
+      !!              - save the trends ('key_trdmxl_trc')
       !!----------------------------------------------------------------------
       !!
@@ -151,5 +151,5 @@
             IF( l_trdtrc ) THEN
                ztrtrd(:,:,:) = tra(:,:,:,jn) -  ztrtrd(:,:,:)
-               CALL trd_tra( kt, 'TRC', jn, jptra_trd_dmp, ztrtrd )
+               CALL trd_tra( kt, 'TRC', jn, jptra_dmp, ztrtrd )
             END IF
             !                                                       ! ===========
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcldf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcldf.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcldf.F90	(revision 5075)
@@ -25,5 +25,5 @@
    USE traldf_iso_grif ! lateral mixing          (tra_ldf_iso_grif routine)
    USE traldf_lap      ! lateral mixing            (tra_ldf_lap routine)
-   USE trdmod_oce
+   USE trd_oce
    USE trdtra
    USE prtctl_trc      ! Print control
@@ -73,16 +73,16 @@
 
       SELECT CASE ( nldf )                       ! compute lateral mixing trend and add it to the general trend
-      CASE ( 0 )   ;   CALL tra_ldf_lap   ( kt, nittrc000, 'TRC', gtru, gtrv, trb, tra, jptra            )  ! iso-level laplacian
+      CASE ( 0 )   ;   CALL tra_ldf_lap   ( kt, nittrc000, 'TRC', gtru, gtrv, gtrui, gtrvi, trb, tra, jptra        )  ! iso-level laplacian
       CASE ( 1 )                                                                                            ! rotated laplacian
                        IF( ln_traldf_grif ) THEN
                           CALL tra_ldf_iso_grif( kt, nittrc000, 'TRC', gtru, gtrv, trb, tra, jptra, rn_ahtb_0 )
                        ELSE
-                          CALL tra_ldf_iso     ( kt, nittrc000, 'TRC', gtru, gtrv, trb, tra, jptra, rn_ahtb_0 )
+                          CALL tra_ldf_iso     ( kt, nittrc000, 'TRC', gtru, gtrv, gtrui, gtrvi, trb, tra, jptra, rn_ahtb_0 )
                        ENDIF
-      CASE ( 2 )   ;   CALL tra_ldf_bilap ( kt, nittrc000, 'TRC', gtru, gtrv, trb, tra, jptra            )  ! iso-level bilaplacian
+      CASE ( 2 )   ;   CALL tra_ldf_bilap ( kt, nittrc000, 'TRC', gtru, gtrv, gtrui, gtrvi, trb, tra, jptra            )  ! iso-level bilaplacian
       CASE ( 3 )   ;   CALL tra_ldf_bilapg( kt, nittrc000, 'TRC',             trb, tra, jptra            )  ! s-coord. horizontal bilaplacian
          !
       CASE ( -1 )                                     ! esopa: test all possibility with control print
-         CALL tra_ldf_lap   ( kt, nittrc000, 'TRC', gtru, gtrv, trb, tra, jptra            )
+         CALL tra_ldf_lap   ( kt, nittrc000, 'TRC', gtru, gtrv, gtrui, gtrvi, trb, tra, jptra            )
          WRITE(charout, FMT="('ldf0 ')") ;  CALL prt_ctl_trc_info(charout)
                                             CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
@@ -90,9 +90,9 @@
             CALL tra_ldf_iso_grif( kt, nittrc000, 'TRC', gtru, gtrv, trb, tra, jptra, rn_ahtb_0 )
          ELSE
-            CALL tra_ldf_iso     ( kt, nittrc000, 'TRC', gtru, gtrv, trb, tra, jptra, rn_ahtb_0 )
+            CALL tra_ldf_iso     ( kt, nittrc000, 'TRC', gtru, gtrv, gtrui, gtrvi, trb, tra, jptra, rn_ahtb_0 )
          ENDIF
          WRITE(charout, FMT="('ldf1 ')") ;  CALL prt_ctl_trc_info(charout)
                                             CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
-         CALL tra_ldf_bilap ( kt, nittrc000, 'TRC', gtru, gtrv, trb, tra, jptra            )
+         CALL tra_ldf_bilap ( kt, nittrc000, 'TRC', gtru, gtrv, gtrui, gtrvi, trb, tra, jptra            )
          WRITE(charout, FMT="('ldf2 ')") ;  CALL prt_ctl_trc_info(charout)
                                             CALL prt_ctl_trc( tab4d=tra, mask=tmask, clinfo=ctrcnm, clinfo2='trd' )
@@ -105,5 +105,5 @@
         DO jn = 1, jptra
            ztrtrd(:,:,:,jn) = tra(:,:,:,jn) - ztrtrd(:,:,:,jn)
-           CALL trd_tra( kt, 'TRC', jn, jptra_trd_ldf, ztrtrd(:,:,:,jn) )
+           CALL trd_tra( kt, 'TRC', jn, jptra_ldf, ztrtrd(:,:,:,jn) )
         END DO
         CALL wrk_dealloc( jpi, jpj, jpk, jptra, ztrtrd )
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcnxt.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcnxt.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcnxt.F90	(revision 5075)
@@ -30,5 +30,5 @@
    USE lbclnk          ! ocean lateral boundary conditions (or mpp link)
    USE prtctl_trc      ! Print control for debbuging
-   USE trdmod_oce
+   USE trd_oce
    USE trdtra
    USE tranxt
@@ -148,5 +148,5 @@
                zfact = 1.e0 / r2dt(jk)  
                ztrdt(:,:,jk,jn) = ( trb(:,:,jk,jn) - ztrdt(:,:,jk,jn) ) * zfact 
-               CALL trd_tra( kt, 'TRC', jn, jptra_trd_atf, ztrdt )
+               CALL trd_tra( kt, 'TRC', jn, jptra_atf, ztrdt )
             END DO
          END DO
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcrad.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcrad.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcrad.F90	(revision 5075)
@@ -15,5 +15,5 @@
    USE oce_trc             ! ocean dynamics and tracers variables
    USE trc                 ! ocean passive tracers variables
-   USE trdmod_oce
+   USE trd_oce
    USE trdtra
    USE prtctl_trc          ! Print control for debbuging
@@ -156,6 +156,6 @@
                ztrtrdb(:,:,:) = ( ptrb(:,:,:,jn) - ztrtrdb(:,:,:) ) * zs2rdt
                ztrtrdn(:,:,:) = ( ptrn(:,:,:,jn) - ztrtrdn(:,:,:) ) * zs2rdt 
-               CALL trd_tra( kt, 'TRC', jn, jptra_trd_radb, ztrtrdb )       ! Asselin-like trend handling
-               CALL trd_tra( kt, 'TRC', jn, jptra_trd_radn, ztrtrdn )       ! standard     trend handling
+               CALL trd_tra( kt, 'TRC', jn, jptra_radb, ztrtrdb )       ! Asselin-like trend handling
+               CALL trd_tra( kt, 'TRC', jn, jptra_radn, ztrtrdn )       ! standard     trend handling
               !
             ENDIF
@@ -187,6 +187,6 @@
                ztrtrdb(:,:,:) = ( ptrb(:,:,:,jn) - ztrtrdb(:,:,:) ) * zs2rdt
                ztrtrdn(:,:,:) = ( ptrn(:,:,:,jn) - ztrtrdn(:,:,:) ) * zs2rdt 
-               CALL trd_tra( kt, 'TRC', jn, jptra_trd_radb, ztrtrdb )       ! Asselin-like trend handling
-               CALL trd_tra( kt, 'TRC', jn, jptra_trd_radn, ztrtrdn )       ! standard     trend handling
+               CALL trd_tra( kt, 'TRC', jn, jptra_radb, ztrtrdb )       ! Asselin-like trend handling
+               CALL trd_tra( kt, 'TRC', jn, jptra_radn, ztrtrdn )       ! standard     trend handling
               !
             ENDIF
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcsbc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcsbc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trcsbc.F90	(revision 5075)
@@ -19,5 +19,5 @@
    USE trc             ! ocean  passive tracers variables
    USE prtctl_trc      ! Print control for debbuging
-   USE trdmod_oce
+   USE trd_oce
    USE trdtra
 
@@ -104,5 +104,5 @@
          IF( l_trdtrc ) THEN
             ztrtrd(:,:,:) = tra(:,:,:,jn) - ztrtrd(:,:,:)
-            CALL trd_tra( kt, 'TRC', jn, jptra_trd_nsr, ztrtrd )
+            CALL trd_tra( kt, 'TRC', jn, jptra_nsr, ztrtrd )
          END IF
          !                                                       ! ===========
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trctrp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trctrp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trctrp.F90	(revision 5075)
@@ -82,5 +82,5 @@
       IF( .NOT. Agrif_Root())   CALL Agrif_Update_Trc( kstp )   ! Update tracer at AGRIF zoom boundaries : children only
 #endif
-         IF( ln_zps    )        CALL zps_hde( kstp, jptra, trn, gtru, gtrv )  ! Partial steps: now horizontal gradient of passive
+         IF( ln_zps    )        CALL zps_hde( kstp, jptra, trn, pgtu=gtru, pgtv=gtrv, sgtu=gtrui, sgtv=gtrvi )  ! Partial steps: now horizontal gradient of passive
                                                                 ! tracers at the bottom ocean level
          !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trczdf.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trczdf.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trczdf.F90	(revision 5075)
@@ -19,5 +19,5 @@
    USE trazdf_exp      ! vertical diffusion: explicit (tra_zdf_exp     routine)
    USE trazdf_imp      ! vertical diffusion: implicit (tra_zdf_imp     routine)
-   USE trdmod_oce
+   USE trd_oce
    USE trdtra
    USE prtctl_trc      ! Print control
@@ -106,5 +106,5 @@
                ztrtrd(:,:,jk,jn) = ( ( tra(:,:,jk,jn) - trb(:,:,jk,jn) ) / r2dt(jk) ) - ztrtrd(:,:,jk,jn)
             END DO
-            CALL trd_tra( kt, 'TRC', jn, jptra_trd_zdf, ztrtrd(:,:,:,jn) )
+            CALL trd_tra( kt, 'TRC', jn, jptra_zdf, ztrtrd(:,:,:,jn) )
          END DO
          CALL wrk_dealloc( jpi, jpj, jpk, jptra, ztrtrd )
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmld_trc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmld_trc.F90	(revision 5074)
+++ 	(revision )
@@ -1,1437 +1,0 @@
-MODULE trdmld_trc
-   !!======================================================================
-   !!                       ***  MODULE  trdmld_trc  ***
-   !! Ocean diagnostics:  mixed layer passive tracer trends 
-   !!======================================================================
-   !! History :  9.0  !  06-08  (C. Deltel)  Original code (from trdmld.F90)
-   !!                 !  07-04  (C. Deltel)  Bug fix : add trcrad trends
-   !!                 !  07-06  (C. Deltel)  key_gyre : do not call lbc_lnk
-   !!----------------------------------------------------------------------
-#if   defined key_top && ( defined key_trdmld_trc   ||   defined key_esopa )
-   !!----------------------------------------------------------------------
-   !!   'key_trdmld_trc'                      mixed layer trend diagnostics
-   !!----------------------------------------------------------------------
-   !!   trd_mld_trc      : passive tracer cumulated trends averaged over ML
-   !!   trd_mld_trc_zint : passive tracer trends vertical integration
-   !!   trd_mld_trc_init : initialization step
-   !!----------------------------------------------------------------------
-   USE trc               ! tracer definitions (trn, trb, tra, etc.)
-   USE trc_oce, ONLY :   nn_dttrc  ! frequency of step on passive tracers
-   USE dom_oce           ! domain definition
-   USE zdfmxl  , ONLY : nmln ! number of level in the mixed layer
-   USE zdf_oce , ONLY : avt  ! vert. diffusivity coef. at w-point for temp  
-# if defined key_zdfddm   
-   USE zdfddm  , ONLY : avs  ! salinity vertical diffusivity coeff. at w-point
-# endif
-   USE trcnam_trp        ! passive tracers transport namelist variables
-   USE trdmod_trc_oce    ! definition of main arrays used for trends computations
-   USE in_out_manager    ! I/O manager
-   USE dianam            ! build the name of file (routine)
-   USE ldfslp            ! iso-neutral slopes 
-   USE ioipsl            ! NetCDF library
-   USE lbclnk            ! ocean lateral boundary conditions (or mpp link)
-   USE lib_mpp           ! MPP library
-   USE trdmld_trc_rst    ! restart for diagnosing the ML trends
-   USE prtctl            ! print control
-   USE sms_pisces        ! PISCES bio-model
-   USE wrk_nemo          ! Memory allocation
-
-   IMPLICIT NONE
-   PRIVATE
-
-   PUBLIC trd_mld_trc
-   PUBLIC trd_mld_trc_alloc
-   PUBLIC trd_mld_bio
-   PUBLIC trd_mld_trc_init
-   PUBLIC trd_mld_trc_zint
-   PUBLIC trd_mld_bio_zint
-
-   CHARACTER (LEN=40) ::  clhstnam                                ! name of the trends NetCDF file
-   INTEGER ::   nmoymltrd
-   INTEGER, ALLOCATABLE, SAVE, DIMENSION(:) ::   ndextrd1
-   INTEGER, DIMENSION(jptra) ::   nidtrd, nh_t
-   INTEGER ::   ndimtrd1                        
-   INTEGER, SAVE ::  ionce, icount
-#if defined key_pisces_reduced
-   INTEGER ::   nidtrdbio, nh_tb
-   INTEGER, SAVE ::  ioncebio, icountbio
-   INTEGER, SAVE ::   nmoymltrdbio
-#endif
-   LOGICAL :: llwarn  = .TRUE.                                    ! this should always be .TRUE.
-   LOGICAL :: lldebug = .TRUE.
-
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  ztmltrd2   !
-#if defined key_pisces_reduced
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  ztmltrdbio2  ! only needed for mean diagnostics in trd_mld_bio()
-#endif
-
-   !! * Substitutions
-#  include "top_substitute.h90"
-#  include "zdfddm_substitute.h90"
-   !!----------------------------------------------------------------------
-   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
-   !! $Header:  $ 
-   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-CONTAINS
-
-   INTEGER FUNCTION trd_mld_trc_alloc()
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld_trc_alloc  ***
-      !!----------------------------------------------------------------------
-      ALLOCATE( ztmltrd2(jpi,jpj,jpltrd_trc,jptra) ,      &
-#if defined key_pisces_reduced
-         &      ztmltrdbio2(jpi,jpj,jpdiabio)      ,      &
-#endif
-         &      ndextrd1(jpi*jpj)                  ,  STAT=trd_mld_trc_alloc)
-         !
-      IF( lk_mpp                )   CALL mpp_sum ( trd_mld_trc_alloc )
-      IF( trd_mld_trc_alloc /=0 )   CALL ctl_warn('trd_mld_trc_alloc: failed to allocate arrays')
-      !
-   END FUNCTION trd_mld_trc_alloc
-
-
-   SUBROUTINE trd_mld_trc_zint( ptrc_trdmld, ktrd, ctype, kjn )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld_trc_zint  ***
-      !! 
-      !! ** Purpose :   Compute the vertical average of the 3D fields given as arguments 
-      !!                to the subroutine. This vertical average is performed from ocean
-      !!                surface down to a chosen control surface.
-      !!
-      !! ** Method/usage :
-      !!      The control surface can be either a mixed layer depth (time varying)
-      !!      or a fixed surface (jk level or bowl). 
-      !!      Choose control surface with nctls_trc in namelist NAMTRD :
-      !!        nctls_trc = -2  : use isopycnal surface
-      !!        nctls_trc = -1  : use euphotic layer with light criterion 
-      !!        nctls_trc =  0  : use mixed layer with density criterion 
-      !!        nctls_trc =  1  : read index from file 'ctlsurf_idx'
-      !!        nctls_trc >  1  : use fixed level surface jk = nctls_trc
-      !!      Note: in the remainder of the routine, the volume between the 
-      !!            surface and the control surface is called "mixed-layer"
-      !!----------------------------------------------------------------------
-      !!
-      INTEGER, INTENT( in ) ::   ktrd, kjn                        ! ocean trend index and passive tracer rank
-      CHARACTER(len=2), INTENT( in ) ::  ctype                    ! surface/bottom (2D) or interior (3D) physics
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( in ) ::  ptrc_trdmld ! passive tracer trend
-      !
-      INTEGER ::   ji, jj, jk, isum
-      REAL(wp), POINTER, DIMENSION(:,:) :: zvlmsk
-      !!----------------------------------------------------------------------
-
-      CALL wrk_alloc( jpi, jpj, zvlmsk )
-
-      ! I. Definition of control surface and integration weights
-      ! --------------------------------------------------------
-
-      ONCE_PER_TIME_STEP : IF( icount == 1 ) THEN
-         !
-         tmltrd_trc(:,:,:,:) = 0.e0                               ! <<< reset trend arrays to zero
-          
-         ! ... Set nmld(ji,jj) = index of first T point below control surf. or outside mixed-layer
-         SELECT CASE ( nn_ctls_trc )                                ! choice of the control surface
-            CASE ( -2  )   ;   STOP 'trdmld_trc : not ready '     !     -> isopycnal surface (see ???)
-#if defined key_pisces || defined key_pisces_reduced
-            CASE ( -1  )   ;   nmld_trc(:,:) = neln(:,:)          !     -> euphotic layer with light criterion
-#endif
-            CASE (  0  )   ;   nmld_trc(:,:) = nmln(:,:)          !     -> ML with density criterion (see zdfmxl)
-            CASE (  1  )   ;   nmld_trc(:,:) = nbol_trc(:,:)          !     -> read index from file
-            CASE (  2: )   ;   nn_ctls_trc = MIN( nn_ctls_trc, jpktrd_trc - 1 )
-                               nmld_trc(:,:) = nn_ctls_trc + 1      !     -> model level
-         END SELECT
-
-         ! ... Compute ndextrd1 and ndimtrd1  ??? role de jpktrd_trc
-         IF( ionce == 1 ) THEN
-            !
-            isum  = 0   ;   zvlmsk(:,:) = 0.e0
-
-            IF( jpktrd_trc < jpk ) THEN                           ! description ???
-               DO jj = 1, jpj
-                  DO ji = 1, jpi
-                     IF( nmld_trc(ji,jj) <= jpktrd_trc ) THEN
-                        zvlmsk(ji,jj) = tmask(ji,jj,1)
-                     ELSE
-                        isum = isum + 1
-                        zvlmsk(ji,jj) = 0.e0
-                     ENDIF
-                  END DO
-               END DO
-            ENDIF
-
-            IF( isum > 0 ) THEN                                   ! index of ocean points (2D only)
-               WRITE(numout,*)' tmltrd_trc : Number of invalid points nmld_trc > jpktrd', isum 
-               CALL wheneq( jpi*jpj, zvlmsk(:,:) , 1, 1., ndextrd1, ndimtrd1 )
-            ELSE 
-               CALL wheneq( jpi*jpj, tmask(:,:,1), 1, 1., ndextrd1, ndimtrd1 )
-            ENDIF                                
-
-            ionce = 0                                             ! no more pass here
-            !
-         ENDIF   ! ionce == 1
-         
-         ! ... Weights for vertical averaging
-         wkx_trc(:,:,:) = 0.e0
-         DO jk = 1, jpktrd_trc                                    ! initialize wkx_trc with vertical scale factor in mixed-layer
-            DO jj = 1, jpj
-               DO ji = 1, jpi
-                  IF( jk - nmld_trc(ji,jj) < 0 )   wkx_trc(ji,jj,jk) = fse3t(ji,jj,jk) * tmask(ji,jj,jk)
-               END DO
-            END DO
-         END DO
-         
-         rmld_trc(:,:) = 0.e0
-         DO jk = 1, jpktrd_trc                                    ! compute mixed-layer depth : rmld_trc
-            rmld_trc(:,:) = rmld_trc(:,:) + wkx_trc(:,:,jk)
-         END DO
-         
-         DO jk = 1, jpktrd_trc                                    ! compute integration weights
-            wkx_trc(:,:,jk) = wkx_trc(:,:,jk) / MAX( 1., rmld_trc(:,:) )
-         END DO
-
-         icount = 0                                               ! <<< flag = off : control surface & integr. weights
-         !                                                        !     computed only once per time step
-      ENDIF ONCE_PER_TIME_STEP
-
-      ! II. Vertical integration of trends in the mixed-layer
-      ! -----------------------------------------------------
-
-      SELECT CASE ( ctype )
-         CASE ( '3D' )                                            ! mean passive tracer trends in the mixed-layer
-            DO jk = 1, jpktrd_trc
-               tmltrd_trc(:,:,ktrd,kjn) = tmltrd_trc(:,:,ktrd,kjn) + ptrc_trdmld(:,:,jk) * wkx_trc(:,:,jk)   
-            END DO
-         CASE ( '2D' )                                            ! forcing at upper boundary of the mixed-layer 
-            tmltrd_trc(:,:,ktrd,kjn) = tmltrd_trc(:,:,ktrd,kjn) + ptrc_trdmld(:,:,1) * wkx_trc(:,:,1)  ! non penetrative
-      END SELECT
-      !
-      CALL wrk_dealloc( jpi, jpj, zvlmsk )
-      !
-   END SUBROUTINE trd_mld_trc_zint
-
-
-   SUBROUTINE trd_mld_bio_zint( ptrc_trdmld, ktrd )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld_bio_zint  ***
-      !!
-      !! ** Purpose :   Compute the vertical average of the 3D fields given as arguments
-      !!                to the subroutine. This vertical average is performed from ocean
-      !!                surface down to a chosen control surface.
-      !!
-      !! ** Method/usage :
-      !!      The control surface can be either a mixed layer depth (time varying)
-      !!      or a fixed surface (jk level or bowl).
-      !!      Choose control surface with nctls in namelist NAMTRD :
-      !!        nctls_trc = 0  : use mixed layer with density criterion
-      !!        nctls_trc = 1  : read index from file 'ctlsurf_idx'
-      !!        nctls_trc > 1  : use fixed level surface jk = nctls_trc
-      !!      Note: in the remainder of the routine, the volume between the
-      !!            surface and the control surface is called "mixed-layer"
-      !!----------------------------------------------------------------------
-      !!
-      INTEGER                         , INTENT(in) ::   ktrd          ! bio trend index
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in) ::   ptrc_trdmld   ! passive trc trend
-#if defined key_pisces_reduced
-      !
-      INTEGER ::   ji, jj, jk, isum
-      REAL(wp), POINTER, DIMENSION(:,:) :: zvlmsk
-      !!----------------------------------------------------------------------
-
-      CALL wrk_alloc( jpi, jpj, zvlmsk )
-
-      ! I. Definition of control surface and integration weights
-      ! --------------------------------------------------------
-      !            ==> only once per time step <==
-
-      IF( icountbio == 1 ) THEN
-         !
-         tmltrd_bio(:,:,:) = 0.e0    ! <<< reset trend arrays to zero
-         ! ... Set nmld(ji,jj) = index of first T point below control surf. or outside mixed-layer
-         SELECT CASE ( nn_ctls_trc )                                    ! choice of the control surface
-            CASE ( -2  )   ;   STOP 'trdmld_trc : not ready '     !     -> isopycnal surface (see ???)
-            CASE ( -1  )   ;   nmld_trc(:,:) = neln(:,:)          !     -> euphotic layer with light criterion
-            CASE (  0  )   ;   nmld_trc(:,:) = nmln(:,:)          !     -> ML with density criterion (see zdfmxl)
-            CASE (  1  )   ;   nmld_trc(:,:) = nbol_trc(:,:)          !     -> read index from file
-            CASE (  2: )   ;   nn_ctls_trc = MIN( nn_ctls_trc, jpktrd_trc - 1 )
-                               nmld_trc(:,:) = nn_ctls_trc + 1          !     -> model level
-         END SELECT
-
-         ! ... Compute ndextrd1 and ndimtrd1 only once
-         IF( ioncebio == 1 ) THEN
-            !
-            ! Check of validity : nmld_trc(ji,jj) <= jpktrd_trc
-            isum        = 0
-            zvlmsk(:,:) = 0.e0
-
-            IF( jpktrd_trc < jpk ) THEN
-               DO jj = 1, jpj
-                  DO ji = 1, jpi
-                     IF( nmld_trc(ji,jj) <= jpktrd_trc ) THEN
-                        zvlmsk(ji,jj) = tmask(ji,jj,1)
-                     ELSE
-                        isum = isum + 1
-                        zvlmsk(ji,jj) = 0.
-                     END IF
-                  END DO
-               END DO
-            END IF
-
-            ! Index of ocean points (2D only)
-            IF( isum > 0 ) THEN
-               WRITE(numout,*)' tmltrd_trc : Number of invalid points nmld_trc > jpktrd', isum
-               CALL wheneq( jpi*jpj, zvlmsk(:,:) , 1, 1., ndextrd1, ndimtrd1 )
-            ELSE
-               CALL wheneq( jpi*jpj, tmask(:,:,1), 1, 1., ndextrd1, ndimtrd1 )
-            END IF
-
-            ioncebio = 0                  ! no more pass here
-            !
-         END IF !  ( ioncebio == 1 )
-
-         ! ... Weights for vertical averaging
-         wkx_trc(:,:,:) = 0.e0
-         DO jk = 1, jpktrd_trc         ! initialize wkx_trc with vertical scale factor in mixed-layer
-            DO jj = 1,jpj
-              DO ji = 1,jpi
-                  IF( jk - nmld_trc(ji,jj) < 0. )   wkx_trc(ji,jj,jk) = fse3t(ji,jj,jk) * tmask(ji,jj,jk)
-               END DO
-            END DO
-         END DO
-
-         rmld_trc(:,:) = 0.
-         DO jk = 1, jpktrd_trc         ! compute mixed-layer depth : rmld_trc
-            rmld_trc(:,:) = rmld_trc(:,:) + wkx_trc(:,:,jk)
-         END DO
-
-         DO jk = 1, jpktrd_trc         ! compute integration weights
-            wkx_trc(:,:,jk) = wkx_trc(:,:,jk) / MAX( 1., rmld_trc(:,:) )
-         END DO
-
-         icountbio = 0                    ! <<< flag = off : control surface & integr. weights
-         !                             !     computed only once per time step
-      END IF ! ( icountbio == 1 )
-
-      ! II. Vertical integration of trends in the mixed-layer
-      ! -----------------------------------------------------
-
-
-      DO jk = 1, jpktrd_trc
-         tmltrd_bio(:,:,ktrd) = tmltrd_bio(:,:,ktrd) + ptrc_trdmld(:,:,jk) * wkx_trc(:,:,jk)
-      END DO
-
-      CALL wrk_dealloc( jpi, jpj, zvlmsk )
-#endif
-      !
-   END SUBROUTINE trd_mld_bio_zint
-
-
-   SUBROUTINE trd_mld_trc( kt )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld_trc  ***
-      !! 
-      !! ** Purpose :  Compute and cumulate the mixed layer trends over an analysis
-      !!               period, and write NetCDF (or dimg) outputs.
-      !!
-      !! ** Method/usage :
-      !!          The stored trends can be chosen twofold (according to the ln_trdmld_trc_instant 
-      !!          logical namelist variable) :
-      !!          1) to explain the difference between initial and final 
-      !!             mixed-layer T & S (where initial and final relate to the
-      !!             current analysis window, defined by ntrc_trc in the namelist)
-      !!          2) to explain the difference between the current and previous 
-      !!             TIME-AVERAGED mixed-layer T & S (where time-averaging is
-      !!             performed over each analysis window).
-      !!
-      !! ** Consistency check : 
-      !!        If the control surface is fixed ( nctls_trc > 1 ), the residual term (dh/dt
-      !!        entrainment) should be zero, at machine accuracy. Note that in the case
-      !!        of time-averaged mixed-layer fields, this residual WILL NOT BE ZERO
-      !!        over the first two analysis windows (except if restart).
-      !!        N.B. For ORCA2_LIM, use e.g. ntrc_trc=5, rn_ucf_trc=1., nctls_trc=8
-      !!             for checking residuals.
-      !!             On a NEC-SX5 computer, this typically leads to:
-      !!                   O(1.e-20) temp. residuals (tml_res) when ln_trdmld_trc_instant=.false.
-      !!                   O(1.e-21) temp. residuals (tml_res) when ln_trdmld_trc_instant=.true.
-      !!
-      !! ** Action :
-      !!       At each time step, mixed-layer averaged trends are stored in the 
-      !!       tmltrd(:,:,jpmld_xxx) array (see trdmld_oce.F90 for definitions of jpmld_xxx).
-      !!       This array is known when trd_mld is called, at the end of the stp subroutine, 
-      !!       except for the purely vertical K_z diffusion term, which is embedded in the
-      !!       lateral diffusion trend.
-      !!
-      !!       In I), this K_z term is diagnosed and stored, thus its contribution is removed
-      !!       from the lateral diffusion trend.
-      !!       In II), the instantaneous mixed-layer T & S are computed, and misc. cumulative
-      !!       arrays are updated.
-      !!       In III), called only once per analysis window, we compute the total trends,
-      !!       along with the residuals and the Asselin correction terms.
-      !!       In IV), the appropriate trends are written in the trends NetCDF file.
-      !!
-      !! References :
-      !!       - Vialard & al.
-      !!       - See NEMO documentation (in preparation)
-      !!----------------------------------------------------------------------
-      !
-      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
-      !
-      INTEGER ::   ji, jj, jk, jl, ik, it, itmod, jn
-      REAL(wp) ::   zavt, zfn, zfn2
-      !
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmltot             ! d(trc)/dt over the anlysis window (incl. Asselin)
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlres             ! residual = dh/dt entrainment term
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlatf             ! for storage only
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlrad             ! for storage only (for trb<0 corr in trcrad)
-      !
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmltot2            ! -+
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlres2            !  | working arrays to diagnose the trends
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmltrdm2           !  | associated with the time meaned ML
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlatf2            !  | passive tracers
-      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlrad2            !  | (-> for trb<0 corr in trcrad)
-      !
-      CHARACTER (LEN=10) ::   clvar
-#if defined key_dimgout
-      INTEGER ::   iyear,imon,iday
-      CHARACTER(LEN=80) ::   cltext, clmode
-#endif
-      !!----------------------------------------------------------------------
-
-      ! Set-up pointers into sub-arrays of workspaces
-      CALL wrk_alloc( jpi, jpj, jptra, ztmltot , ztmlres , ztmlatf , ztmlrad             )
-      CALL wrk_alloc( jpi, jpj, jptra, ztmltot2, ztmlres2, ztmlatf2, ztmlrad2, ztmltrdm2 )
-
-      IF( nn_dttrc  /= 1  )   CALL ctl_stop( " Be careful, trends diags never validated " )
-
-      ! ======================================================================
-      ! I. Diagnose the purely vertical (K_z) diffusion trend
-      ! ======================================================================
-
-      ! ... These terms can be estimated by flux computation at the lower boundary of the ML 
-      !     (we compute (-1/h) * K_z * d_z( tracer ))
-
-      IF( ln_trcldf_iso ) THEN
-         !
-         DO jj = 1,jpj
-            DO ji = 1,jpi
-               ik = nmld_trc(ji,jj)
-               zavt = fsavs(ji,jj,ik)
-               DO jn = 1, jptra
-                  IF( ln_trdtrc(jn) )    &
-                  tmltrd_trc(ji,jj,jpmld_trc_zdf,jn) = - zavt / fse3w(ji,jj,ik) * tmask(ji,jj,ik)  &
-                       &                    * ( trn(ji,jj,ik-1,jn) - trn(ji,jj,ik,jn) )            &
-                       &                    / MAX( 1., rmld_trc(ji,jj) ) * tmask(ji,jj,1)
-               END DO
-            END DO
-         END DO
-
-         DO jn = 1, jptra
-            ! ... Remove this K_z trend from the iso-neutral diffusion term (if any)
-            IF( ln_trdtrc(jn) ) &
-                 tmltrd_trc(:,:,jpmld_trc_ldf,jn) = tmltrd_trc(:,:,jpmld_trc_ldf,jn) - tmltrd_trc(:,:,jpmld_trc_zdf,jn)
-   
-         END DO
-         !      
-      ENDIF
-
-      IF ( cp_cfg .NE. 'gyre' ) THEN            ! other than GYRE configuration
-      ! GYRE : for diagnostic fields, are needed if cyclic B.C. are present, but not for purely MPI comm. 
-      ! therefore we do not call lbc_lnk in GYRE config. (closed basin, no cyclic B.C.)
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN
-               DO jl = 1, jpltrd_trc
-                  CALL lbc_lnk( tmltrd_trc(:,:,jl,jn), 'T', 1. )        ! lateral boundary conditions
-               END DO
-            ENDIF
-         END DO
-      ENDIF
-      ! ======================================================================
-      ! II. Cumulate the trends over the analysis window
-      ! ======================================================================
-
-      ztmltrd2(:,:,:,:) = 0.e0   ;   ztmltot2(:,:,:)   = 0.e0     ! <<< reset arrays to zero
-      ztmlres2(:,:,:)   = 0.e0   ;   ztmlatf2(:,:,:)   = 0.e0
-      ztmlrad2(:,:,:)   = 0.e0
-
-      ! II.1 Set before values of vertically averages passive tracers
-      ! -------------------------------------------------------------
-      IF( kt > nittrc000 ) THEN
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN
-               tmlb_trc   (:,:,jn) = tml_trc   (:,:,jn)
-               tmlatfn_trc(:,:,jn) = tmltrd_trc(:,:,jpmld_trc_atf,jn)
-               tmlradn_trc(:,:,jn) = tmltrd_trc(:,:,jpmld_trc_radb,jn)
-            ENDIF
-         END DO
-      ENDIF
-
-      ! II.2 Vertically averaged passive tracers
-      ! ----------------------------------------
-      tml_trc(:,:,:) = 0.e0
-      DO jk = 1, jpktrd_trc ! - 1 ???
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) &
-               tml_trc(:,:,jn) = tml_trc(:,:,jn) + wkx_trc(:,:,jk) * trn(:,:,jk,jn)
-         END DO
-      END DO
-
-      ! II.3 Initialize mixed-layer "before" arrays for the 1rst analysis window    
-      ! ------------------------------------------------------------------------
-      IF( kt == nittrc000 + nn_dttrc ) THEN  !  i.e. ( .NOT. ln_rstart ).AND.( kt == nit000 + 1)    ???
-         !
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN
-               tmlbb_trc  (:,:,jn) = tmlb_trc   (:,:,jn)   ;   tmlbn_trc  (:,:,jn) = tml_trc    (:,:,jn)
-               tmlatfb_trc(:,:,jn) = tmlatfn_trc(:,:,jn)   ;   tmlradb_trc(:,:,jn) = tmlradn_trc(:,:,jn)
-               
-               tmltrd_csum_ub_trc (:,:,:,jn) = 0.e0   ;   tmltrd_atf_sumb_trc  (:,:,jn) = 0.e0
-               tmltrd_rad_sumb_trc  (:,:,jn) = 0.e0
-            ENDIF
-         END DO
-         
-         rmldbn_trc(:,:) = rmld_trc(:,:)
-         !
-      ENDIF
-
-      ! II.4 Cumulated trends over the analysis period
-      ! ----------------------------------------------
-      !
-      !         [  1rst analysis window ] [     2nd analysis window     ]                       
-      !
-      !     o---[--o-----o-----o-----o--]-[--o-----o-----o-----o-----o--]---o-----o--> time steps
-      !                            ntrd                             2*ntrd       etc.
-      !     1      2     3     4    =5 e.g.                          =10
-      !
-      IF( ( kt >= 2 ).OR.( ln_rsttr ) ) THEN                        ! ???
-         !
-         nmoymltrd = nmoymltrd + 1
-
-
-         ! ... Cumulate over BOTH physical contributions AND over time steps
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN
-               DO jl = 1, jpltrd_trc
-                  tmltrdm_trc(:,:,jn) = tmltrdm_trc(:,:,jn) + tmltrd_trc(:,:,jl,jn)
-               END DO
-            ENDIF
-         END DO
-
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN
-               ! ... Special handling of the Asselin trend 
-               tmlatfm_trc(:,:,jn) = tmlatfm_trc(:,:,jn) + tmlatfn_trc(:,:,jn)
-               tmlradm_trc(:,:,jn) = tmlradm_trc(:,:,jn) + tmlradn_trc(:,:,jn)
-
-               ! ... Trends associated with the time mean of the ML passive tracers
-               tmltrd_sum_trc    (:,:,:,jn) = tmltrd_sum_trc    (:,:,:,jn) + tmltrd_trc    (:,:,:,jn)
-               tmltrd_csum_ln_trc(:,:,:,jn) = tmltrd_csum_ln_trc(:,:,:,jn) + tmltrd_sum_trc(:,:,:,jn)
-               tml_sum_trc       (:,:,jn)   = tml_sum_trc       (:,:,jn)   + tml_trc       (:,:,jn)
-            ENDIF
-         ENDDO
-
-         rmld_sum_trc      (:,:)     = rmld_sum_trc      (:,:)     + rmld_trc      (:,:)
-         !
-      ENDIF
-
-      ! ======================================================================
-      ! III. Prepare fields for output (get here ONCE PER ANALYSIS PERIOD)
-      ! ======================================================================
-
-      ! Convert to appropriate physical units
-      tmltrd_trc(:,:,:,:) = tmltrd_trc(:,:,:,:) * rn_ucf_trc
-
-      itmod = kt - nittrc000 + 1
-      it    = kt
-
-      MODULO_NTRD : IF( MOD( itmod, nn_trd_trc ) == 0 ) THEN           ! nitend MUST be multiple of nn_trd_trc
-         !
-         ztmltot (:,:,:) = 0.e0                                   ! reset arrays to zero
-         ztmlres (:,:,:) = 0.e0
-         ztmltot2(:,:,:) = 0.e0
-         ztmlres2(:,:,:) = 0.e0
-      
-         zfn  = FLOAT( nmoymltrd )    ;    zfn2 = zfn * zfn
-         
-         ! III.1 Prepare fields for output ("instantaneous" diagnostics) 
-         ! -------------------------------------------------------------
-
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN
-               !-- Compute total trends    (use rdttrc instead of rdt ???)
-               IF ( ln_trcadv_muscl .OR. ln_trcadv_muscl2 ) THEN  ! EULER-FORWARD schemes
-                  ztmltot(:,:,jn) =  ( tml_trc(:,:,jn) - tmlbn_trc(:,:,jn) )/rdt
-               ELSE                                                                     ! LEAP-FROG schemes
-                  ztmltot(:,:,jn) =  ( tml_trc(:,:,jn) - tmlbn_trc(:,:,jn) + tmlb_trc(:,:,jn) - tmlbb_trc(:,:,jn))/(2.*rdt)
-               ENDIF
-               
-               !-- Compute residuals
-               ztmlres(:,:,jn) = ztmltot(:,:,jn) - ( tmltrdm_trc(:,:,jn) - tmlatfn_trc(:,:,jn) + tmlatfb_trc(:,:,jn) &
-                  &                                                 - tmlradn_trc(:,:,jn) + tmlradb_trc(:,:,jn)  )
-               
-               !-- Diagnose Asselin trend over the analysis window 
-               ztmlatf(:,:,jn) = tmlatfm_trc(:,:,jn) - tmlatfn_trc(:,:,jn) + tmlatfb_trc(:,:,jn)
-               ztmlrad(:,:,jn) = tmlradm_trc(:,:,jn) - tmlradn_trc(:,:,jn) + tmlradb_trc(:,:,jn)
-               
-         !-- Lateral boundary conditions
-               IF ( cp_cfg .NE. 'gyre' ) THEN
-                  CALL lbc_lnk( ztmltot(:,:,jn) , 'T', 1. )   ;   CALL lbc_lnk( ztmlres(:,:,jn) , 'T', 1. )
-                  CALL lbc_lnk( ztmlatf(:,:,jn) , 'T', 1. )   ;   CALL lbc_lnk( ztmlrad(:,:,jn) , 'T', 1. )
-               ENDIF
-
-
-#if defined key_diainstant
-               STOP 'tmltrd_trc : key_diainstant was never checked within trdmld. Comment this to proceed.'
-#endif
-            ENDIF
-         END DO
-
-         ! III.2 Prepare fields for output ("mean" diagnostics) 
-         ! ----------------------------------------------------
-         
-         !-- Update the ML depth time sum (to build the Leap-Frog time mean)
-         rmld_sum_trc(:,:) = rmldbn_trc(:,:) + 2 * ( rmld_sum_trc(:,:) - rmld_trc(:,:) ) + rmld_trc(:,:)
-
-               !-- Compute passive tracer total trends
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN
-               tml_sum_trc(:,:,jn) = tmlbn_trc(:,:,jn) + 2 * ( tml_sum_trc(:,:,jn) - tml_trc(:,:,jn) ) + tml_trc(:,:,jn)
-               ztmltot2   (:,:,jn) = ( tml_sum_trc(:,:,jn) - tml_sumb_trc(:,:,jn) ) /  ( 2.*rdt )    ! now tracer unit is /sec
-            ENDIF
-         END DO
-
-         !-- Compute passive tracer residuals
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN
-               !
-               DO jl = 1, jpltrd_trc
-                  ztmltrd2(:,:,jl,jn) = tmltrd_csum_ub_trc(:,:,jl,jn) + tmltrd_csum_ln_trc(:,:,jl,jn)
-               END DO
-               
-               ztmltrdm2(:,:,jn) = 0.e0
-               DO jl = 1, jpltrd_trc
-                  ztmltrdm2(:,:,jn) = ztmltrdm2(:,:,jn) + ztmltrd2(:,:,jl,jn)
-               END DO
-               
-               ztmlres2(:,:,jn) =  ztmltot2(:,:,jn)  -       &
-                  & ( ztmltrdm2(:,:,jn) - tmltrd_sum_trc(:,:,jpmld_trc_atf ,jn) + tmltrd_atf_sumb_trc(:,:,jn) &
-                  &                     - tmltrd_sum_trc(:,:,jpmld_trc_radb,jn) + tmltrd_rad_sumb_trc(:,:,jn) )
-               !
-
-               !-- Diagnose Asselin trend over the analysis window
-               ztmlatf2(:,:,jn) = ztmltrd2(:,:,jpmld_trc_atf ,jn) - tmltrd_sum_trc(:,:,jpmld_trc_atf ,jn) &
-                  &                                               + tmltrd_atf_sumb_trc(:,:,jn)
-               ztmlrad2(:,:,jn) = ztmltrd2(:,:,jpmld_trc_radb,jn) - tmltrd_sum_trc(:,:,jpmld_trc_radb,jn) &
-                  &                                               + tmltrd_rad_sumb_trc(:,:,jn)
-
-         !-- Lateral boundary conditions 
-               IF ( cp_cfg .NE. 'gyre' ) THEN            ! other than GYRE configuration    
-                  CALL lbc_lnk( ztmltot2(:,:,jn), 'T', 1. )
-                  CALL lbc_lnk( ztmlres2(:,:,jn), 'T', 1. )
-                  DO jl = 1, jpltrd_trc
-                     CALL lbc_lnk( ztmltrd2(:,:,jl,jn), 'T', 1. )       ! will be output in the NetCDF trends file
-                  END DO
-               ENDIF
-
-            ENDIF
-         END DO
-
-         ! * Debugging information *
-         IF( lldebug ) THEN
-            !
-            WRITE(numout,*) 'trd_mld_trc : write trends in the Mixed Layer for debugging process:'
-            WRITE(numout,*) '~~~~~~~~~~~  '
-            WRITE(numout,*)
-            WRITE(numout,*) 'TRC kt = ', kt, '    nmoymltrd = ', nmoymltrd
-
-            DO jn = 1, jptra
-
-               IF( ln_trdtrc(jn) ) THEN
-                  WRITE(numout, *)
-                  WRITE(numout, *) '>>>>>>>>>>>>>>>>>>  TRC TRACER jn =', jn, ' <<<<<<<<<<<<<<<<<<'
-                  
-                  WRITE(numout, *)
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ztmlres     : ', SUM2D(ztmlres(:,:,jn))
-                  !CD??? PREVOIR: z2d = ztmlres(:,:,jn)   ;   CALL prt_ctl(tab2d_1=z2d, clinfo1=' ztmlres   -   : ')
-                  
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ABS(ztmlres): ', SUM2D(ABS(ztmlres(:,:,jn)))
-                  WRITE(numout, '(3x,a)') ' -->>>------------------- ztmlres is computed from ------------- '
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +ztmltot    : ', SUM2D(+ztmltot    (:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmltrdm_trc: ', SUM2D(+tmltrdm_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmlatfn_trc: ', SUM2D(-tmlatfn_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmlatfb_trc: ', SUM2D(+tmlatfb_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmlradn_trc: ', SUM2D(-tmlradn_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmlradb_trc: ', SUM2D(+tmlradb_trc(:,:,jn))
-                  WRITE(numout, '(3x,a)') ' --<<<----------------------------------------------------------- '
-                  
-                  WRITE(numout, *)
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ztmlres2    : ', SUM2D(ztmlres2(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ABS(ztmlres2):', SUM2D(ABS(ztmlres2(:,:,jn)))
-                  WRITE(numout, '(3x,a)') ' -->>>------------------- ztmlres2 is computed from ------------ '
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +ztmltot2            : ', SUM2D(+ztmltot2(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +ztmltrdm2           : ', SUM2D(+ztmltrdm2(:,:,jn)) 
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmltrd_sum_trc      : ', SUM2D(-tmltrd_sum_trc(:,:,jpmld_trc_atf,jn)) 
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmltrd_atf_sumb_trc : ', SUM2D(+tmltrd_atf_sumb_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmltrd_sum_trc      : ', SUM2D(-tmltrd_sum_trc(:,:,jpmld_trc_radb,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmltrd_rad_sumb_trc : ', SUM2D(+tmltrd_rad_sumb_trc(:,:,jn) )
-                  WRITE(numout, '(3x,a)') ' --<<<----------------------------------------------------------- '
-                  
-                  WRITE(numout, *)
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ztmltot     : ', SUM2D(ztmltot    (:,:,jn))
-                  WRITE(numout, '(3x,a)') ' -->>>------------------- ztmltot is computed from ------------- '
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tml_trc    : ', SUM2D(tml_trc    (:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmlbn_trc  : ', SUM2D(tmlbn_trc  (:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmlb_trc   : ', SUM2D(tmlb_trc   (:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmlbb_trc  : ', SUM2D(tmlbb_trc  (:,:,jn))
-                  WRITE(numout, '(3x,a)') ' --<<<----------------------------------------------------------- '
-                  
-                  WRITE(numout, *)
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmltrdm_trc : ', SUM2D(tmltrdm_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmlatfb_trc : ', SUM2D(tmlatfb_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmlatfn_trc : ', SUM2D(tmlatfn_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmlradb_trc : ', SUM2D(tmlradb_trc(:,:,jn))
-                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmlradn_trc : ', SUM2D(tmlradn_trc(:,:,jn))
-                  
-                  WRITE(numout, *)
-                  DO jl = 1, jpltrd_trc
-                     WRITE(numout,97) 'TRC jn =', jn, ' TREND INDEX jpmld_trc_xxx = ', jl, &
-                        & ' SUM tmltrd_trc : ', SUM2D(tmltrd_trc(:,:,jl,jn))
-                  END DO
-               
-                  WRITE(numout,*) 
-                  WRITE(numout,*) ' *********************** ZTMLRES, ZTMLRES2 *********************** '
-                  WRITE(numout,*)
-                  WRITE(numout,*) 'TRC ztmlres (jpi/2,jpj/2,:) : ', ztmlres (jpi/2,jpj/2,jn)
-                  WRITE(numout,*)
-                  WRITE(numout,*) 'TRC ztmlres2(jpi/2,jpj/2,:) : ', ztmlres2(jpi/2,jpj/2,jn)
-                  
-                  WRITE(numout,*) 
-                  WRITE(numout,*) ' *********************** ZTMLRES *********************** '
-                  WRITE(numout,*)
-                  
-                  WRITE(numout,*) '...................................................'
-                  WRITE(numout,*) 'TRC jn =', jn, ' ztmlres (1:10,1:5,jn) : '
-                  DO jj = 5, 1, -1
-                     WRITE(numout,99) jj, ( ztmlres (ji,jj,jn), ji=1,10 )
-                  END DO
-                  
-                  WRITE(numout,*) 
-                  WRITE(numout,*) ' *********************** ZTMLRES2 *********************** '
-                  WRITE(numout,*)
-                  
-                  WRITE(numout,*) '...................................................'
-                  WRITE(numout,*) 'TRC jn =', jn, ' ztmlres2 (1:10,1:5,jn) : '
-                  DO jj = 5, 1, -1
-                     WRITE(numout,99) jj, ( ztmlres2 (ji,jj,jn), ji=1,10 )
-                  END DO
-                  !
-               ENDIF
-               !
-            END DO
-
-
-97            FORMAT(a10, i3, 2x, a30, i3, a20, 2x, g20.10)
-98            FORMAT(a10, i3, 2x, a30, 2x, g20.10)
-99            FORMAT('TRC jj =', i3,' : ', 10(g10.3,2x))
-              WRITE(numout,*)
-            !
-         ENDIF
-
-         ! III.3 Time evolution array swap
-         ! -------------------------------
-         ! ML depth
-         rmldbn_trc(:,:)   = rmld_trc(:,:)
-         rmld_sum_trc(:,:)     = rmld_sum_trc(:,:)     /      (2*zfn)  ! similar to tml_sum and sml_sum
-         DO jn = 1, jptra
-            IF( ln_trdtrc(jn) ) THEN        
-               ! For passive tracer instantaneous diagnostics
-               tmlbb_trc  (:,:,jn) = tmlb_trc   (:,:,jn)   ;   tmlbn_trc  (:,:,jn) = tml_trc    (:,:,jn)
-               tmlatfb_trc(:,:,jn) = tmlatfn_trc(:,:,jn)   ;   tmlradb_trc(:,:,jn) = tmlradn_trc(:,:,jn)
-               
-               ! For passive tracer mean diagnostics
-               tmltrd_csum_ub_trc (:,:,:,jn) = zfn * tmltrd_sum_trc(:,:,:,jn) - tmltrd_csum_ln_trc(:,:,:,jn)
-               tml_sumb_trc       (:,:,jn)   = tml_sum_trc(:,:,jn)
-               tmltrd_atf_sumb_trc(:,:,jn)   = tmltrd_sum_trc(:,:,jpmld_trc_atf ,jn)
-               tmltrd_rad_sumb_trc(:,:,jn)   = tmltrd_sum_trc(:,:,jpmld_trc_radb,jn)
-               
-               
-               ! III.4 Convert to appropriate physical units
-               ! -------------------------------------------
-               ztmltot     (:,:,jn)   = ztmltot     (:,:,jn)   * rn_ucf_trc/zfn   ! instant diags
-               ztmlres     (:,:,jn)   = ztmlres     (:,:,jn)   * rn_ucf_trc/zfn
-               ztmlatf     (:,:,jn)   = ztmlatf     (:,:,jn)   * rn_ucf_trc/zfn
-               ztmlrad     (:,:,jn)   = ztmlrad     (:,:,jn)   * rn_ucf_trc/zfn
-               tml_sum_trc (:,:,jn)   = tml_sum_trc (:,:,jn)   /      (2*zfn)  ! mean diags
-               ztmltot2    (:,:,jn)   = ztmltot2    (:,:,jn)   * rn_ucf_trc/zfn2
-               ztmltrd2    (:,:,:,jn) = ztmltrd2    (:,:,:,jn) * rn_ucf_trc/zfn2
-               ztmlatf2    (:,:,jn)   = ztmlatf2    (:,:,jn)   * rn_ucf_trc/zfn2
-               ztmlrad2    (:,:,jn)   = ztmlrad2    (:,:,jn)   * rn_ucf_trc/zfn2
-               ztmlres2    (:,:,jn)   = ztmlres2    (:,:,jn)   * rn_ucf_trc/zfn2
-            ENDIF
-         END DO
-         !
-      ENDIF MODULO_NTRD
-
-      ! ======================================================================
-      ! IV. Write trends in the NetCDF file
-      ! ======================================================================
-
-      ! IV.1 Code for dimg mpp output
-      ! -----------------------------
-
-# if defined key_dimgout
-      STOP 'Not implemented'
-# else
-      
-      ! IV.2 Code for IOIPSL/NetCDF output
-      ! ----------------------------------
-
-      IF( lwp .AND. MOD( itmod , nn_trd_trc ) == 0 ) THEN
-         WRITE(numout,*) ' '
-         WRITE(numout,*) 'trd_mld_trc : write passive tracer trends in the NetCDF file :'
-         WRITE(numout,*) '~~~~~~~~~~~ '
-         WRITE(numout,*) '          ', trim(clhstnam), ' at kt = ', kt
-         WRITE(numout,*) '          N.B. nmoymltrd = ', nmoymltrd
-         WRITE(numout,*) ' '
-      ENDIF
-         
-      NETCDF_OUTPUT : IF( ln_trdmld_trc_instant ) THEN            ! <<< write the trends for passive tracer instant. diags
-         !
-
-         DO jn = 1, jptra
-            !
-            IF( ln_trdtrc(jn) ) THEN
-               CALL histwrite( nidtrd(jn), "mxl_depth", it, rmld_trc(:,:), ndimtrd1, ndextrd1 )
-               !-- Output the fields
-               clvar = trim(ctrcnm(jn))//"ml"                        ! e.g. detml, zooml, nh4ml, etc.
-               CALL histwrite( nidtrd(jn), trim(clvar)         , it, tml_trc(:,:,jn), ndimtrd1, ndextrd1 ) 
-               CALL histwrite( nidtrd(jn), trim(clvar)//"_tot" , it, ztmltot(:,:,jn), ndimtrd1, ndextrd1 ) 
-               CALL histwrite( nidtrd(jn), trim(clvar)//"_res" , it, ztmlres(:,:,jn), ndimtrd1, ndextrd1 ) 
-           
-               DO jl = 1, jpltrd_trc - 2
-                  CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jl,2)),             &
-                    &          it, tmltrd_trc(:,:,jl,jn), ndimtrd1, ndextrd1 )
-               END DO
-
-               CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmld_trc_radb,2)),    &  ! now trcrad    : jpltrd_trc - 1
-                    &          it, ztmlrad(:,:,jn), ndimtrd1, ndextrd1 )
-
-               CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmld_trc_atf,2)),     &  ! now Asselin   : jpltrd_trc
-                    &          it, ztmlatf(:,:,jn), ndimtrd1, ndextrd1 )
-                     
-            ENDIF
-         END DO
-
-         IF( kt == nitend ) THEN 
-            DO jn = 1, jptra
-               IF( ln_trdtrc(jn) )  CALL histclo( nidtrd(jn) )
-            END DO
-         ENDIF
-
-      ELSE                                                        ! <<< write the trends for passive tracer mean diagnostics
-         
-         DO jn = 1, jptra
-            !
-            IF( ln_trdtrc(jn) ) THEN
-               CALL histwrite( nidtrd(jn), "mxl_depth", it, rmld_sum_trc(:,:), ndimtrd1, ndextrd1 ) 
-               !-- Output the fields
-               clvar = trim(ctrcnm(jn))//"ml"                        ! e.g. detml, zooml, nh4ml, etc.
-
-               CALL histwrite( nidtrd(jn), trim(clvar)         , it, tml_sum_trc(:,:,jn), ndimtrd1, ndextrd1 )
-               CALL histwrite( nidtrd(jn), trim(clvar)//"_tot" , it,    ztmltot2(:,:,jn), ndimtrd1, ndextrd1 ) 
-               CALL histwrite( nidtrd(jn), trim(clvar)//"_res" , it,    ztmlres2(:,:,jn), ndimtrd1, ndextrd1 ) 
-
-               DO jl = 1, jpltrd_trc - 2
-                  CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jl,2)),           &
-                    &          it, ztmltrd2(:,:,jl,jn), ndimtrd1, ndextrd1 )
-               END DO
-            
-               CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmld_trc_radb,2)),   &  ! now trcrad    : jpltrd_trc - 1
-                 &          it, ztmlrad2(:,:,jn), ndimtrd1, ndextrd1 )
-
-               CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmld_trc_atf,2)),    &  ! now Asselin   : jpltrd_trc
-                 &          it, ztmlatf2(:,:,jn), ndimtrd1, ndextrd1 )
-
-            ENDIF 
-            !
-         END DO
-         IF( kt == nitend ) THEN 
-            DO jn = 1, jptra
-               IF( ln_trdtrc(jn) )  CALL histclo( nidtrd(jn) )
-            END DO
-         ENDIF
-
-         !
-      ENDIF NETCDF_OUTPUT
-         
-      ! Compute the control surface (for next time step) : flag = on
-      icount = 1
-
-# endif /* key_dimgout */
-
-      IF( MOD( itmod, nn_trd_trc ) == 0 ) THEN
-         !
-         ! Reset cumulative arrays to zero
-         ! -------------------------------         
-         nmoymltrd = 0
-         tmltrdm_trc        (:,:,:)   = 0.e0   ;   tmlatfm_trc        (:,:,:)   = 0.e0
-         tmlradm_trc        (:,:,:)   = 0.e0   ;   tml_sum_trc        (:,:,:)   = 0.e0
-         tmltrd_csum_ln_trc (:,:,:,:) = 0.e0   ;   tmltrd_sum_trc     (:,:,:,:) = 0.e0
-         rmld_sum_trc       (:,:)     = 0.e0
-         !
-      ENDIF
-
-      ! ======================================================================
-      ! V. Write restart file
-      ! ======================================================================
-
-      IF( lrst_trc )   CALL trd_mld_trc_rst_write( kt )  ! this must be after the array swap above (III.3)
-
-      CALL wrk_dealloc( jpi, jpj, jptra, ztmltot , ztmlres , ztmlatf , ztmlrad             )
-      CALL wrk_dealloc( jpi, jpj, jptra, ztmltot2, ztmlres2, ztmlatf2, ztmlrad2, ztmltrdm2 )
-      !
-   END SUBROUTINE trd_mld_trc
-
-
-   SUBROUTINE trd_mld_bio( kt )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld  ***
-      !!
-      !! ** Purpose :  Compute and cumulate the mixed layer biological trends over an analysis
-      !!               period, and write NetCDF (or dimg) outputs.
-      !!
-      !! ** Method/usage :
-      !!          The stored trends can be chosen twofold (according to the ln_trdmld_trc_instant
-      !!          logical namelist variable) :
-      !!          1) to explain the difference between initial and final
-      !!             mixed-layer T & S (where initial and final relate to the
-      !!             current analysis window, defined by ntrd in the namelist)
-      !!          2) to explain the difference between the current and previous
-      !!             TIME-AVERAGED mixed-layer T & S (where time-averaging is
-      !!             performed over each analysis window).
-      !!
-      !! ** Consistency check :
-      !!        If the control surface is fixed ( nctls > 1 ), the residual term (dh/dt
-      !!        entrainment) should be zero, at machine accuracy. Note that in the case
-      !!        of time-averaged mixed-layer fields, this residual WILL NOT BE ZERO
-      !!        over the first two analysis windows (except if restart).
-      !!        N.B. For ORCA2_LIM, use e.g. ntrd=5, ucf=1., nctls=8
-      !!             for checking residuals.
-      !!             On a NEC-SX5 computer, this typically leads to:
-      !!                   O(1.e-20) temp. residuals (tml_res) when ln_trdmld_trc_instant=.false.
-      !!                   O(1.e-21) temp. residuals (tml_res) when ln_trdmld_trc_instant=.true.
-      !!
-      !! ** Action :
-      !!       At each time step, mixed-layer averaged trends are stored in the
-      !!       tmltrd(:,:,jpmld_xxx) array (see trdmld_oce.F90 for definitions of jpmld_xxx).
-      !!       This array is known when trd_mld is called, at the end of the stp subroutine,
-      !!       except for the purely vertical K_z diffusion term, which is embedded in the
-      !!       lateral diffusion trend.
-      !!
-      !!       In I), this K_z term is diagnosed and stored, thus its contribution is removed
-      !!       from the lateral diffusion trend.
-      !!       In II), the instantaneous mixed-layer T & S are computed, and misc. cumulative
-      !!       arrays are updated.
-      !!       In III), called only once per analysis window, we compute the total trends,
-      !!       along with the residuals and the Asselin correction terms.
-      !!       In IV), the appropriate trends are written in the trends NetCDF file.
-      !!
-      !! References :
-      !!       - Vialard & al.
-      !!       - See NEMO documentation (in preparation)
-      !!----------------------------------------------------------------------
-      INTEGER, INTENT( in ) ::   kt                       ! ocean time-step index
-#if defined key_pisces_reduced
-      INTEGER  ::  jl, it, itmod
-      LOGICAL  :: llwarn  = .TRUE., lldebug = .TRUE.
-      REAL(wp) :: zfn, zfn2
-#if defined key_dimgout
-      INTEGER ::  iyear,imon,iday
-      CHARACTER(LEN=80) :: cltext, clmode
-#endif
-      !!----------------------------------------------------------------------
-      ! ... Warnings
-      IF( nn_dttrc  /= 1  ) CALL ctl_stop( " Be careful, trends diags never validated " )
-
-      ! ======================================================================
-      ! II. Cumulate the trends over the analysis window
-      ! ======================================================================
-
-      ztmltrdbio2(:,:,:) = 0.e0  ! <<< reset arrays to zero
-
-      ! II.3 Initialize mixed-layer "before" arrays for the 1rst analysis window
-      ! ------------------------------------------------------------------------
-      IF( kt == nittrc000 + nn_dttrc ) THEN  !  i.e. ( .NOT. ln_rstart ).AND.( kt == nit000 + 1)
-         !
-         tmltrd_csum_ub_bio (:,:,:) = 0.e0
-         !
-      END IF
-
-      ! II.4 Cumulated trends over the analysis period
-      ! ----------------------------------------------
-      !
-      !         [  1rst analysis window ] [     2nd analysis window     ]
-      !
-      !
-      !     o---[--o-----o-----o-----o--]-[--o-----o-----o-----o-----o--]---o-----o--> time steps
-      !                            ntrd                             2*ntrd       etc.
-      !     1      2     3     4    =5 e.g.                          =10
-      !
-      IF( ( kt >= 2 ).OR.( ln_rsttr ) ) THEN
-         !
-         nmoymltrdbio = nmoymltrdbio + 1
-
-         ! ... Trends associated with the time mean of the ML passive tracers
-         tmltrd_sum_bio    (:,:,:) = tmltrd_sum_bio    (:,:,:) + tmltrd_bio    (:,:,:)
-         tmltrd_csum_ln_bio(:,:,:) = tmltrd_csum_ln_bio(:,:,:) + tmltrd_sum_bio(:,:,:)
-         !
-      END IF
-
-      ! ======================================================================
-      ! III. Prepare fields for output (get here ONCE PER ANALYSIS PERIOD)
-      ! ======================================================================
-
-      ! Convert to appropriate physical units
-      tmltrd_bio(:,:,:) = tmltrd_bio(:,:,:) * rn_ucf_trc
-
-      MODULO_NTRD : IF( MOD( kt, nn_trd_trc ) == 0 ) THEN      ! nitend MUST be multiple of ntrd
-         !
-         zfn  = float(nmoymltrdbio)    ;    zfn2 = zfn * zfn
-
-         ! III.1 Prepare fields for output ("instantaneous" diagnostics)
-         ! -------------------------------------------------------------
-
-#if defined key_diainstant
-         STOP 'tmltrd_bio : key_diainstant was never checked within trdmld. Comment this to proceed.'
-#endif
-         ! III.2 Prepare fields for output ("mean" diagnostics)
-         ! ----------------------------------------------------
-
-         ztmltrdbio2(:,:,:) = tmltrd_csum_ub_bio(:,:,:) + tmltrd_csum_ln_bio(:,:,:)
-
-         !-- Lateral boundary conditions
-         IF ( cp_cfg .NE. 'gyre' ) THEN            ! other than GYRE configuration 
-            ! ES_B27_CD_WARN : lbc inutile GYRE, cf. + haut
-            DO jn = 1, jpdiabio
-              CALL lbc_lnk( ztmltrdbio2(:,:,jn), 'T', 1. )
-            ENDDO
-         ENDIF
-
-         IF( lldebug ) THEN
-            !
-            WRITE(numout,*) 'trd_mld_bio : write trends in the Mixed Layer for debugging process:'
-            WRITE(numout,*) '~~~~~~~~~~~  '
-            WRITE(numout,*) 'TRC kt = ', kt, 'nmoymltrdbio = ', nmoymltrdbio
-            WRITE(numout,*)
-
-            DO jl = 1, jpdiabio
-              IF( ln_trdmld_trc_instant ) THEN
-                  WRITE(numout,97) 'TRC jl =', jl, ' bio TREND INDEX  = ', jl, &
-                     & ' SUM tmltrd_bio : ', SUM2D(tmltrd_bio(:,:,jl))
-              ELSE
-                  WRITE(numout,97) 'TRC jl =', jl, ' bio TREND INDEX  = ', jl, &
-                     & ' SUM ztmltrdbio2 : ', SUM2D(ztmltrdbio2(:,:,jl))
-              endif
-            END DO
-
-97          FORMAT(a10, i3, 2x, a30, i3, a20, 2x, g20.10)
-98          FORMAT(a10, i3, 2x, a30, 2x, g20.10)
-99          FORMAT('TRC jj =', i3,' : ', 10(g10.3,2x))
-            WRITE(numout,*)
-            !
-         ENDIF
-
-         ! III.3 Time evolution array swap
-         ! -------------------------------
-
-         ! For passive tracer mean diagnostics
-         tmltrd_csum_ub_bio (:,:,:) = zfn * tmltrd_sum_bio(:,:,:) - tmltrd_csum_ln_bio(:,:,:)
-
-         ! III.4 Convert to appropriate physical units
-         ! -------------------------------------------
-         ztmltrdbio2    (:,:,:) = ztmltrdbio2    (:,:,:) * rn_ucf_trc/zfn2
-
-      END IF MODULO_NTRD
-
-      ! ======================================================================
-      ! IV. Write trends in the NetCDF file
-      ! ======================================================================
-
-      ! IV.1 Code for dimg mpp output
-      ! -----------------------------
-
-# if defined key_dimgout
-      STOP 'Not implemented'
-# else
-
-      ! IV.2 Code for IOIPSL/NetCDF output
-      ! ----------------------------------
-
-      ! define time axis
-      itmod = kt - nittrc000 + 1
-      it    = kt
-
-      IF( lwp .AND. MOD( itmod , nn_trd_trc ) == 0 ) THEN
-         WRITE(numout,*) ' '
-         WRITE(numout,*) 'trd_mld_bio : write ML bio trends in the NetCDF file :'
-         WRITE(numout,*) '~~~~~~~~~~~ '
-         WRITE(numout,*) '          ', TRIM(clhstnam), ' at kt = ', kt
-         WRITE(numout,*) '          N.B. nmoymltrdbio = ', nmoymltrdbio
-         WRITE(numout,*) ' '
-      END IF
-
-
-      ! 2. Start writing data
-      ! ---------------------
-
-      NETCDF_OUTPUT : IF( ln_trdmld_trc_instant ) THEN    ! <<< write the trends for passive tracer instant. diags
-         !
-            DO jl = 1, jpdiabio
-               CALL histwrite( nidtrdbio,TRIM("ML_"//ctrd_bio(jl,2)) ,            &
-                    &          it, tmltrd_bio(:,:,jl), ndimtrd1, ndextrd1 )
-            END DO
-
-
-         IF( kt == nitend )   CALL histclo( nidtrdbio )
-
-      ELSE    ! <<< write the trends for passive tracer mean diagnostics
-
-            DO jl = 1, jpdiabio
-               CALL histwrite( nidtrdbio, TRIM("ML_"//ctrd_bio(jl,2)) ,            &
-                    &          it, ztmltrdbio2(:,:,jl), ndimtrd1, ndextrd1 )
-            END DO
-
-            IF( kt == nitend )   CALL histclo( nidtrdbio )
-            !
-      END IF NETCDF_OUTPUT
-
-      ! Compute the control surface (for next time step) : flag = on
-      icountbio = 1
-
-
-# endif /* key_dimgout */
-
-      IF( MOD( itmod, nn_trd_trc ) == 0 ) THEN
-         !
-         ! III.5 Reset cumulative arrays to zero
-         ! -------------------------------------
-         nmoymltrdbio = 0
-         tmltrd_csum_ln_bio (:,:,:) = 0.e0
-         tmltrd_sum_bio     (:,:,:) = 0.e0
-      END IF
-
-      ! ======================================================================
-      ! Write restart file
-      ! ======================================================================
-
-! restart write is done in trd_mld_trc_write which is called by trd_mld_bio (Marina)
-!
-#endif
-   END SUBROUTINE trd_mld_bio
-
-
-   REAL FUNCTION sum2d( ztab )
-      !!----------------------------------------------------------------------
-      !! CD ??? prevoir d'utiliser plutot prtctl
-      !!----------------------------------------------------------------------
-      REAL(wp), DIMENSION(jpi,jpj), INTENT( in ) ::  ztab      
-      !!----------------------------------------------------------------------
-      sum2d = SUM( ztab(2:jpi-1,2:jpj-1) )
-   END FUNCTION sum2d
-
-
-   SUBROUTINE trd_mld_trc_init
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mld_init  ***
-      !! 
-      !! ** Purpose :   computation of vertically integrated T and S budgets
-      !!      from ocean surface down to control surface (NetCDF output)
-      !!
-      !! ** Method/usage :
-      !!
-      !!----------------------------------------------------------------------
-      INTEGER :: inum   ! logical unit
-      INTEGER :: ilseq, jl, jn, iiter
-      REAL(wp) ::   zjulian, zsto, zout
-      CHARACTER (LEN=40) ::   clop
-      CHARACTER (LEN=15) ::   csuff
-      CHARACTER (LEN=12) ::   clmxl
-      CHARACTER (LEN=16) ::   cltrcu
-      CHARACTER (LEN=10) ::   clvar
-
-      !!----------------------------------------------------------------------
-
-      ! ======================================================================
-      ! I. initialization
-      ! ======================================================================
-
-      IF(lwp) THEN
-         WRITE(numout,*)
-         WRITE(numout,*) ' trd_mld_trc_init : Mixed-layer trends for passive tracers                '
-         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~'
-         WRITE(numout,*)
-      ENDIF
-
-      
-      ! I.1 Check consistency of user defined preferences
-      ! -------------------------------------------------
-
-      IF( ( lk_trdmld_trc ) .AND. ( MOD( nitend-nittrc000+1, nn_trd_trc ) /= 0 ) ) THEN
-         WRITE(numout,cform_err)
-         WRITE(numout,*) '                Your nitend parameter, nitend = ', nitend
-         WRITE(numout,*) '                is no multiple of the trends diagnostics frequency        '
-         WRITE(numout,*) '                          you defined, nn_trd_trc   = ', nn_trd_trc
-         WRITE(numout,*) '                This will not allow you to restart from this simulation.  '
-         WRITE(numout,*) '                You should reconsider this choice.                        ' 
-         WRITE(numout,*) 
-         WRITE(numout,*) '                N.B. the nitend parameter is also constrained to be a     '
-         WRITE(numout,*) '                multiple of the sea-ice frequency parameter (typically 5) '
-         nstop = nstop + 1
-      ENDIF
-
-      ! * Debugging information *
-      IF( lldebug ) THEN
-         WRITE(numout,*) '               ln_trcadv_muscl = '      , ln_trcadv_muscl
-         WRITE(numout,*) '               ln_trdmld_trc_instant = ', ln_trdmld_trc_instant
-      ENDIF
-
-      IF( ( ln_trcadv_muscl .OR. ln_trcadv_muscl2 ) .AND. .NOT. ln_trdmld_trc_instant ) THEN
-         WRITE(numout,cform_err)
-         WRITE(numout,*) '                Currently, you can NOT use simultaneously tracer MUSCL    '
-         WRITE(numout,*) '                advection and window averaged diagnostics of ML trends.   '
-         WRITE(numout,*) '                WHY? Everything in trdmld_trc is coded for leap-frog, and '
-         WRITE(numout,*) '                MUSCL scheme is Euler forward for passive tracers (note   '
-         WRITE(numout,*) '                that MUSCL is leap-frog for active tracers T/S).          '
-         WRITE(numout,*) '                In particuliar, entrainment trend would be FALSE. However '
-         WRITE(numout,*) '                this residual is correct for instantaneous ML diagnostics.'
-         WRITE(numout,*) 
-         nstop = nstop + 1
-      ENDIF
-
-      ! I.2 Initialize arrays to zero or read a restart file
-      ! ----------------------------------------------------
-      nmoymltrd   = 0
-
-      rmld_trc           (:,:)     = 0.e0   ;   tml_trc            (:,:,:)   = 0.e0       ! inst.
-      tmltrdm_trc        (:,:,:)   = 0.e0   ;   tmlatfm_trc        (:,:,:)   = 0.e0
-      tmlradm_trc        (:,:,:)   = 0.e0
-
-      tml_sum_trc        (:,:,:)   = 0.e0   ;   tmltrd_sum_trc     (:,:,:,:) = 0.e0       ! mean
-      tmltrd_csum_ln_trc (:,:,:,:) = 0.e0   ;   rmld_sum_trc       (:,:)     = 0.e0
-
-#if defined key_pisces_reduced
-      nmoymltrdbio   = 0
-      tmltrd_sum_bio     (:,:,:) = 0.e0     ;   tmltrd_csum_ln_bio (:,:,:) = 0.e0
-      DO jl = 1, jp_pisces_trd
-          ctrd_bio(jl,1) = ctrbil(jl)   ! long name
-          ctrd_bio(jl,2) = ctrbio(jl)   ! short name
-       ENDDO
-#endif
-
-      IF( ln_rsttr .AND. ln_trdmld_trc_restart ) THEN
-         CALL trd_mld_trc_rst_read
-      ELSE
-         tmlb_trc           (:,:,:)   = 0.e0   ;   tmlbb_trc          (:,:,:)   = 0.e0     ! inst.
-         tmlbn_trc          (:,:,:)   = 0.e0
-
-         tml_sumb_trc       (:,:,:)   = 0.e0   ;   tmltrd_csum_ub_trc (:,:,:,:) = 0.e0     ! mean
-         tmltrd_atf_sumb_trc(:,:,:)   = 0.e0   ;   tmltrd_rad_sumb_trc(:,:,:)   = 0.e0 
-#if defined key_pisces_reduced
-         tmltrd_csum_ub_bio (:,:,:) = 0.e0
-#endif
-
-       ENDIF
-
-      icount = 1   ;   ionce  = 1  ! open specifier   
-
-#if defined key_pisces_reduced
-      icountbio = 1   ;   ioncebio  = 1  ! open specifier
-#endif
-
-      ! I.3 Read control surface from file ctlsurf_idx
-      ! ----------------------------------------------
-      IF( nn_ctls_trc == 1 ) THEN
-         CALL ctl_opn( inum, 'ctlsurf_idx', 'OLD', 'UNFORMATTED', 'SEQUENTIAL', -1, numout, lwp )
-         READ ( inum ) nbol_trc
-         CLOSE( inum )
-      ENDIF
-
-      ! ======================================================================
-      ! II. netCDF output initialization
-      ! ======================================================================
-
-#if defined key_dimgout 
-      ???
-#else
-      ! clmxl = legend root for netCDF output
-      IF( nn_ctls_trc == 0 ) THEN                                   ! control surface = mixed-layer with density criterion
-         clmxl = 'Mixed Layer '
-      ELSE IF( nn_ctls_trc == 1 ) THEN                              ! control surface = read index from file 
-         clmxl = '      Bowl '
-      ELSE IF( nn_ctls_trc >= 2 ) THEN                              ! control surface = model level
-         WRITE(clmxl,'(A10,I2,1X)') 'Levels 1 -', nn_ctls_trc
-      ENDIF
-
-      ! II.1 Define frequency of output and means
-      ! -----------------------------------------
-      IF( ln_mskland )   THEN   ;   clop = "only(x)"   ! put 1.e+20 on land (very expensive!!)
-      ELSE                      ;   clop = "x"         ! no use of the mask value (require less cp time)
-      ENDIF
-#  if defined key_diainstant
-      IF( .NOT. ln_trdmld_trc_instant ) THEN
-         STOP 'trd_mld_trc : this was never checked. Comment this line to proceed...'
-      ENDIF
-      zsto = nn_trd_trc * rdt
-      clop = "inst("//TRIM(clop)//")"
-#  else
-      IF( ln_trdmld_trc_instant ) THEN
-         zsto = rdt                                               ! inst. diags : we use IOIPSL time averaging
-      ELSE
-         zsto = nn_trd_trc * rdt                                    ! mean  diags : we DO NOT use any IOIPSL time averaging
-      ENDIF
-      clop = "ave("//TRIM(clop)//")"
-#  endif
-      zout = nn_trd_trc * rdt
-      iiter = ( nittrc000 - 1 ) / nn_dttrc
-
-      IF(lwp) WRITE (numout,*) '                netCDF initialization'
-
-      ! II.2 Compute julian date from starting date of the run
-      ! ------------------------------------------------------
-      CALL ymds2ju( nyear, nmonth, nday, rdt, zjulian )
-      zjulian = zjulian - adatrj   !   set calendar origin to the beginning of the experiment
-      IF(lwp) WRITE(numout,*)' '  
-      IF(lwp) WRITE(numout,*)' Date 0 used :', nittrc000               &
-           &   ,' YEAR ', nyear, ' MONTH ', nmonth,' DAY ', nday       &
-           &   ,'Julian day : ', zjulian
-
-      ! II.3 Define the T grid trend file (nidtrd)
-      ! ------------------------------------------
-
-      !-- Define long and short names for the NetCDF output variables
-      !       ==> choose them according to trdmld_trc_oce.F90 <==
-
-      ctrd_trc(jpmld_trc_xad    ,1) = " Zonal advection"                 ;   ctrd_trc(jpmld_trc_xad    ,2) = "_xad"
-      ctrd_trc(jpmld_trc_yad    ,1) = " Meridional advection"            ;   ctrd_trc(jpmld_trc_yad    ,2) = "_yad"
-      ctrd_trc(jpmld_trc_zad    ,1) = " Vertical advection"              ;   ctrd_trc(jpmld_trc_zad    ,2) = "_zad"
-      ctrd_trc(jpmld_trc_ldf    ,1) = " Lateral diffusion"               ;   ctrd_trc(jpmld_trc_ldf    ,2) = "_ldf"
-      ctrd_trc(jpmld_trc_zdf    ,1) = " Vertical diff. (Kz)"             ;   ctrd_trc(jpmld_trc_zdf    ,2) = "_zdf"
-      ctrd_trc(jpmld_trc_bbl    ,1) = " Adv/diff. Bottom boundary layer" ;   ctrd_trc(jpmld_trc_bbl    ,2) = "_bbl"
-      ctrd_trc(jpmld_trc_dmp    ,1) = " Tracer damping"                  ;   ctrd_trc(jpmld_trc_dmp    ,2) = "_dmp"
-      ctrd_trc(jpmld_trc_sbc    ,1) = " Surface boundary cond."          ;   ctrd_trc(jpmld_trc_sbc    ,2) = "_sbc"
-      ctrd_trc(jpmld_trc_sms,    1) = " Sources minus sinks"             ;   ctrd_trc(jpmld_trc_sms    ,2) = "_sms"
-      ctrd_trc(jpmld_trc_radb   ,1) = " Correct negative concentrations" ;   ctrd_trc(jpmld_trc_radb   ,2) = "_radb"
-      ctrd_trc(jpmld_trc_radn   ,1) = " Correct negative concentrations" ;   ctrd_trc(jpmld_trc_radn   ,2) = "_radn"
-      ctrd_trc(jpmld_trc_atf    ,1) = " Asselin time filter"             ;   ctrd_trc(jpmld_trc_atf    ,2) = "_atf"
-
-      DO jn = 1, jptra      
-      !-- Create a NetCDF file and enter the define mode 
-         IF( ln_trdtrc(jn) ) THEN
-            csuff="ML_"//ctrcnm(jn)
-            CALL dia_nam( clhstnam, nn_trd_trc, csuff )
-            CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,                                            &
-               &        1, jpi, 1, jpj, iiter, zjulian, rdt, nh_t(jn), nidtrd(jn), domain_id=nidom, snc4chunks=snc4set )
-      
-            !-- Define the ML depth variable
-            CALL histdef(nidtrd(jn), "mxl_depth", clmxl//" Mixed Layer Depth", "m",                        &
-               &        jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zsto, zout )
-
-         ENDIF
-      END DO
-
-#if defined key_pisces_reduced
-          !-- Create a NetCDF file and enter the define mode
-          CALL dia_nam( clhstnam, nn_trd_trc, 'trdbio' )
-          CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,                                            &
-             &             1, jpi, 1, jpj, iiter, zjulian, rdt, nh_tb, nidtrdbio, domain_id=nidom, snc4chunks=snc4set )
-#endif
-
-      !-- Define physical units
-      IF( rn_ucf_trc == 1. ) THEN
-         cltrcu = "(mmole-N/m3)/sec"                              ! all passive tracers have the same unit 
-      ELSEIF ( rn_ucf_trc == 3600.*24.) THEN                         ! ??? trop long : seulement (mmole-N/m3)
-         cltrcu = "(mmole-N/m3)/day"                              ! ??? apparait dans les sorties netcdf 
-      ELSE
-         cltrcu = "unknown?"
-      ENDIF
-
-      !-- Define miscellaneous passive tracer mixed-layer variables 
-      IF( jpltrd_trc /= jpmld_trc_atf .OR.  jpltrd_trc - 1 /= jpmld_trc_radb ) THEN
-         STOP 'Error : jpltrd_trc /= jpmld_trc_atf .OR.  jpltrd_trc - 1 /= jpmld_trc_radb'  ! see below
-      ENDIF
-
-      DO jn = 1, jptra
-         !
-         IF( ln_trdtrc(jn) ) THEN
-            clvar = trim(ctrcnm(jn))//"ml"                           ! e.g. detml, zooml, no3ml, etc.
-            CALL histdef(nidtrd(jn), trim(clvar),           clmxl//" "//trim(ctrcnm(jn))//" Mixed Layer ",                         &
-              & "mmole-N/m3", jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zsto, zout )           
-            CALL histdef(nidtrd(jn), trim(clvar)//"_tot"  , clmxl//" "//trim(ctrcnm(jn))//" Total trend ",                         & 
-              &       cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zout, zout ) 
-            CALL histdef(nidtrd(jn), trim(clvar)//"_res"  , clmxl//" "//trim(ctrcnm(jn))//" dh/dt Entrainment (Resid.)",           & 
-              &       cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zout, zout )                   
-         
-            DO jl = 1, jpltrd_trc - 2                                ! <== only true if jpltrd_trc == jpmld_trc_atf
-               CALL histdef(nidtrd(jn), trim(clvar)//trim(ctrd_trc(jl,2)), clmxl//" "//clvar//ctrd_trc(jl,1),                      & 
-                 &    cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zsto, zout ) ! IOIPSL: time mean
-            END DO                                                                         ! if zsto=rdt above
-         
-            CALL histdef(nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmld_trc_radb,2)), clmxl//" "//clvar//ctrd_trc(jpmld_trc_radb,1), & 
-              &       cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zout, zout ) ! IOIPSL: NO time mean
-         
-            CALL histdef(nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmld_trc_atf,2)), clmxl//" "//clvar//ctrd_trc(jpmld_trc_atf,1),   & 
-              &       cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zout, zout ) ! IOIPSL: NO time mean
-         !
-         ENDIF
-      END DO
-
-#if defined key_pisces_reduced
-      DO jl = 1, jp_pisces_trd
-         CALL histdef(nidtrdbio, TRIM("ML_"//ctrd_bio(jl,2)), TRIM(clmxl//" ML_"//ctrd_bio(jl,1))   ,            &
-             &    cltrcu, jpi, jpj, nh_tb, 1  , 1, 1  , -99 , 32, clop, zsto, zout ) ! IOIPSL: time mean
-      END DO                                                                         ! if zsto=rdt above
-#endif
-
-      !-- Leave IOIPSL/NetCDF define mode
-      DO jn = 1, jptra
-         IF( ln_trdtrc(jn) )  CALL histend( nidtrd(jn), snc4set )
-      END DO
-
-#if defined key_pisces_reduced
-      !-- Leave IOIPSL/NetCDF define mode
-      CALL histend( nidtrdbio, snc4set )
-
-      IF(lwp) WRITE(numout,*)
-       IF(lwp) WRITE(numout,*) 'End of NetCDF Initialization for ML bio trends'
-#endif
-
-#endif        /* key_dimgout */
-   END SUBROUTINE trd_mld_trc_init
-
-#else
-   !!----------------------------------------------------------------------
-   !!   Default option :                                       Empty module
-   !!----------------------------------------------------------------------
-CONTAINS
-   SUBROUTINE trd_mld_trc( kt )                                   ! Empty routine
-      INTEGER, INTENT( in) ::   kt
-      WRITE(*,*) 'trd_mld_trc: You should not have seen this print! error?', kt
-   END SUBROUTINE trd_mld_trc
-   SUBROUTINE trd_mld_bio( kt )
-      INTEGER, INTENT( in) ::   kt
-      WRITE(*,*) 'trd_mld_bio: You should not have seen this print! error?', kt
-   END SUBROUTINE trd_mld_bio
-   SUBROUTINE trd_mld_trc_zint( ptrc_trdmld, ktrd, ctype, kjn )
-      INTEGER               , INTENT( in ) ::  ktrd, kjn              ! ocean trend index and passive tracer rank
-      CHARACTER(len=2)      , INTENT( in ) ::  ctype                  ! surface/bottom (2D) or interior (3D) physics
-      REAL, DIMENSION(:,:,:), INTENT( in ) ::  ptrc_trdmld            ! passive trc trend
-      WRITE(*,*) 'trd_mld_trc_zint: You should not have seen this print! error?', ptrc_trdmld(1,1,1)
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', ctype
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', ktrd
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kjn
-   END SUBROUTINE trd_mld_trc_zint
-   SUBROUTINE trd_mld_trc_init                                    ! Empty routine
-      WRITE(*,*) 'trd_mld_trc_init: You should not have seen this print! error?'
-   END SUBROUTINE trd_mld_trc_init
-#endif
-
-   !!======================================================================
-END MODULE trdmld_trc
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmld_trc_rst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmld_trc_rst.F90	(revision 5074)
+++ 	(revision )
@@ -1,220 +1,0 @@
-MODULE trdmld_trc_rst
-   !!======================================================================
-   !!                       ***  MODULE  trdmld_rst  ***
-   !! Ocean dynamic :  Input/Output files for restart on mixed-layer diagnostics
-   !!======================================================================
-   !! History :  9.0  ! 07-03 (C. Deltel) Original code
-   !!----------------------------------------------------------------------
-  
-#if defined key_top && defined key_trdmld_trc
-   !!----------------------------------------------------------------------
-   USE in_out_manager  ! I/O manager
-   USE iom             ! I/O module
-   USE trc             ! for nn_dttrc ctrcnm
-   USE trdmod_trc_oce  ! for lk_trdmld_trc
-
-   IMPLICIT NONE
-   PRIVATE
-  
-   PUBLIC   trd_mld_trc_rst_read    ! routine called by trd_mld_init
-   PUBLIC   trd_mld_trc_rst_write   ! routine called by step.F90
-  
-   INTEGER ::   nummldw_trc               ! logical unit for mld restart
-   !!---------------------------------------------------------------------------------
-   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
-   !! $Header: /home/opalod/NEMOCVSROOT/NEMO/OPA_SRC/TRD/trdmld_rst.F90,v 1.6 2006/11/14 09:46:13 opalod Exp $ 
-   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
-   !!---------------------------------------------------------------------------------
-  
-CONTAINS
-  
-
-    SUBROUTINE trd_mld_trc_rst_write( kt )
-      !!--------------------------------------------------------------------------------
-      !!                  ***  SUBROUTINE trd_mld_rst_wri  ***
-      !!                
-      !! ** Purpose :   Write mixed-layer diagnostics restart fields.
-      !!--------------------------------------------------------------------------------
-      INTEGER, INTENT( in ) ::   kt     ! ocean time-step index
-      !
-      CHARACTER(LEN=20)   ::   clkt     ! ocean time-step deine as a character
-      CHARACTER(LEN=50)   ::   clname   ! ice output restart file name
-      CHARACTER (len=35) :: charout
-      INTEGER :: jl,  jk, jn               ! loop indice
-      !!--------------------------------------------------------------------------------
-
-      IF( kt == nitrst - nn_dttrc .OR. nitend - nit000 + 1 < 2 * nn_dttrc ) THEN ! idem trcrst.F90
-         IF( nitrst > 1.0e9 ) THEN
-            WRITE(clkt,*) nitrst
-         ELSE
-           WRITE(clkt,'(i8.8)') nitrst
-         ENDIF
-         clname = TRIM(cexper)//"_"//TRIM(ADJUSTL(clkt))//"_"//TRIM(cn_trdrst_trc_out)
-         IF(lwp) WRITE(numout,*) '             open ocean restart_mld_trc NetCDF  '//clname
-         CALL iom_open( clname, nummldw_trc, ldwrt = .TRUE., kiolib = jprstlib )
-      ENDIF
-
-      IF( kt == nitend .AND. lk_trdmld_trc ) THEN
-
-         IF( kt == nitend .AND. lwp ) THEN
-            WRITE(numout,*)
-            WRITE(numout,*) 'trdmld_trc_rst: output for ML diags. restart, with trd_mld_trc_rst_write routine'
-            WRITE(numout,*) '~~~~~~~~~~~~~~'
-            WRITE(numout,*)
-         ENDIF
-
-         IF( ln_trdmld_trc_instant ) THEN 
-            !
-            DO jn = 1, jptra
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlbb_trc_'  //ctrcnm(jn), tmlbb_trc  (:,:,jn) )
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlbn_trc_'  //ctrcnm(jn), tmlbn_trc  (:,:,jn) )
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlatfb_trc_'//ctrcnm(jn), tmlatfb_trc(:,:,jn) )
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlradb_trc_'//ctrcnm(jn), tmlradb_trc(:,:,jn) )
-            END DO
-            !
-         ELSE
-            !
-            CALL iom_rstput( kt, nitrst, nummldw_trc, 'rmldbn_trc', rmldbn_trc )  ! 2D x 1
-            
-            !                                                          ! ===========
-            DO jn = 1, jptra                                           ! tracer loop
-               !                                                       ! ===========
-
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlatfb_trc_' //ctrcnm(jn), tmlatfb_trc (:,:,jn) ) ! 2D x jptra
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlbb_trc_'   //ctrcnm(jn), tmlbb_trc   (:,:,jn) ) ! 2D x jptra
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlradb_trc_' //ctrcnm(jn), tmlradb_trc (:,:,jn) ) ! 2D x jptra
-
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlbn_trc_'   //ctrcnm(jn), tmlbn_trc   (:,:,jn) ) ! 2D x jptra
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tml_sumb_trc_'//ctrcnm(jn), tml_sumb_trc(:,:,jn) ) ! 2D x jptra
-               
-               DO jk = 1, jpltrd_trc
-                  IF( jk < 10 )   THEN
-                     WRITE(charout,FMT="('tmltrd_csum_ub_trc_', A3, '_', I1)") ctrcnm(jn), jk
-                  ELSE
-                     WRITE(charout,FMT="('tmltrd_csum_ub_trc_', A3, '_', I2)") ctrcnm(jn), jk
-                  ENDIF
-                  CALL iom_rstput( kt, nitrst, nummldw_trc, charout, tmltrd_csum_ub_trc(:,:,jk,jn) )
-               END DO
-               
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmltrd_atf_sumb_trc_'//ctrcnm(jn) , &
-                    &           tmltrd_atf_sumb_trc(:,:,jn) ) ! 2D x jptra
-
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmltrd_rad_sumb_trc_'//ctrcnm(jn) , &
-                    &           tmltrd_rad_sumb_trc(:,:,jn) ) ! 2D x jptra
-               !                                                       ! ===========
-            END DO                                                     ! tracer loop
-            !                                                          ! ===========
-#if defined key_pisces_reduced
-            DO jl = 1, jp_pisces_trd
-               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmltrd_csum_ub_bio'//ctrd_bio(jl,2), tmltrd_csum_ub_bio(:,:,jl) )
-            ENDDO
-#endif
-
-         ENDIF
-         
-         CALL iom_close( nummldw_trc )
-         lrst_trc = .TRUE.
-
-      ENDIF
-
-    END SUBROUTINE trd_mld_trc_rst_write
-
-
-    SUBROUTINE trd_mld_trc_rst_read
-      !!----------------------------------------------------------------------------
-      !!                   ***  SUBROUTINE trd_mld_rst_lec  ***
-      !!                   
-      !! ** Purpose :   Read file for mixed-layer diagnostics restart.
-      !!----------------------------------------------------------------------------
-      INTEGER  ::  inum       ! temporary logical unit
-      !
-      CHARACTER (len=35) :: charout
-      INTEGER ::  jk, jn, jl     ! loop indice
-      INTEGER ::  jlibalt = jprstlib
-      LOGICAL ::  llok
-      !!-----------------------------------------------------------------------------
-      
-      IF(lwp)  THEN
-         WRITE(numout,*)
-         WRITE(numout,*) ' trd_mld_trc_rst_read : read the NetCDF MLD restart file'
-         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~'
-      ENDIF
-      
-      IF ( jprstlib == jprstdimg ) THEN
-        ! eventually read netcdf file (monobloc)  for restarting on different number of processors
-        ! if {cn_trdrst_trc_in}.nc exists, then set jlibalt to jpnf90
-        INQUIRE( FILE = TRIM(cn_trdrst_trc_in)//'.nc', EXIST = llok )
-        IF ( llok ) THEN ; jlibalt = jpnf90  ; ELSE ; jlibalt = jprstlib ; ENDIF
-      ENDIF
-
-      CALL iom_open( cn_trdrst_trc_in, inum, kiolib = jlibalt ) 
-      
-      IF( ln_trdmld_trc_instant ) THEN 
-         
-         DO jn = 1, jptra
-            CALL iom_get( inum, jpdom_autoglo, 'tmlbb_trc_'  //ctrcnm(jn), tmlbb_trc  (:,:,jn) )
-            CALL iom_get( inum, jpdom_autoglo, 'tmlbn_trc_'  //ctrcnm(jn), tmlbn_trc  (:,:,jn) )
-            CALL iom_get( inum, jpdom_autoglo, 'tmlatfb_trc_'//ctrcnm(jn), tmlatfb_trc(:,:,jn) )
-            CALL iom_get( inum, jpdom_autoglo, 'tmlradb_trc_'//ctrcnm(jn), tmlradb_trc(:,:,jn) )
-         END DO
-         
-      ELSE
-         CALL iom_get( inum, jpdom_autoglo, 'rmldbn_trc', rmldbn_trc ) ! needed for rmld_sum
-         
-         !                                                          ! ===========
-         DO jn = 1, jptra                                           ! tracer loop
-            !                                                       ! ===========
-            CALL iom_get( inum, jpdom_autoglo, 'tmlatfb_trc_' //ctrcnm(jn), tmlatfb_trc(:,:,jn) )
-            CALL iom_get( inum, jpdom_autoglo, 'tmlbb_trc_'   //ctrcnm(jn), tmlbb_trc  (:,:,jn) )
-            CALL iom_get( inum, jpdom_autoglo, 'tmlradb_trc_' //ctrcnm(jn), tmlradb_trc(:,:,jn) )
-
-            CALL iom_get( inum, jpdom_autoglo, 'tmlbn_trc_'   //ctrcnm(jn), tmlbn_trc   (:,:,jn) ) ! needed for tml_sum
-            CALL iom_get( inum, jpdom_autoglo, 'tml_sumb_trc_'//ctrcnm(jn), tml_sumb_trc(:,:,jn) )
-            
-            DO jk = 1, jpltrd_trc
-               IF( jk < 10 )   THEN
-                  WRITE(charout,FMT="('tmltrd_csum_ub_trc_', A3, '_', I1)") ctrcnm(jn), jk
-               ELSE
-                  WRITE(charout,FMT="('tmltrd_csum_ub_trc_', A3, '_', I2)") ctrcnm(jn), jk
-               ENDIF
-               CALL iom_get( inum, jpdom_autoglo, charout, tmltrd_csum_ub_trc(:,:,jk,jn) )
-            END DO
-            
-            CALL iom_get( inum, jpdom_autoglo, 'tmltrd_atf_sumb_trc_'//ctrcnm(jn) , &
-                 &        tmltrd_atf_sumb_trc(:,:,jn) )
-
-            CALL iom_get( inum, jpdom_autoglo, 'tmltrd_rad_sumb_trc_'//ctrcnm(jn) , &
-                 &        tmltrd_rad_sumb_trc(:,:,jn) )
-            !                                                       ! ===========
-         END DO                                                     ! tracer loop
-         !                                                          ! ===========
-
-#if defined key_pisces_reduced
-         DO jl = 1, jp_pisces_trd
-            CALL iom_get( inum, jpdom_autoglo, 'tmltrd_csum_ub_bio'//ctrd_bio(jl,2), tmltrd_csum_ub_bio(:,:,jl) )
-         ENDDO
-#endif
-         
-         CALL iom_close( inum )
-      ENDIF
-      
-    END SUBROUTINE trd_mld_trc_rst_read
-  
-#else
-  !!=================================================================================
-  !!                       ***  MODULE  trdmld_rst  ***
-  !! Ocean dynamic :  Input/Output files for restart on mixed-layer diagnostics
-  !!=================================================================================
-CONTAINS
-  SUBROUTINE trd_mld_trc_rst_opn( kt )
-    WRITE(*,*) 'trd_mld_trc_rst_opn: You should not have seen this print! error?', kt
-  END SUBROUTINE trd_mld_trc_rst_opn
-  SUBROUTINE trd_mld_trc_rst_write( kt )           !  No ML diags ==> empty routine
-    WRITE(*,*) 'trd_mld_trc_rst_wri: You should not have seen this print! error?', kt
-  END SUBROUTINE trd_mld_trc_rst_write
-  SUBROUTINE trd_mld_trc_rst_read                  !  No ML Diags ==> empty routine
-  END SUBROUTINE trd_mld_trc_rst_read
-#endif
-
-  !!=================================================================================
-END MODULE trdmld_trc_rst
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmod_trc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmod_trc.F90	(revision 5074)
+++ 	(revision )
@@ -1,158 +1,0 @@
-MODULE trdmod_trc
-   !!======================================================================
-   !!                       ***  MODULE  trdmod_trc  ***
-   !! Ocean diagnostics:  mixed layer passive tracer trends 
-   !!======================================================================
-   !! History :  3.0  !  2010-07  (C. Ethe)  Original code (from trdmod.F90)
-   !!----------------------------------------------------------------------
-#if   defined key_top && ( defined key_trdmld_trc   ||   defined key_trdtrc )
-   !!----------------------------------------------------------------------
-   !!   'key_trdmld_trc'                  mixed layer trend diagnostics
-   !!   'key_trdtrc'                      3D trend diagnostics
-   !!----------------------------------------------------------------------
-   !!   trd_mod_trc      : passive tracer trends 
-   !!----------------------------------------------------------------------
-   USE trc               ! tracer definitions (trn, trb, tra, etc.)
-   USE trcnam_trp
-   USE trdmod_oce
-   USE trdmod_trc_oce    ! definition of main arrays used for trends computations
-   USE trdmld_trc        ! Mixed layer trends diag.
-   USE iom               ! I/O library
-
-   IMPLICIT NONE
-   PRIVATE
-
-   INTERFACE trd_mod_trc
-      MODULE PROCEDURE trd_mod_trc_trp, trd_mod_trc_bio
-   END INTERFACE
-
-   PUBLIC trd_mod_trc
-
-   !! * Substitutions
-#  include "top_substitute.h90"
-   !!----------------------------------------------------------------------
-   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
-   !! $Header:  $ 
-   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-
-CONTAINS
-
-   SUBROUTINE trd_mod_trc_trp( ptrtrd, kjn, ktrd, kt )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mod_trc  ***
-      !!----------------------------------------------------------------------
-      INTEGER, INTENT( in )  ::   kt                                  ! time step
-      INTEGER, INTENT( in )  ::   kjn                                 ! tracer index
-      INTEGER, INTENT( in )  ::   ktrd                                ! tracer trend index
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( inout )  ::   ptrtrd  ! Temperature or U trend
-      CHARACTER (len=20) :: cltra
-      !!----------------------------------------------------------------------
-
-      IF( kt == nittrc000 ) THEN
-!         IF(lwp)WRITE(numout,*)
-!         IF(lwp)WRITE(numout,*) 'trd_mod_trc:'
-!         IF(lwp)WRITE(numout,*) '~~~~~~~~~~~~'
-      ENDIF
-
-      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
-      ! Mixed layer trends for passive tracers
-      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
-#if defined key_trdmld_trc  
-      IF( lk_trdmld_trc .AND. ln_trdtrc( kjn ) ) THEN
-         !
-         SELECT CASE ( ktrd )
-         CASE ( jptra_trd_xad     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_xad, '3D', kjn )
-         CASE ( jptra_trd_yad     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_yad, '3D', kjn )
-         CASE ( jptra_trd_zad     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_zad, '3D', kjn )
-         CASE ( jptra_trd_ldf     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_ldf, '3D', kjn )
-         CASE ( jptra_trd_bbl     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_bbl, '3D', kjn )
-         CASE ( jptra_trd_zdf     )
-            IF( ln_trcldf_iso ) THEN
-               CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_ldf, '3D', kjn )
-            ELSE
-               CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_zdf, '3D', kjn )
-            ENDIF
-         CASE ( jptra_trd_dmp     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_dmp , '3D', kjn )
-         CASE ( jptra_trd_nsr     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_sbc , '2D', kjn )
-         CASE ( jptra_trd_sms     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_sms , '3D', kjn )
-         CASE ( jptra_trd_radb    )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_radb, '3D', kjn )
-         CASE ( jptra_trd_radn    )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_radn, '3D', kjn )
-         CASE ( jptra_trd_atf     )   ;   CALL trd_mld_trc_zint( ptrtrd, jpmld_trc_atf , '3D', kjn )
-         END SELECT
-         !
-      END IF
-#endif
-
-      IF( lk_trdtrc .AND. ln_trdtrc( kjn ) ) THEN
-         !
-         SELECT CASE( ktrd )
-         CASE( jptra_trd_xad  )       ;    WRITE (cltra,'("XAD_",4a)')
-         CASE( jptra_trd_yad  )       ;    WRITE (cltra,'("YAD_",4a)')
-         CASE( jptra_trd_zad  )       ;    WRITE (cltra,'("ZAD_",4a)')
-         CASE( jptra_trd_ldf  )       ;    WRITE (cltra,'("LDF_",4a)')
-         CASE( jptra_trd_bbl  )       ;    WRITE (cltra,'("BBL_",4a)')
-         CASE( jptra_trd_nsr  )       ;    WRITE (cltra,'("FOR_",4a)')
-         CASE( jptra_trd_zdf  )       ;    WRITE (cltra,'("ZDF_",4a)')
-         CASE( jptra_trd_dmp  )       ;    WRITE (cltra,'("DMP_",4a)')
-         CASE( jptra_trd_sms  )       ;    WRITE (cltra,'("SMS_",4a)')
-         CASE( jptra_trd_atf  )       ;    WRITE (cltra,'("ATF_",4a)')
-         CASE( jptra_trd_radb )       ;    WRITE (cltra,'("RDB_",4a)')
-         CASE( jptra_trd_radn )       ;    WRITE (cltra,'("RDN_",4a)')
-         END SELECT
-                                          cltra = TRIM(cltra)//TRIM(ctrcnm(kjn))
-                                          CALL iom_put( cltra,  ptrtrd(:,:,:) )
-         !
-      END IF
-
-   END SUBROUTINE trd_mod_trc_trp
-
-   SUBROUTINE trd_mod_trc_bio( ptrbio, ktrd, kt )
-      !!----------------------------------------------------------------------
-      !!                  ***  ROUTINE trd_mod_bio  ***
-      !!----------------------------------------------------------------------
-
-      INTEGER, INTENT( in )  ::   kt                                  ! time step
-      INTEGER, INTENT( in )  ::   ktrd                                ! bio trend index
-      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( inout )  ::   ptrbio  ! Bio trend
-      !!----------------------------------------------------------------------
-
-#if defined key_trdmld_trc  
-      CALL trd_mld_bio_zint( ptrbio, ktrd ) ! Verticaly integrated biological trends
-#endif
-
-   END SUBROUTINE trd_mod_trc_bio
-#else
-   !!----------------------------------------------------------------------
-   !!   Default option :                                       Empty module
-   !!----------------------------------------------------------------------
-
-   INTERFACE trd_mod_trc
-      MODULE PROCEDURE trd_mod_trc_trp, trd_mod_trc_bio
-   END INTERFACE
-
-CONTAINS
-
-   SUBROUTINE trd_mod_trc_trp( ptrtrd, kjn, ktrd, kt )
-      INTEGER               , INTENT( in )     ::   kt      ! time step
-      INTEGER               , INTENT( in )     ::   kjn     ! tracer index
-      INTEGER               , INTENT( in )     ::   ktrd    ! tracer trend index
-      REAL, DIMENSION(:,:,:), INTENT( inout )  ::   ptrtrd  ! Temperature or U trend
-      WRITE(*,*) 'trd_mod_trc_trp : You should not have seen this print! error?', ptrtrd(1,1,1)
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kjn
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', ktrd
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kt
-   END SUBROUTINE trd_mod_trc_trp
-
-   SUBROUTINE trd_mod_trc_bio( ptrbio, ktrd, kt )
-      INTEGER               , INTENT( in )     ::   kt      ! time step
-      INTEGER               , INTENT( in )     ::   ktrd    ! tracer trend index
-      REAL, DIMENSION(:,:,:), INTENT( inout )  ::   ptrbio  ! Temperature or U trend
-      WRITE(*,*) 'trd_mod_trc_trp : You should not have seen this print! error?', ptrbio(1,1,1)
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', ktrd
-      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kt
-   END SUBROUTINE trd_mod_trc_bio
-
-#endif
-   !!======================================================================
-END MODULE trdmod_trc
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmod_trc_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmod_trc_oce.F90	(revision 5074)
+++ 	(revision )
@@ -1,180 +1,0 @@
-MODULE trdmod_trc_oce
-   !!======================================================================
-   !!                   ***  MODULE trdmod_trc_oce  ***
-   !! Ocean trends :   set tracer and momentum trend variables
-   !!======================================================================
-#if defined key_top   ||   defined key_esopa
-   !!----------------------------------------------------------------------
-   !!   'key_top'                                                TOP models
-   !!----------------------------------------------------------------------
-   USE par_oce       ! ocean parameters
-   USE par_trc       ! passive tracers parameters
-
-   IMPLICIT NONE
-   PUBLIC
-
-   !                                         !!* Namelist namtoptrd:  diagnostics on passive tracers trends
-   INTEGER  ::    nn_trd_trc                  !: time step frequency dynamics and tracers trends
-   INTEGER  ::    nn_ctls_trc                 !: control surface type for trends vertical integration
-   REAL(wp) ::    rn_ucf_trc                  !: unit conversion factor (for netCDF trends outputs)
-   LOGICAL  ::    ln_trdmld_trc_instant       !: flag to diagnose inst./mean ML trc trends
-   LOGICAL  ::    ln_trdmld_trc_restart       !: flag to restart mixed-layer trc diagnostics
-   CHARACTER(len=50) ::  cn_trdrst_trc_in     !: suffix of pass. tracer restart name (input)
-   CHARACTER(len=50) ::  cn_trdrst_trc_out    !: suffix of pass. tracer restart name (output)
-   LOGICAL, DIMENSION(jptra) ::   ln_trdtrc   !: large trends diagnostic to write or not (namelist)
-
-# if defined key_trdtrc && defined key_iomput
-   LOGICAL, PARAMETER ::   lk_trdtrc = .TRUE. 
-# else
-   LOGICAL, PARAMETER ::   lk_trdtrc = .FALSE.   !: ML trend flag
-# endif
-
-# if defined key_trdmld_trc   ||   defined key_esopa
-   !!----------------------------------------------------------------------
-   !!   'key_trdmld_trc'                     mixed layer trends diagnostics
-   !!----------------------------------------------------------------------
-
-   LOGICAL, PARAMETER ::   lk_trdmld_trc = .TRUE.    !: ML trend flag
-
-   INTEGER, PARAMETER ::            & !: mixed layer trends indices
-        jpmld_trc_xad     =  1,     & !:     zonal       advection     
-        jpmld_trc_yad     =  2,     & !:     meridonal   =========
-        jpmld_trc_zad     =  3,     & !:     vertical    =========
-        jpmld_trc_ldf     =  4,     & !:     lateral diffusion (geopot. or iso-neutral)
-        jpmld_trc_zdf     =  5,     & !:     vertical diffusion (TKE)
-        jpmld_trc_bbl     =  6,     & !:     bottom boundary layer (advective/diffusive)
-        jpmld_trc_dmp     =  7,     & !:     internal restoring trend
-        jpmld_trc_sbc     =  8,     & !:     forcing 
-        jpmld_trc_sms     =  9,     & !:     sources minus sinks trend
-  !     jpmld_trc_xxx     = xx,     & !:     add here any additional trend    (** AND UPDATE JPLTRD_TRC BELOW **)
-        jpmld_trc_radn    = 10,     & !:     corr. trn<0 in trcrad
-        jpmld_trc_radb    = 11,     & !:     corr. trb<0 in trcrad (like atf) (** MUST BE BEFORE THE LAST ONE **)
-        jpmld_trc_atf     = 12        !:     asselin trend                    (** MUST BE    THE      LAST ONE**)
-
-   !! Trends diagnostics parameters
-   !!---------------------------------------------------------------------
-   INTEGER, PARAMETER :: jpltrd_trc = 12    !: number of mixed-layer trends arrays
-      
-   INTEGER            :: jpktrd_trc         !: max level for mixed-layer trends diag.
-
-   !! Arrays used for diagnosing mixed-layer trends 
-   !!---------------------------------------------------------------------
-   CHARACTER(LEN=80) :: clname_trc, ctrd_trc(jpltrd_trc+1,2)
-
-   INTEGER, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   &
-      nmld_trc       , &                            !: mixed layer depth indexes 
-      nbol_trc                                   !: mixed-layer depth indexes when read from file
-
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  wkx_trc  !:
-
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::  rmld_trc     !: ML depth (m) corresponding to nmld_trc
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::  rmld_sum_trc !: needed to compute the leap-frog time mean of ML depth
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::  rmldbn_trc   !: idem
-
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  &
-      tml_trc    ,                        &      !: \ "now" mixed layer temperature/salinity
-      tmlb_trc   ,                        &      !: /  and associated "before" fields
-      tmlbb_trc  ,                        &      !: \  idem, but valid at the 1rst time step of the
-      tmlbn_trc  ,                        &      !: /  current analysis window
-      tml_sum_trc,                        &      !: mixed layer T, summed over the current analysis period
-      tml_sumb_trc,                       &      !: idem, but from the previous analysis period
-      tmltrd_atf_sumb_trc,                &      !: Asselin trends, summed over the previous analysis period
-      tmltrd_rad_sumb_trc                        !: trends due to trb correction in trcrad.F90, summed over the
-                                                 !:     previous analysis period
-                                                 
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  &      
-      tmlatfb_trc, tmlatfn_trc ,          &      !: "before" Asselin contrib. at beginning of the averaging
-                                                 !:     period (i.e. last contrib. from previous such period)
-                                                 !:     and "now" Asselin contrib. to the ML trc. trends
-      tmlatfm_trc,                        &      !: accumulator for Asselin trends (needed for storage only)
-      tmlradb_trc, tmlradn_trc ,          &      !: similar to Asselin above, but for the trend due to trb
-                                                 !:     correction in trcrad.F90
-      tmlradm_trc                                !: accumulator for the previous trcrad trend
-
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  &
-      tmltrd_trc,                         &      !: \ physical contributions to the total trend (for T/S),
-                                                 !: / cumulated over the current analysis window
-      tmltrd_sum_trc,                     &      !: sum of these trends over the analysis period
-      tmltrd_csum_ln_trc,                 &      !: now cumulated sum of trends over the "lower triangle"
-      tmltrd_csum_ub_trc                         !: before (prev. analysis period) cumulated sum over the
-                                                 !: upper triangle
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  &
-      tmltrdm_trc                                !: total cumulative trends over the analysis window
-
-# else
-   LOGICAL, PARAMETER ::   lk_trdmld_trc = .FALSE.   !: ML trend flag
-# endif
-
-# if defined key_pisces_reduced
-   CHARACTER(LEN=80) :: clname_bio, ctrd_bio(jpdiabio,2)
-   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  &
-      tmltrd_bio,                         &      !: \ biological contributions to the total trend ,
-                                                 !: / cumulated over the current analysis window
-      tmltrd_sum_bio,                     &      !: sum of these trends over the analysis period
-      tmltrd_csum_ln_bio,                 &      !: now cumulated sum of trends over the "lower triangle"
-      tmltrd_csum_ub_bio                         !: before (prev. analysis period) cumulated sum over the
-                                                 !: upper triangle
-#endif
-   !!----------------------------------------------------------------------
-   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
-   !! $Header: /home/opalod/NEMOCVSROOT/NEMO/OPA_SRC/TRD/trdmld_oce.F90,v 1.2 2005/03/27 18:35:23 opalod Exp $ 
-   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-   !!----------------------------------------------------------------------
-CONTAINS
-
-   INTEGER FUNCTION trd_mod_trc_oce_alloc()
-      !!----------------------------------------------------------------------
-      !!         *** ROUTINE trd_mod_trc_oce_alloc ***
-      !!----------------------------------------------------------------------
-      USE lib_mpp, ONLY: ctl_warn
-      INTEGER :: ierr(2)
-      !!----------------------------------------------------------------------
-      ierr(:) = 0
-      !
-# if defined key_trdmld_trc
-      ALLOCATE(nmld_trc(jpi,jpj),          nbol_trc(jpi,jpj),           &
-               wkx_trc(jpi,jpj,jpk),       rmld_trc(jpi,jpj),           &
-               rmld_sum_trc(jpi,jpj),      rmldbn_trc(jpi,jpj),         &
-               tml_trc(jpi,jpj,jptra),     tmlb_trc(jpi,jpj,jptra),     &
-               tmlbb_trc(jpi,jpj,jptra),   tmlbn_trc(jpi,jpj,jptra),    &
-               tml_sum_trc(jpi,jpj,jptra), tml_sumb_trc(jpi,jpj,jptra), &
-               tmltrd_atf_sumb_trc(jpi,jpj,jptra),                      &
-               tmltrd_rad_sumb_trc(jpi,jpj,jptra),                      &
-               !
-               tmlatfb_trc(jpi,jpj,jptra), tmlatfn_trc(jpi,jpj,jptra),  &
-               tmlatfm_trc(jpi,jpj,jptra), tmlradb_trc(jpi,jpj,jptra),  &
-               tmlradn_trc(jpi,jpj,jptra), tmlradm_trc(jpi,jpj,jptra),  &
-               !
-               tmltrd_trc(jpi,jpj,jpltrd_trc,jptra)         , &
-               tmltrd_sum_trc(jpi,jpj,jpltrd_trc,jptra)     , &
-               tmltrd_csum_ln_trc(jpi,jpj,jpltrd_trc,jptra) , &
-               tmltrd_csum_ub_trc(jpi,jpj,jpltrd_trc,jptra) , &
-               !
-               tmltrdm_trc(jpi,jpj,jptra)                   , STAT=ierr(1) )
-#endif
-      !
-# if defined key_pisces_reduced
-      ALLOCATE( tmltrd_bio        (jpi,jpj,jpdiabio) ,     &
-         &      tmltrd_sum_bio    (jpi,jpj,jpdiabio) ,     &
-         &      tmltrd_csum_ln_bio(jpi,jpj,jpdiabio) ,     &
-         &      tmltrd_csum_ub_bio(jpi,jpj,jpdiabio) , STAT=ierr(2) )
-# endif
-      !
-      trd_mod_trc_oce_alloc = MAXVAL(ierr)
-      !
-      IF( trd_mod_trc_oce_alloc /= 0 )   CALL ctl_warn('trd_mod_trc_oce_alloc: failed to allocate arrays')
-      !
-# if defined key_trdmld_trc
-      jpktrd_trc = jpk      ! Initialise what used to be a parameter - max level for mixed-layer trends diag.
-# endif
-      !
-   END FUNCTION trd_mod_trc_oce_alloc
-
-#else
-   !!----------------------------------------------------------------------
-   !!  Empty module :                                     No passive tracer
-   !!----------------------------------------------------------------------
-#endif
-
-   !!======================================================================
-END MODULE trdmod_trc_oce
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmxl_trc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmxl_trc.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmxl_trc.F90	(revision 5075)
@@ -0,0 +1,1437 @@
+MODULE trdmxl_trc
+   !!======================================================================
+   !!                       ***  MODULE  trdmxl_trc  ***
+   !! Ocean diagnostics:  mixed layer passive tracer trends 
+   !!======================================================================
+   !! History :  9.0  !  06-08  (C. Deltel)  Original code (from trdmxl.F90)
+   !!                 !  07-04  (C. Deltel)  Bug fix : add trcrad trends
+   !!                 !  07-06  (C. Deltel)  key_gyre : do not call lbc_lnk
+   !!----------------------------------------------------------------------
+#if   defined key_top && ( defined key_trdmxl_trc   ||   defined key_esopa )
+   !!----------------------------------------------------------------------
+   !!   'key_trdmxl_trc'                      mixed layer trend diagnostics
+   !!----------------------------------------------------------------------
+   !!   trd_mxl_trc      : passive tracer cumulated trends averaged over ML
+   !!   trd_mxl_trc_zint : passive tracer trends vertical integration
+   !!   trd_mxl_trc_init : initialization step
+   !!----------------------------------------------------------------------
+   USE trc               ! tracer definitions (trn, trb, tra, etc.)
+   USE trc_oce, ONLY :   nn_dttrc  ! frequency of step on passive tracers
+   USE dom_oce           ! domain definition
+   USE zdfmxl  , ONLY : nmln ! number of level in the mixed layer
+   USE zdf_oce , ONLY : avt  ! vert. diffusivity coef. at w-point for temp  
+# if defined key_zdfddm   
+   USE zdfddm  , ONLY : avs  ! salinity vertical diffusivity coeff. at w-point
+# endif
+   USE trcnam_trp        ! passive tracers transport namelist variables
+   USE trdtrc_oce    ! definition of main arrays used for trends computations
+   USE in_out_manager    ! I/O manager
+   USE dianam            ! build the name of file (routine)
+   USE ldfslp            ! iso-neutral slopes 
+   USE ioipsl            ! NetCDF library
+   USE lbclnk            ! ocean lateral boundary conditions (or mpp link)
+   USE lib_mpp           ! MPP library
+   USE trdmxl_trc_rst    ! restart for diagnosing the ML trends
+   USE prtctl            ! print control
+   USE sms_pisces        ! PISCES bio-model
+   USE wrk_nemo          ! Memory allocation
+
+   IMPLICIT NONE
+   PRIVATE
+
+   PUBLIC trd_mxl_trc
+   PUBLIC trd_mxl_trc_alloc
+   PUBLIC trd_mxl_bio
+   PUBLIC trd_mxl_trc_init
+   PUBLIC trd_mxl_trc_zint
+   PUBLIC trd_mxl_bio_zint
+
+   CHARACTER (LEN=40) ::  clhstnam                                ! name of the trends NetCDF file
+   INTEGER ::   nmoymltrd
+   INTEGER, ALLOCATABLE, SAVE, DIMENSION(:) ::   ndextrd1
+   INTEGER, DIMENSION(jptra) ::   nidtrd, nh_t
+   INTEGER ::   ndimtrd1                        
+   INTEGER, SAVE ::  ionce, icount
+#if defined key_pisces_reduced
+   INTEGER ::   nidtrdbio, nh_tb
+   INTEGER, SAVE ::  ioncebio, icountbio
+   INTEGER, SAVE ::   nmoymltrdbio
+#endif
+   LOGICAL :: llwarn  = .TRUE.                                    ! this should always be .TRUE.
+   LOGICAL :: lldebug = .TRUE.
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  ztmltrd2   !
+#if defined key_pisces_reduced
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  ztmltrdbio2  ! only needed for mean diagnostics in trd_mxl_bio()
+#endif
+
+   !! * Substitutions
+#  include "top_substitute.h90"
+#  include "zdfddm_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Header:  $ 
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_mxl_trc_alloc()
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_trc_alloc  ***
+      !!----------------------------------------------------------------------
+      ALLOCATE( ztmltrd2(jpi,jpj,jpltrd_trc,jptra) ,      &
+#if defined key_pisces_reduced
+         &      ztmltrdbio2(jpi,jpj,jpdiabio)      ,      &
+#endif
+         &      ndextrd1(jpi*jpj)                  ,  STAT=trd_mxl_trc_alloc)
+         !
+      IF( lk_mpp                )   CALL mpp_sum ( trd_mxl_trc_alloc )
+      IF( trd_mxl_trc_alloc /=0 )   CALL ctl_warn('trd_mxl_trc_alloc: failed to allocate arrays')
+      !
+   END FUNCTION trd_mxl_trc_alloc
+
+
+   SUBROUTINE trd_mxl_trc_zint( ptrc_trdmxl, ktrd, ctype, kjn )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_trc_zint  ***
+      !! 
+      !! ** Purpose :   Compute the vertical average of the 3D fields given as arguments 
+      !!                to the subroutine. This vertical average is performed from ocean
+      !!                surface down to a chosen control surface.
+      !!
+      !! ** Method/usage :
+      !!      The control surface can be either a mixed layer depth (time varying)
+      !!      or a fixed surface (jk level or bowl). 
+      !!      Choose control surface with nctls_trc in namelist NAMTRD :
+      !!        nctls_trc = -2  : use isopycnal surface
+      !!        nctls_trc = -1  : use euphotic layer with light criterion 
+      !!        nctls_trc =  0  : use mixed layer with density criterion 
+      !!        nctls_trc =  1  : read index from file 'ctlsurf_idx'
+      !!        nctls_trc >  1  : use fixed level surface jk = nctls_trc
+      !!      Note: in the remainder of the routine, the volume between the 
+      !!            surface and the control surface is called "mixed-layer"
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER, INTENT( in ) ::   ktrd, kjn                        ! ocean trend index and passive tracer rank
+      CHARACTER(len=2), INTENT( in ) ::  ctype                    ! surface/bottom (2D) or interior (3D) physics
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( in ) ::  ptrc_trdmxl ! passive tracer trend
+      !
+      INTEGER ::   ji, jj, jk, isum
+      REAL(wp), POINTER, DIMENSION(:,:) :: zvlmsk
+      !!----------------------------------------------------------------------
+
+      CALL wrk_alloc( jpi, jpj, zvlmsk )
+
+      ! I. Definition of control surface and integration weights
+      ! --------------------------------------------------------
+
+      ONCE_PER_TIME_STEP : IF( icount == 1 ) THEN
+         !
+         tmltrd_trc(:,:,:,:) = 0.e0                               ! <<< reset trend arrays to zero
+          
+         ! ... Set nmld(ji,jj) = index of first T point below control surf. or outside mixed-layer
+         SELECT CASE ( nn_ctls_trc )                                ! choice of the control surface
+            CASE ( -2  )   ;   STOP 'trdmxl_trc : not ready '     !     -> isopycnal surface (see ???)
+#if defined key_pisces || defined key_pisces_reduced
+            CASE ( -1  )   ;   nmld_trc(:,:) = neln(:,:)          !     -> euphotic layer with light criterion
+#endif
+            CASE (  0  )   ;   nmld_trc(:,:) = nmln(:,:)          !     -> ML with density criterion (see zdfmxl)
+            CASE (  1  )   ;   nmld_trc(:,:) = nbol_trc(:,:)          !     -> read index from file
+            CASE (  2: )   ;   nn_ctls_trc = MIN( nn_ctls_trc, jpktrd_trc - 1 )
+                               nmld_trc(:,:) = nn_ctls_trc + 1      !     -> model level
+         END SELECT
+
+         ! ... Compute ndextrd1 and ndimtrd1  ??? role de jpktrd_trc
+         IF( ionce == 1 ) THEN
+            !
+            isum  = 0   ;   zvlmsk(:,:) = 0.e0
+
+            IF( jpktrd_trc < jpk ) THEN                           ! description ???
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     IF( nmld_trc(ji,jj) <= jpktrd_trc ) THEN
+                        zvlmsk(ji,jj) = tmask(ji,jj,1)
+                     ELSE
+                        isum = isum + 1
+                        zvlmsk(ji,jj) = 0.e0
+                     ENDIF
+                  END DO
+               END DO
+            ENDIF
+
+            IF( isum > 0 ) THEN                                   ! index of ocean points (2D only)
+               WRITE(numout,*)' tmltrd_trc : Number of invalid points nmld_trc > jpktrd', isum 
+               CALL wheneq( jpi*jpj, zvlmsk(:,:) , 1, 1., ndextrd1, ndimtrd1 )
+            ELSE 
+               CALL wheneq( jpi*jpj, tmask(:,:,1), 1, 1., ndextrd1, ndimtrd1 )
+            ENDIF                                
+
+            ionce = 0                                             ! no more pass here
+            !
+         ENDIF   ! ionce == 1
+         
+         ! ... Weights for vertical averaging
+         wkx_trc(:,:,:) = 0.e0
+         DO jk = 1, jpktrd_trc                                    ! initialize wkx_trc with vertical scale factor in mixed-layer
+            DO jj = 1, jpj
+               DO ji = 1, jpi
+                  IF( jk - nmld_trc(ji,jj) < 0 )   wkx_trc(ji,jj,jk) = fse3t(ji,jj,jk) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+         
+         rmld_trc(:,:) = 0.e0
+         DO jk = 1, jpktrd_trc                                    ! compute mixed-layer depth : rmld_trc
+            rmld_trc(:,:) = rmld_trc(:,:) + wkx_trc(:,:,jk)
+         END DO
+         
+         DO jk = 1, jpktrd_trc                                    ! compute integration weights
+            wkx_trc(:,:,jk) = wkx_trc(:,:,jk) / MAX( 1., rmld_trc(:,:) )
+         END DO
+
+         icount = 0                                               ! <<< flag = off : control surface & integr. weights
+         !                                                        !     computed only once per time step
+      ENDIF ONCE_PER_TIME_STEP
+
+      ! II. Vertical integration of trends in the mixed-layer
+      ! -----------------------------------------------------
+
+      SELECT CASE ( ctype )
+         CASE ( '3D' )                                            ! mean passive tracer trends in the mixed-layer
+            DO jk = 1, jpktrd_trc
+               tmltrd_trc(:,:,ktrd,kjn) = tmltrd_trc(:,:,ktrd,kjn) + ptrc_trdmxl(:,:,jk) * wkx_trc(:,:,jk)   
+            END DO
+         CASE ( '2D' )                                            ! forcing at upper boundary of the mixed-layer 
+            tmltrd_trc(:,:,ktrd,kjn) = tmltrd_trc(:,:,ktrd,kjn) + ptrc_trdmxl(:,:,1) * wkx_trc(:,:,1)  ! non penetrative
+      END SELECT
+      !
+      CALL wrk_dealloc( jpi, jpj, zvlmsk )
+      !
+   END SUBROUTINE trd_mxl_trc_zint
+
+
+   SUBROUTINE trd_mxl_bio_zint( ptrc_trdmxl, ktrd )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_bio_zint  ***
+      !!
+      !! ** Purpose :   Compute the vertical average of the 3D fields given as arguments
+      !!                to the subroutine. This vertical average is performed from ocean
+      !!                surface down to a chosen control surface.
+      !!
+      !! ** Method/usage :
+      !!      The control surface can be either a mixed layer depth (time varying)
+      !!      or a fixed surface (jk level or bowl).
+      !!      Choose control surface with nctls in namelist NAMTRD :
+      !!        nctls_trc = 0  : use mixed layer with density criterion
+      !!        nctls_trc = 1  : read index from file 'ctlsurf_idx'
+      !!        nctls_trc > 1  : use fixed level surface jk = nctls_trc
+      !!      Note: in the remainder of the routine, the volume between the
+      !!            surface and the control surface is called "mixed-layer"
+      !!----------------------------------------------------------------------
+      !!
+      INTEGER                         , INTENT(in) ::   ktrd          ! bio trend index
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT(in) ::   ptrc_trdmxl   ! passive trc trend
+#if defined key_pisces_reduced
+      !
+      INTEGER ::   ji, jj, jk, isum
+      REAL(wp), POINTER, DIMENSION(:,:) :: zvlmsk
+      !!----------------------------------------------------------------------
+
+      CALL wrk_alloc( jpi, jpj, zvlmsk )
+
+      ! I. Definition of control surface and integration weights
+      ! --------------------------------------------------------
+      !            ==> only once per time step <==
+
+      IF( icountbio == 1 ) THEN
+         !
+         tmltrd_bio(:,:,:) = 0.e0    ! <<< reset trend arrays to zero
+         ! ... Set nmld(ji,jj) = index of first T point below control surf. or outside mixed-layer
+         SELECT CASE ( nn_ctls_trc )                                    ! choice of the control surface
+            CASE ( -2  )   ;   STOP 'trdmxl_trc : not ready '     !     -> isopycnal surface (see ???)
+            CASE ( -1  )   ;   nmld_trc(:,:) = neln(:,:)          !     -> euphotic layer with light criterion
+            CASE (  0  )   ;   nmld_trc(:,:) = nmln(:,:)          !     -> ML with density criterion (see zdfmxl)
+            CASE (  1  )   ;   nmld_trc(:,:) = nbol_trc(:,:)          !     -> read index from file
+            CASE (  2: )   ;   nn_ctls_trc = MIN( nn_ctls_trc, jpktrd_trc - 1 )
+                               nmld_trc(:,:) = nn_ctls_trc + 1          !     -> model level
+         END SELECT
+
+         ! ... Compute ndextrd1 and ndimtrd1 only once
+         IF( ioncebio == 1 ) THEN
+            !
+            ! Check of validity : nmld_trc(ji,jj) <= jpktrd_trc
+            isum        = 0
+            zvlmsk(:,:) = 0.e0
+
+            IF( jpktrd_trc < jpk ) THEN
+               DO jj = 1, jpj
+                  DO ji = 1, jpi
+                     IF( nmld_trc(ji,jj) <= jpktrd_trc ) THEN
+                        zvlmsk(ji,jj) = tmask(ji,jj,1)
+                     ELSE
+                        isum = isum + 1
+                        zvlmsk(ji,jj) = 0.
+                     END IF
+                  END DO
+               END DO
+            END IF
+
+            ! Index of ocean points (2D only)
+            IF( isum > 0 ) THEN
+               WRITE(numout,*)' tmltrd_trc : Number of invalid points nmld_trc > jpktrd', isum
+               CALL wheneq( jpi*jpj, zvlmsk(:,:) , 1, 1., ndextrd1, ndimtrd1 )
+            ELSE
+               CALL wheneq( jpi*jpj, tmask(:,:,1), 1, 1., ndextrd1, ndimtrd1 )
+            END IF
+
+            ioncebio = 0                  ! no more pass here
+            !
+         END IF !  ( ioncebio == 1 )
+
+         ! ... Weights for vertical averaging
+         wkx_trc(:,:,:) = 0.e0
+         DO jk = 1, jpktrd_trc         ! initialize wkx_trc with vertical scale factor in mixed-layer
+            DO jj = 1,jpj
+              DO ji = 1,jpi
+                  IF( jk - nmld_trc(ji,jj) < 0. )   wkx_trc(ji,jj,jk) = fse3t(ji,jj,jk) * tmask(ji,jj,jk)
+               END DO
+            END DO
+         END DO
+
+         rmld_trc(:,:) = 0.
+         DO jk = 1, jpktrd_trc         ! compute mixed-layer depth : rmld_trc
+            rmld_trc(:,:) = rmld_trc(:,:) + wkx_trc(:,:,jk)
+         END DO
+
+         DO jk = 1, jpktrd_trc         ! compute integration weights
+            wkx_trc(:,:,jk) = wkx_trc(:,:,jk) / MAX( 1., rmld_trc(:,:) )
+         END DO
+
+         icountbio = 0                    ! <<< flag = off : control surface & integr. weights
+         !                             !     computed only once per time step
+      END IF ! ( icountbio == 1 )
+
+      ! II. Vertical integration of trends in the mixed-layer
+      ! -----------------------------------------------------
+
+
+      DO jk = 1, jpktrd_trc
+         tmltrd_bio(:,:,ktrd) = tmltrd_bio(:,:,ktrd) + ptrc_trdmxl(:,:,jk) * wkx_trc(:,:,jk)
+      END DO
+
+      CALL wrk_dealloc( jpi, jpj, zvlmsk )
+#endif
+      !
+   END SUBROUTINE trd_mxl_bio_zint
+
+
+   SUBROUTINE trd_mxl_trc( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_trc  ***
+      !! 
+      !! ** Purpose :  Compute and cumulate the mixed layer trends over an analysis
+      !!               period, and write NetCDF (or dimg) outputs.
+      !!
+      !! ** Method/usage :
+      !!          The stored trends can be chosen twofold (according to the ln_trdmxl_trc_instant 
+      !!          logical namelist variable) :
+      !!          1) to explain the difference between initial and final 
+      !!             mixed-layer T & S (where initial and final relate to the
+      !!             current analysis window, defined by ntrc_trc in the namelist)
+      !!          2) to explain the difference between the current and previous 
+      !!             TIME-AVERAGED mixed-layer T & S (where time-averaging is
+      !!             performed over each analysis window).
+      !!
+      !! ** Consistency check : 
+      !!        If the control surface is fixed ( nctls_trc > 1 ), the residual term (dh/dt
+      !!        entrainment) should be zero, at machine accuracy. Note that in the case
+      !!        of time-averaged mixed-layer fields, this residual WILL NOT BE ZERO
+      !!        over the first two analysis windows (except if restart).
+      !!        N.B. For ORCA2_LIM, use e.g. ntrc_trc=5, rn_ucf_trc=1., nctls_trc=8
+      !!             for checking residuals.
+      !!             On a NEC-SX5 computer, this typically leads to:
+      !!                   O(1.e-20) temp. residuals (tml_res) when ln_trdmxl_trc_instant=.false.
+      !!                   O(1.e-21) temp. residuals (tml_res) when ln_trdmxl_trc_instant=.true.
+      !!
+      !! ** Action :
+      !!       At each time step, mixed-layer averaged trends are stored in the 
+      !!       tmltrd(:,:,jpmxl_xxx) array (see trdmxl_oce.F90 for definitions of jpmxl_xxx).
+      !!       This array is known when trd_mld is called, at the end of the stp subroutine, 
+      !!       except for the purely vertical K_z diffusion term, which is embedded in the
+      !!       lateral diffusion trend.
+      !!
+      !!       In I), this K_z term is diagnosed and stored, thus its contribution is removed
+      !!       from the lateral diffusion trend.
+      !!       In II), the instantaneous mixed-layer T & S are computed, and misc. cumulative
+      !!       arrays are updated.
+      !!       In III), called only once per analysis window, we compute the total trends,
+      !!       along with the residuals and the Asselin correction terms.
+      !!       In IV), the appropriate trends are written in the trends NetCDF file.
+      !!
+      !! References :
+      !!       - Vialard & al.
+      !!       - See NEMO documentation (in preparation)
+      !!----------------------------------------------------------------------
+      !
+      INTEGER, INTENT(in) ::   kt   ! ocean time-step index
+      !
+      INTEGER ::   ji, jj, jk, jl, ik, it, itmod, jn
+      REAL(wp) ::   zavt, zfn, zfn2
+      !
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmltot             ! d(trc)/dt over the anlysis window (incl. Asselin)
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlres             ! residual = dh/dt entrainment term
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlatf             ! for storage only
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlrad             ! for storage only (for trb<0 corr in trcrad)
+      !
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmltot2            ! -+
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlres2            !  | working arrays to diagnose the trends
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmltrdm2           !  | associated with the time meaned ML
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlatf2            !  | passive tracers
+      REAL(wp), POINTER, DIMENSION(:,:,:) ::   ztmlrad2            !  | (-> for trb<0 corr in trcrad)
+      !
+      CHARACTER (LEN=10) ::   clvar
+#if defined key_dimgout
+      INTEGER ::   iyear,imon,iday
+      CHARACTER(LEN=80) ::   cltext, clmode
+#endif
+      !!----------------------------------------------------------------------
+
+      ! Set-up pointers into sub-arrays of workspaces
+      CALL wrk_alloc( jpi, jpj, jptra, ztmltot , ztmlres , ztmlatf , ztmlrad             )
+      CALL wrk_alloc( jpi, jpj, jptra, ztmltot2, ztmlres2, ztmlatf2, ztmlrad2, ztmltrdm2 )
+
+      IF( nn_dttrc  /= 1  )   CALL ctl_stop( " Be careful, trends diags never validated " )
+
+      ! ======================================================================
+      ! I. Diagnose the purely vertical (K_z) diffusion trend
+      ! ======================================================================
+
+      ! ... These terms can be estimated by flux computation at the lower boundary of the ML 
+      !     (we compute (-1/h) * K_z * d_z( tracer ))
+
+      IF( ln_trcldf_iso ) THEN
+         !
+         DO jj = 1,jpj
+            DO ji = 1,jpi
+               ik = nmld_trc(ji,jj)
+               zavt = fsavs(ji,jj,ik)
+               DO jn = 1, jptra
+                  IF( ln_trdtrc(jn) )    &
+                  tmltrd_trc(ji,jj,jpmxl_trc_zdf,jn) = - zavt / fse3w(ji,jj,ik) * tmask(ji,jj,ik)  &
+                       &                    * ( trn(ji,jj,ik-1,jn) - trn(ji,jj,ik,jn) )            &
+                       &                    / MAX( 1., rmld_trc(ji,jj) ) * tmask(ji,jj,1)
+               END DO
+            END DO
+         END DO
+
+         DO jn = 1, jptra
+            ! ... Remove this K_z trend from the iso-neutral diffusion term (if any)
+            IF( ln_trdtrc(jn) ) &
+                 tmltrd_trc(:,:,jpmxl_trc_ldf,jn) = tmltrd_trc(:,:,jpmxl_trc_ldf,jn) - tmltrd_trc(:,:,jpmxl_trc_zdf,jn)
+   
+         END DO
+         !      
+      ENDIF
+
+      IF ( cp_cfg .NE. 'gyre' ) THEN            ! other than GYRE configuration
+      ! GYRE : for diagnostic fields, are needed if cyclic B.C. are present, but not for purely MPI comm. 
+      ! therefore we do not call lbc_lnk in GYRE config. (closed basin, no cyclic B.C.)
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN
+               DO jl = 1, jpltrd_trc
+                  CALL lbc_lnk( tmltrd_trc(:,:,jl,jn), 'T', 1. )        ! lateral boundary conditions
+               END DO
+            ENDIF
+         END DO
+      ENDIF
+      ! ======================================================================
+      ! II. Cumulate the trends over the analysis window
+      ! ======================================================================
+
+      ztmltrd2(:,:,:,:) = 0.e0   ;   ztmltot2(:,:,:)   = 0.e0     ! <<< reset arrays to zero
+      ztmlres2(:,:,:)   = 0.e0   ;   ztmlatf2(:,:,:)   = 0.e0
+      ztmlrad2(:,:,:)   = 0.e0
+
+      ! II.1 Set before values of vertically averages passive tracers
+      ! -------------------------------------------------------------
+      IF( kt > nittrc000 ) THEN
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN
+               tmlb_trc   (:,:,jn) = tml_trc   (:,:,jn)
+               tmlatfn_trc(:,:,jn) = tmltrd_trc(:,:,jpmxl_trc_atf,jn)
+               tmlradn_trc(:,:,jn) = tmltrd_trc(:,:,jpmxl_trc_radb,jn)
+            ENDIF
+         END DO
+      ENDIF
+
+      ! II.2 Vertically averaged passive tracers
+      ! ----------------------------------------
+      tml_trc(:,:,:) = 0.e0
+      DO jk = 1, jpktrd_trc ! - 1 ???
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) &
+               tml_trc(:,:,jn) = tml_trc(:,:,jn) + wkx_trc(:,:,jk) * trn(:,:,jk,jn)
+         END DO
+      END DO
+
+      ! II.3 Initialize mixed-layer "before" arrays for the 1rst analysis window    
+      ! ------------------------------------------------------------------------
+      IF( kt == nittrc000 + nn_dttrc ) THEN  !  i.e. ( .NOT. ln_rstart ).AND.( kt == nit000 + 1)    ???
+         !
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN
+               tmlbb_trc  (:,:,jn) = tmlb_trc   (:,:,jn)   ;   tmlbn_trc  (:,:,jn) = tml_trc    (:,:,jn)
+               tmlatfb_trc(:,:,jn) = tmlatfn_trc(:,:,jn)   ;   tmlradb_trc(:,:,jn) = tmlradn_trc(:,:,jn)
+               
+               tmltrd_csum_ub_trc (:,:,:,jn) = 0.e0   ;   tmltrd_atf_sumb_trc  (:,:,jn) = 0.e0
+               tmltrd_rad_sumb_trc  (:,:,jn) = 0.e0
+            ENDIF
+         END DO
+         
+         rmldbn_trc(:,:) = rmld_trc(:,:)
+         !
+      ENDIF
+
+      ! II.4 Cumulated trends over the analysis period
+      ! ----------------------------------------------
+      !
+      !         [  1rst analysis window ] [     2nd analysis window     ]                       
+      !
+      !     o---[--o-----o-----o-----o--]-[--o-----o-----o-----o-----o--]---o-----o--> time steps
+      !                            ntrd                             2*ntrd       etc.
+      !     1      2     3     4    =5 e.g.                          =10
+      !
+      IF( ( kt >= 2 ).OR.( ln_rsttr ) ) THEN                        ! ???
+         !
+         nmoymltrd = nmoymltrd + 1
+
+
+         ! ... Cumulate over BOTH physical contributions AND over time steps
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN
+               DO jl = 1, jpltrd_trc
+                  tmltrdm_trc(:,:,jn) = tmltrdm_trc(:,:,jn) + tmltrd_trc(:,:,jl,jn)
+               END DO
+            ENDIF
+         END DO
+
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN
+               ! ... Special handling of the Asselin trend 
+               tmlatfm_trc(:,:,jn) = tmlatfm_trc(:,:,jn) + tmlatfn_trc(:,:,jn)
+               tmlradm_trc(:,:,jn) = tmlradm_trc(:,:,jn) + tmlradn_trc(:,:,jn)
+
+               ! ... Trends associated with the time mean of the ML passive tracers
+               tmltrd_sum_trc    (:,:,:,jn) = tmltrd_sum_trc    (:,:,:,jn) + tmltrd_trc    (:,:,:,jn)
+               tmltrd_csum_ln_trc(:,:,:,jn) = tmltrd_csum_ln_trc(:,:,:,jn) + tmltrd_sum_trc(:,:,:,jn)
+               tml_sum_trc       (:,:,jn)   = tml_sum_trc       (:,:,jn)   + tml_trc       (:,:,jn)
+            ENDIF
+         ENDDO
+
+         rmld_sum_trc      (:,:)     = rmld_sum_trc      (:,:)     + rmld_trc      (:,:)
+         !
+      ENDIF
+
+      ! ======================================================================
+      ! III. Prepare fields for output (get here ONCE PER ANALYSIS PERIOD)
+      ! ======================================================================
+
+      ! Convert to appropriate physical units
+      tmltrd_trc(:,:,:,:) = tmltrd_trc(:,:,:,:) * rn_ucf_trc
+
+      itmod = kt - nittrc000 + 1
+      it    = kt
+
+      MODULO_NTRD : IF( MOD( itmod, nn_trd_trc ) == 0 ) THEN           ! nitend MUST be multiple of nn_trd_trc
+         !
+         ztmltot (:,:,:) = 0.e0                                   ! reset arrays to zero
+         ztmlres (:,:,:) = 0.e0
+         ztmltot2(:,:,:) = 0.e0
+         ztmlres2(:,:,:) = 0.e0
+      
+         zfn  = FLOAT( nmoymltrd )    ;    zfn2 = zfn * zfn
+         
+         ! III.1 Prepare fields for output ("instantaneous" diagnostics) 
+         ! -------------------------------------------------------------
+
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN
+               !-- Compute total trends    (use rdttrc instead of rdt ???)
+               IF ( ln_trcadv_muscl .OR. ln_trcadv_muscl2 ) THEN  ! EULER-FORWARD schemes
+                  ztmltot(:,:,jn) =  ( tml_trc(:,:,jn) - tmlbn_trc(:,:,jn) )/rdt
+               ELSE                                                                     ! LEAP-FROG schemes
+                  ztmltot(:,:,jn) =  ( tml_trc(:,:,jn) - tmlbn_trc(:,:,jn) + tmlb_trc(:,:,jn) - tmlbb_trc(:,:,jn))/(2.*rdt)
+               ENDIF
+               
+               !-- Compute residuals
+               ztmlres(:,:,jn) = ztmltot(:,:,jn) - ( tmltrdm_trc(:,:,jn) - tmlatfn_trc(:,:,jn) + tmlatfb_trc(:,:,jn) &
+                  &                                                 - tmlradn_trc(:,:,jn) + tmlradb_trc(:,:,jn)  )
+               
+               !-- Diagnose Asselin trend over the analysis window 
+               ztmlatf(:,:,jn) = tmlatfm_trc(:,:,jn) - tmlatfn_trc(:,:,jn) + tmlatfb_trc(:,:,jn)
+               ztmlrad(:,:,jn) = tmlradm_trc(:,:,jn) - tmlradn_trc(:,:,jn) + tmlradb_trc(:,:,jn)
+               
+         !-- Lateral boundary conditions
+               IF ( cp_cfg .NE. 'gyre' ) THEN
+                  CALL lbc_lnk( ztmltot(:,:,jn) , 'T', 1. )   ;   CALL lbc_lnk( ztmlres(:,:,jn) , 'T', 1. )
+                  CALL lbc_lnk( ztmlatf(:,:,jn) , 'T', 1. )   ;   CALL lbc_lnk( ztmlrad(:,:,jn) , 'T', 1. )
+               ENDIF
+
+
+#if defined key_diainstant
+               STOP 'tmltrd_trc : key_diainstant was never checked within trdmxl. Comment this to proceed.'
+#endif
+            ENDIF
+         END DO
+
+         ! III.2 Prepare fields for output ("mean" diagnostics) 
+         ! ----------------------------------------------------
+         
+         !-- Update the ML depth time sum (to build the Leap-Frog time mean)
+         rmld_sum_trc(:,:) = rmldbn_trc(:,:) + 2 * ( rmld_sum_trc(:,:) - rmld_trc(:,:) ) + rmld_trc(:,:)
+
+               !-- Compute passive tracer total trends
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN
+               tml_sum_trc(:,:,jn) = tmlbn_trc(:,:,jn) + 2 * ( tml_sum_trc(:,:,jn) - tml_trc(:,:,jn) ) + tml_trc(:,:,jn)
+               ztmltot2   (:,:,jn) = ( tml_sum_trc(:,:,jn) - tml_sumb_trc(:,:,jn) ) /  ( 2.*rdt )    ! now tracer unit is /sec
+            ENDIF
+         END DO
+
+         !-- Compute passive tracer residuals
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN
+               !
+               DO jl = 1, jpltrd_trc
+                  ztmltrd2(:,:,jl,jn) = tmltrd_csum_ub_trc(:,:,jl,jn) + tmltrd_csum_ln_trc(:,:,jl,jn)
+               END DO
+               
+               ztmltrdm2(:,:,jn) = 0.e0
+               DO jl = 1, jpltrd_trc
+                  ztmltrdm2(:,:,jn) = ztmltrdm2(:,:,jn) + ztmltrd2(:,:,jl,jn)
+               END DO
+               
+               ztmlres2(:,:,jn) =  ztmltot2(:,:,jn)  -       &
+                  & ( ztmltrdm2(:,:,jn) - tmltrd_sum_trc(:,:,jpmxl_trc_atf ,jn) + tmltrd_atf_sumb_trc(:,:,jn) &
+                  &                     - tmltrd_sum_trc(:,:,jpmxl_trc_radb,jn) + tmltrd_rad_sumb_trc(:,:,jn) )
+               !
+
+               !-- Diagnose Asselin trend over the analysis window
+               ztmlatf2(:,:,jn) = ztmltrd2(:,:,jpmxl_trc_atf ,jn) - tmltrd_sum_trc(:,:,jpmxl_trc_atf ,jn) &
+                  &                                               + tmltrd_atf_sumb_trc(:,:,jn)
+               ztmlrad2(:,:,jn) = ztmltrd2(:,:,jpmxl_trc_radb,jn) - tmltrd_sum_trc(:,:,jpmxl_trc_radb,jn) &
+                  &                                               + tmltrd_rad_sumb_trc(:,:,jn)
+
+         !-- Lateral boundary conditions 
+               IF ( cp_cfg .NE. 'gyre' ) THEN            ! other than GYRE configuration    
+                  CALL lbc_lnk( ztmltot2(:,:,jn), 'T', 1. )
+                  CALL lbc_lnk( ztmlres2(:,:,jn), 'T', 1. )
+                  DO jl = 1, jpltrd_trc
+                     CALL lbc_lnk( ztmltrd2(:,:,jl,jn), 'T', 1. )       ! will be output in the NetCDF trends file
+                  END DO
+               ENDIF
+
+            ENDIF
+         END DO
+
+         ! * Debugging information *
+         IF( lldebug ) THEN
+            !
+            WRITE(numout,*) 'trd_mxl_trc : write trends in the Mixed Layer for debugging process:'
+            WRITE(numout,*) '~~~~~~~~~~~  '
+            WRITE(numout,*)
+            WRITE(numout,*) 'TRC kt = ', kt, '    nmoymltrd = ', nmoymltrd
+
+            DO jn = 1, jptra
+
+               IF( ln_trdtrc(jn) ) THEN
+                  WRITE(numout, *)
+                  WRITE(numout, *) '>>>>>>>>>>>>>>>>>>  TRC TRACER jn =', jn, ' <<<<<<<<<<<<<<<<<<'
+                  
+                  WRITE(numout, *)
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ztmlres     : ', SUM2D(ztmlres(:,:,jn))
+                  !CD??? PREVOIR: z2d = ztmlres(:,:,jn)   ;   CALL prt_ctl(tab2d_1=z2d, clinfo1=' ztmlres   -   : ')
+                  
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ABS(ztmlres): ', SUM2D(ABS(ztmlres(:,:,jn)))
+                  WRITE(numout, '(3x,a)') ' -->>>------------------- ztmlres is computed from ------------- '
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +ztmltot    : ', SUM2D(+ztmltot    (:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmltrdm_trc: ', SUM2D(+tmltrdm_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmlatfn_trc: ', SUM2D(-tmlatfn_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmlatfb_trc: ', SUM2D(+tmlatfb_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmlradn_trc: ', SUM2D(-tmlradn_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmlradb_trc: ', SUM2D(+tmlradb_trc(:,:,jn))
+                  WRITE(numout, '(3x,a)') ' --<<<----------------------------------------------------------- '
+                  
+                  WRITE(numout, *)
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ztmlres2    : ', SUM2D(ztmlres2(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ABS(ztmlres2):', SUM2D(ABS(ztmlres2(:,:,jn)))
+                  WRITE(numout, '(3x,a)') ' -->>>------------------- ztmlres2 is computed from ------------ '
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +ztmltot2            : ', SUM2D(+ztmltot2(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +ztmltrdm2           : ', SUM2D(+ztmltrdm2(:,:,jn)) 
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmltrd_sum_trc      : ', SUM2D(-tmltrd_sum_trc(:,:,jpmxl_trc_atf,jn)) 
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmltrd_atf_sumb_trc : ', SUM2D(+tmltrd_atf_sumb_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmltrd_sum_trc      : ', SUM2D(-tmltrd_sum_trc(:,:,jpmxl_trc_radb,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmltrd_rad_sumb_trc : ', SUM2D(+tmltrd_rad_sumb_trc(:,:,jn) )
+                  WRITE(numout, '(3x,a)') ' --<<<----------------------------------------------------------- '
+                  
+                  WRITE(numout, *)
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM ztmltot     : ', SUM2D(ztmltot    (:,:,jn))
+                  WRITE(numout, '(3x,a)') ' -->>>------------------- ztmltot is computed from ------------- '
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tml_trc    : ', SUM2D(tml_trc    (:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmlbn_trc  : ', SUM2D(tmlbn_trc  (:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM +tmlb_trc   : ', SUM2D(tmlb_trc   (:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM -tmlbb_trc  : ', SUM2D(tmlbb_trc  (:,:,jn))
+                  WRITE(numout, '(3x,a)') ' --<<<----------------------------------------------------------- '
+                  
+                  WRITE(numout, *)
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmltrdm_trc : ', SUM2D(tmltrdm_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmlatfb_trc : ', SUM2D(tmlatfb_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmlatfn_trc : ', SUM2D(tmlatfn_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmlradb_trc : ', SUM2D(tmlradb_trc(:,:,jn))
+                  WRITE(numout,98) 'TRC jn =', jn, ' SUM tmlradn_trc : ', SUM2D(tmlradn_trc(:,:,jn))
+                  
+                  WRITE(numout, *)
+                  DO jl = 1, jpltrd_trc
+                     WRITE(numout,97) 'TRC jn =', jn, ' TREND INDEX jpmxl_trc_xxx = ', jl, &
+                        & ' SUM tmltrd_trc : ', SUM2D(tmltrd_trc(:,:,jl,jn))
+                  END DO
+               
+                  WRITE(numout,*) 
+                  WRITE(numout,*) ' *********************** ZTMLRES, ZTMLRES2 *********************** '
+                  WRITE(numout,*)
+                  WRITE(numout,*) 'TRC ztmlres (jpi/2,jpj/2,:) : ', ztmlres (jpi/2,jpj/2,jn)
+                  WRITE(numout,*)
+                  WRITE(numout,*) 'TRC ztmlres2(jpi/2,jpj/2,:) : ', ztmlres2(jpi/2,jpj/2,jn)
+                  
+                  WRITE(numout,*) 
+                  WRITE(numout,*) ' *********************** ZTMLRES *********************** '
+                  WRITE(numout,*)
+                  
+                  WRITE(numout,*) '...................................................'
+                  WRITE(numout,*) 'TRC jn =', jn, ' ztmlres (1:10,1:5,jn) : '
+                  DO jj = 5, 1, -1
+                     WRITE(numout,99) jj, ( ztmlres (ji,jj,jn), ji=1,10 )
+                  END DO
+                  
+                  WRITE(numout,*) 
+                  WRITE(numout,*) ' *********************** ZTMLRES2 *********************** '
+                  WRITE(numout,*)
+                  
+                  WRITE(numout,*) '...................................................'
+                  WRITE(numout,*) 'TRC jn =', jn, ' ztmlres2 (1:10,1:5,jn) : '
+                  DO jj = 5, 1, -1
+                     WRITE(numout,99) jj, ( ztmlres2 (ji,jj,jn), ji=1,10 )
+                  END DO
+                  !
+               ENDIF
+               !
+            END DO
+
+
+97            FORMAT(a10, i3, 2x, a30, i3, a20, 2x, g20.10)
+98            FORMAT(a10, i3, 2x, a30, 2x, g20.10)
+99            FORMAT('TRC jj =', i3,' : ', 10(g10.3,2x))
+              WRITE(numout,*)
+            !
+         ENDIF
+
+         ! III.3 Time evolution array swap
+         ! -------------------------------
+         ! ML depth
+         rmldbn_trc(:,:)   = rmld_trc(:,:)
+         rmld_sum_trc(:,:)     = rmld_sum_trc(:,:)     /      (2*zfn)  ! similar to tml_sum and sml_sum
+         DO jn = 1, jptra
+            IF( ln_trdtrc(jn) ) THEN        
+               ! For passive tracer instantaneous diagnostics
+               tmlbb_trc  (:,:,jn) = tmlb_trc   (:,:,jn)   ;   tmlbn_trc  (:,:,jn) = tml_trc    (:,:,jn)
+               tmlatfb_trc(:,:,jn) = tmlatfn_trc(:,:,jn)   ;   tmlradb_trc(:,:,jn) = tmlradn_trc(:,:,jn)
+               
+               ! For passive tracer mean diagnostics
+               tmltrd_csum_ub_trc (:,:,:,jn) = zfn * tmltrd_sum_trc(:,:,:,jn) - tmltrd_csum_ln_trc(:,:,:,jn)
+               tml_sumb_trc       (:,:,jn)   = tml_sum_trc(:,:,jn)
+               tmltrd_atf_sumb_trc(:,:,jn)   = tmltrd_sum_trc(:,:,jpmxl_trc_atf ,jn)
+               tmltrd_rad_sumb_trc(:,:,jn)   = tmltrd_sum_trc(:,:,jpmxl_trc_radb,jn)
+               
+               
+               ! III.4 Convert to appropriate physical units
+               ! -------------------------------------------
+               ztmltot     (:,:,jn)   = ztmltot     (:,:,jn)   * rn_ucf_trc/zfn   ! instant diags
+               ztmlres     (:,:,jn)   = ztmlres     (:,:,jn)   * rn_ucf_trc/zfn
+               ztmlatf     (:,:,jn)   = ztmlatf     (:,:,jn)   * rn_ucf_trc/zfn
+               ztmlrad     (:,:,jn)   = ztmlrad     (:,:,jn)   * rn_ucf_trc/zfn
+               tml_sum_trc (:,:,jn)   = tml_sum_trc (:,:,jn)   /      (2*zfn)  ! mean diags
+               ztmltot2    (:,:,jn)   = ztmltot2    (:,:,jn)   * rn_ucf_trc/zfn2
+               ztmltrd2    (:,:,:,jn) = ztmltrd2    (:,:,:,jn) * rn_ucf_trc/zfn2
+               ztmlatf2    (:,:,jn)   = ztmlatf2    (:,:,jn)   * rn_ucf_trc/zfn2
+               ztmlrad2    (:,:,jn)   = ztmlrad2    (:,:,jn)   * rn_ucf_trc/zfn2
+               ztmlres2    (:,:,jn)   = ztmlres2    (:,:,jn)   * rn_ucf_trc/zfn2
+            ENDIF
+         END DO
+         !
+      ENDIF MODULO_NTRD
+
+      ! ======================================================================
+      ! IV. Write trends in the NetCDF file
+      ! ======================================================================
+
+      ! IV.1 Code for dimg mpp output
+      ! -----------------------------
+
+# if defined key_dimgout
+      STOP 'Not implemented'
+# else
+      
+      ! IV.2 Code for IOIPSL/NetCDF output
+      ! ----------------------------------
+
+      IF( lwp .AND. MOD( itmod , nn_trd_trc ) == 0 ) THEN
+         WRITE(numout,*) ' '
+         WRITE(numout,*) 'trd_mxl_trc : write passive tracer trends in the NetCDF file :'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '          ', trim(clhstnam), ' at kt = ', kt
+         WRITE(numout,*) '          N.B. nmoymltrd = ', nmoymltrd
+         WRITE(numout,*) ' '
+      ENDIF
+         
+      NETCDF_OUTPUT : IF( ln_trdmxl_trc_instant ) THEN            ! <<< write the trends for passive tracer instant. diags
+         !
+
+         DO jn = 1, jptra
+            !
+            IF( ln_trdtrc(jn) ) THEN
+               CALL histwrite( nidtrd(jn), "mxl_depth", it, rmld_trc(:,:), ndimtrd1, ndextrd1 )
+               !-- Output the fields
+               clvar = trim(ctrcnm(jn))//"ml"                        ! e.g. detml, zooml, nh4ml, etc.
+               CALL histwrite( nidtrd(jn), trim(clvar)         , it, tml_trc(:,:,jn), ndimtrd1, ndextrd1 ) 
+               CALL histwrite( nidtrd(jn), trim(clvar)//"_tot" , it, ztmltot(:,:,jn), ndimtrd1, ndextrd1 ) 
+               CALL histwrite( nidtrd(jn), trim(clvar)//"_res" , it, ztmlres(:,:,jn), ndimtrd1, ndextrd1 ) 
+           
+               DO jl = 1, jpltrd_trc - 2
+                  CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jl,2)),             &
+                    &          it, tmltrd_trc(:,:,jl,jn), ndimtrd1, ndextrd1 )
+               END DO
+
+               CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmxl_trc_radb,2)),    &  ! now trcrad    : jpltrd_trc - 1
+                    &          it, ztmlrad(:,:,jn), ndimtrd1, ndextrd1 )
+
+               CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmxl_trc_atf,2)),     &  ! now Asselin   : jpltrd_trc
+                    &          it, ztmlatf(:,:,jn), ndimtrd1, ndextrd1 )
+                     
+            ENDIF
+         END DO
+
+         IF( kt == nitend ) THEN 
+            DO jn = 1, jptra
+               IF( ln_trdtrc(jn) )  CALL histclo( nidtrd(jn) )
+            END DO
+         ENDIF
+
+      ELSE                                                        ! <<< write the trends for passive tracer mean diagnostics
+         
+         DO jn = 1, jptra
+            !
+            IF( ln_trdtrc(jn) ) THEN
+               CALL histwrite( nidtrd(jn), "mxl_depth", it, rmld_sum_trc(:,:), ndimtrd1, ndextrd1 ) 
+               !-- Output the fields
+               clvar = trim(ctrcnm(jn))//"ml"                        ! e.g. detml, zooml, nh4ml, etc.
+
+               CALL histwrite( nidtrd(jn), trim(clvar)         , it, tml_sum_trc(:,:,jn), ndimtrd1, ndextrd1 )
+               CALL histwrite( nidtrd(jn), trim(clvar)//"_tot" , it,    ztmltot2(:,:,jn), ndimtrd1, ndextrd1 ) 
+               CALL histwrite( nidtrd(jn), trim(clvar)//"_res" , it,    ztmlres2(:,:,jn), ndimtrd1, ndextrd1 ) 
+
+               DO jl = 1, jpltrd_trc - 2
+                  CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jl,2)),           &
+                    &          it, ztmltrd2(:,:,jl,jn), ndimtrd1, ndextrd1 )
+               END DO
+            
+               CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmxl_trc_radb,2)),   &  ! now trcrad    : jpltrd_trc - 1
+                 &          it, ztmlrad2(:,:,jn), ndimtrd1, ndextrd1 )
+
+               CALL histwrite( nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmxl_trc_atf,2)),    &  ! now Asselin   : jpltrd_trc
+                 &          it, ztmlatf2(:,:,jn), ndimtrd1, ndextrd1 )
+
+            ENDIF 
+            !
+         END DO
+         IF( kt == nitend ) THEN 
+            DO jn = 1, jptra
+               IF( ln_trdtrc(jn) )  CALL histclo( nidtrd(jn) )
+            END DO
+         ENDIF
+
+         !
+      ENDIF NETCDF_OUTPUT
+         
+      ! Compute the control surface (for next time step) : flag = on
+      icount = 1
+
+# endif /* key_dimgout */
+
+      IF( MOD( itmod, nn_trd_trc ) == 0 ) THEN
+         !
+         ! Reset cumulative arrays to zero
+         ! -------------------------------         
+         nmoymltrd = 0
+         tmltrdm_trc        (:,:,:)   = 0.e0   ;   tmlatfm_trc        (:,:,:)   = 0.e0
+         tmlradm_trc        (:,:,:)   = 0.e0   ;   tml_sum_trc        (:,:,:)   = 0.e0
+         tmltrd_csum_ln_trc (:,:,:,:) = 0.e0   ;   tmltrd_sum_trc     (:,:,:,:) = 0.e0
+         rmld_sum_trc       (:,:)     = 0.e0
+         !
+      ENDIF
+
+      ! ======================================================================
+      ! V. Write restart file
+      ! ======================================================================
+
+      IF( lrst_trc )   CALL trd_mxl_trc_rst_write( kt )  ! this must be after the array swap above (III.3)
+
+      CALL wrk_dealloc( jpi, jpj, jptra, ztmltot , ztmlres , ztmlatf , ztmlrad             )
+      CALL wrk_dealloc( jpi, jpj, jptra, ztmltot2, ztmlres2, ztmlatf2, ztmlrad2, ztmltrdm2 )
+      !
+   END SUBROUTINE trd_mxl_trc
+
+
+   SUBROUTINE trd_mxl_bio( kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mld  ***
+      !!
+      !! ** Purpose :  Compute and cumulate the mixed layer biological trends over an analysis
+      !!               period, and write NetCDF (or dimg) outputs.
+      !!
+      !! ** Method/usage :
+      !!          The stored trends can be chosen twofold (according to the ln_trdmxl_trc_instant
+      !!          logical namelist variable) :
+      !!          1) to explain the difference between initial and final
+      !!             mixed-layer T & S (where initial and final relate to the
+      !!             current analysis window, defined by ntrd in the namelist)
+      !!          2) to explain the difference between the current and previous
+      !!             TIME-AVERAGED mixed-layer T & S (where time-averaging is
+      !!             performed over each analysis window).
+      !!
+      !! ** Consistency check :
+      !!        If the control surface is fixed ( nctls > 1 ), the residual term (dh/dt
+      !!        entrainment) should be zero, at machine accuracy. Note that in the case
+      !!        of time-averaged mixed-layer fields, this residual WILL NOT BE ZERO
+      !!        over the first two analysis windows (except if restart).
+      !!        N.B. For ORCA2_LIM, use e.g. ntrd=5, ucf=1., nctls=8
+      !!             for checking residuals.
+      !!             On a NEC-SX5 computer, this typically leads to:
+      !!                   O(1.e-20) temp. residuals (tml_res) when ln_trdmxl_trc_instant=.false.
+      !!                   O(1.e-21) temp. residuals (tml_res) when ln_trdmxl_trc_instant=.true.
+      !!
+      !! ** Action :
+      !!       At each time step, mixed-layer averaged trends are stored in the
+      !!       tmltrd(:,:,jpmxl_xxx) array (see trdmxl_oce.F90 for definitions of jpmxl_xxx).
+      !!       This array is known when trd_mld is called, at the end of the stp subroutine,
+      !!       except for the purely vertical K_z diffusion term, which is embedded in the
+      !!       lateral diffusion trend.
+      !!
+      !!       In I), this K_z term is diagnosed and stored, thus its contribution is removed
+      !!       from the lateral diffusion trend.
+      !!       In II), the instantaneous mixed-layer T & S are computed, and misc. cumulative
+      !!       arrays are updated.
+      !!       In III), called only once per analysis window, we compute the total trends,
+      !!       along with the residuals and the Asselin correction terms.
+      !!       In IV), the appropriate trends are written in the trends NetCDF file.
+      !!
+      !! References :
+      !!       - Vialard & al.
+      !!       - See NEMO documentation (in preparation)
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt                       ! ocean time-step index
+#if defined key_pisces_reduced
+      INTEGER  ::  jl, it, itmod
+      LOGICAL  :: llwarn  = .TRUE., lldebug = .TRUE.
+      REAL(wp) :: zfn, zfn2
+#if defined key_dimgout
+      INTEGER ::  iyear,imon,iday
+      CHARACTER(LEN=80) :: cltext, clmode
+#endif
+      !!----------------------------------------------------------------------
+      ! ... Warnings
+      IF( nn_dttrc  /= 1  ) CALL ctl_stop( " Be careful, trends diags never validated " )
+
+      ! ======================================================================
+      ! II. Cumulate the trends over the analysis window
+      ! ======================================================================
+
+      ztmltrdbio2(:,:,:) = 0.e0  ! <<< reset arrays to zero
+
+      ! II.3 Initialize mixed-layer "before" arrays for the 1rst analysis window
+      ! ------------------------------------------------------------------------
+      IF( kt == nittrc000 + nn_dttrc ) THEN  !  i.e. ( .NOT. ln_rstart ).AND.( kt == nit000 + 1)
+         !
+         tmltrd_csum_ub_bio (:,:,:) = 0.e0
+         !
+      END IF
+
+      ! II.4 Cumulated trends over the analysis period
+      ! ----------------------------------------------
+      !
+      !         [  1rst analysis window ] [     2nd analysis window     ]
+      !
+      !
+      !     o---[--o-----o-----o-----o--]-[--o-----o-----o-----o-----o--]---o-----o--> time steps
+      !                            ntrd                             2*ntrd       etc.
+      !     1      2     3     4    =5 e.g.                          =10
+      !
+      IF( ( kt >= 2 ).OR.( ln_rsttr ) ) THEN
+         !
+         nmoymltrdbio = nmoymltrdbio + 1
+
+         ! ... Trends associated with the time mean of the ML passive tracers
+         tmltrd_sum_bio    (:,:,:) = tmltrd_sum_bio    (:,:,:) + tmltrd_bio    (:,:,:)
+         tmltrd_csum_ln_bio(:,:,:) = tmltrd_csum_ln_bio(:,:,:) + tmltrd_sum_bio(:,:,:)
+         !
+      END IF
+
+      ! ======================================================================
+      ! III. Prepare fields for output (get here ONCE PER ANALYSIS PERIOD)
+      ! ======================================================================
+
+      ! Convert to appropriate physical units
+      tmltrd_bio(:,:,:) = tmltrd_bio(:,:,:) * rn_ucf_trc
+
+      MODULO_NTRD : IF( MOD( kt, nn_trd_trc ) == 0 ) THEN      ! nitend MUST be multiple of ntrd
+         !
+         zfn  = float(nmoymltrdbio)    ;    zfn2 = zfn * zfn
+
+         ! III.1 Prepare fields for output ("instantaneous" diagnostics)
+         ! -------------------------------------------------------------
+
+#if defined key_diainstant
+         STOP 'tmltrd_bio : key_diainstant was never checked within trdmxl. Comment this to proceed.'
+#endif
+         ! III.2 Prepare fields for output ("mean" diagnostics)
+         ! ----------------------------------------------------
+
+         ztmltrdbio2(:,:,:) = tmltrd_csum_ub_bio(:,:,:) + tmltrd_csum_ln_bio(:,:,:)
+
+         !-- Lateral boundary conditions
+         IF ( cp_cfg .NE. 'gyre' ) THEN            ! other than GYRE configuration 
+            ! ES_B27_CD_WARN : lbc inutile GYRE, cf. + haut
+            DO jn = 1, jpdiabio
+              CALL lbc_lnk( ztmltrdbio2(:,:,jn), 'T', 1. )
+            ENDDO
+         ENDIF
+
+         IF( lldebug ) THEN
+            !
+            WRITE(numout,*) 'trd_mxl_bio : write trends in the Mixed Layer for debugging process:'
+            WRITE(numout,*) '~~~~~~~~~~~  '
+            WRITE(numout,*) 'TRC kt = ', kt, 'nmoymltrdbio = ', nmoymltrdbio
+            WRITE(numout,*)
+
+            DO jl = 1, jpdiabio
+              IF( ln_trdmxl_trc_instant ) THEN
+                  WRITE(numout,97) 'TRC jl =', jl, ' bio TREND INDEX  = ', jl, &
+                     & ' SUM tmltrd_bio : ', SUM2D(tmltrd_bio(:,:,jl))
+              ELSE
+                  WRITE(numout,97) 'TRC jl =', jl, ' bio TREND INDEX  = ', jl, &
+                     & ' SUM ztmltrdbio2 : ', SUM2D(ztmltrdbio2(:,:,jl))
+              endif
+            END DO
+
+97          FORMAT(a10, i3, 2x, a30, i3, a20, 2x, g20.10)
+98          FORMAT(a10, i3, 2x, a30, 2x, g20.10)
+99          FORMAT('TRC jj =', i3,' : ', 10(g10.3,2x))
+            WRITE(numout,*)
+            !
+         ENDIF
+
+         ! III.3 Time evolution array swap
+         ! -------------------------------
+
+         ! For passive tracer mean diagnostics
+         tmltrd_csum_ub_bio (:,:,:) = zfn * tmltrd_sum_bio(:,:,:) - tmltrd_csum_ln_bio(:,:,:)
+
+         ! III.4 Convert to appropriate physical units
+         ! -------------------------------------------
+         ztmltrdbio2    (:,:,:) = ztmltrdbio2    (:,:,:) * rn_ucf_trc/zfn2
+
+      END IF MODULO_NTRD
+
+      ! ======================================================================
+      ! IV. Write trends in the NetCDF file
+      ! ======================================================================
+
+      ! IV.1 Code for dimg mpp output
+      ! -----------------------------
+
+# if defined key_dimgout
+      STOP 'Not implemented'
+# else
+
+      ! IV.2 Code for IOIPSL/NetCDF output
+      ! ----------------------------------
+
+      ! define time axis
+      itmod = kt - nittrc000 + 1
+      it    = kt
+
+      IF( lwp .AND. MOD( itmod , nn_trd_trc ) == 0 ) THEN
+         WRITE(numout,*) ' '
+         WRITE(numout,*) 'trd_mxl_bio : write ML bio trends in the NetCDF file :'
+         WRITE(numout,*) '~~~~~~~~~~~ '
+         WRITE(numout,*) '          ', TRIM(clhstnam), ' at kt = ', kt
+         WRITE(numout,*) '          N.B. nmoymltrdbio = ', nmoymltrdbio
+         WRITE(numout,*) ' '
+      END IF
+
+
+      ! 2. Start writing data
+      ! ---------------------
+
+      NETCDF_OUTPUT : IF( ln_trdmxl_trc_instant ) THEN    ! <<< write the trends for passive tracer instant. diags
+         !
+            DO jl = 1, jpdiabio
+               CALL histwrite( nidtrdbio,TRIM("ML_"//ctrd_bio(jl,2)) ,            &
+                    &          it, tmltrd_bio(:,:,jl), ndimtrd1, ndextrd1 )
+            END DO
+
+
+         IF( kt == nitend )   CALL histclo( nidtrdbio )
+
+      ELSE    ! <<< write the trends for passive tracer mean diagnostics
+
+            DO jl = 1, jpdiabio
+               CALL histwrite( nidtrdbio, TRIM("ML_"//ctrd_bio(jl,2)) ,            &
+                    &          it, ztmltrdbio2(:,:,jl), ndimtrd1, ndextrd1 )
+            END DO
+
+            IF( kt == nitend )   CALL histclo( nidtrdbio )
+            !
+      END IF NETCDF_OUTPUT
+
+      ! Compute the control surface (for next time step) : flag = on
+      icountbio = 1
+
+
+# endif /* key_dimgout */
+
+      IF( MOD( itmod, nn_trd_trc ) == 0 ) THEN
+         !
+         ! III.5 Reset cumulative arrays to zero
+         ! -------------------------------------
+         nmoymltrdbio = 0
+         tmltrd_csum_ln_bio (:,:,:) = 0.e0
+         tmltrd_sum_bio     (:,:,:) = 0.e0
+      END IF
+
+      ! ======================================================================
+      ! Write restart file
+      ! ======================================================================
+
+! restart write is done in trd_mxl_trc_write which is called by trd_mxl_bio (Marina)
+!
+#endif
+   END SUBROUTINE trd_mxl_bio
+
+
+   REAL FUNCTION sum2d( ztab )
+      !!----------------------------------------------------------------------
+      !! CD ??? prevoir d'utiliser plutot prtctl
+      !!----------------------------------------------------------------------
+      REAL(wp), DIMENSION(jpi,jpj), INTENT( in ) ::  ztab      
+      !!----------------------------------------------------------------------
+      sum2d = SUM( ztab(2:jpi-1,2:jpj-1) )
+   END FUNCTION sum2d
+
+
+   SUBROUTINE trd_mxl_trc_init
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_mxl_init  ***
+      !! 
+      !! ** Purpose :   computation of vertically integrated T and S budgets
+      !!      from ocean surface down to control surface (NetCDF output)
+      !!
+      !! ** Method/usage :
+      !!
+      !!----------------------------------------------------------------------
+      INTEGER :: inum   ! logical unit
+      INTEGER :: ilseq, jl, jn, iiter
+      REAL(wp) ::   zjulian, zsto, zout
+      CHARACTER (LEN=40) ::   clop
+      CHARACTER (LEN=15) ::   csuff
+      CHARACTER (LEN=12) ::   clmxl
+      CHARACTER (LEN=16) ::   cltrcu
+      CHARACTER (LEN=10) ::   clvar
+
+      !!----------------------------------------------------------------------
+
+      ! ======================================================================
+      ! I. initialization
+      ! ======================================================================
+
+      IF(lwp) THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' trd_mxl_trc_init : Mixed-layer trends for passive tracers                '
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~'
+         WRITE(numout,*)
+      ENDIF
+
+      
+      ! I.1 Check consistency of user defined preferences
+      ! -------------------------------------------------
+
+      IF( ( lk_trdmxl_trc ) .AND. ( MOD( nitend-nittrc000+1, nn_trd_trc ) /= 0 ) ) THEN
+         WRITE(numout,cform_err)
+         WRITE(numout,*) '                Your nitend parameter, nitend = ', nitend
+         WRITE(numout,*) '                is no multiple of the trends diagnostics frequency        '
+         WRITE(numout,*) '                          you defined, nn_trd_trc   = ', nn_trd_trc
+         WRITE(numout,*) '                This will not allow you to restart from this simulation.  '
+         WRITE(numout,*) '                You should reconsider this choice.                        ' 
+         WRITE(numout,*) 
+         WRITE(numout,*) '                N.B. the nitend parameter is also constrained to be a     '
+         WRITE(numout,*) '                multiple of the sea-ice frequency parameter (typically 5) '
+         nstop = nstop + 1
+      ENDIF
+
+      ! * Debugging information *
+      IF( lldebug ) THEN
+         WRITE(numout,*) '               ln_trcadv_muscl = '      , ln_trcadv_muscl
+         WRITE(numout,*) '               ln_trdmxl_trc_instant = ', ln_trdmxl_trc_instant
+      ENDIF
+
+      IF( ( ln_trcadv_muscl .OR. ln_trcadv_muscl2 ) .AND. .NOT. ln_trdmxl_trc_instant ) THEN
+         WRITE(numout,cform_err)
+         WRITE(numout,*) '                Currently, you can NOT use simultaneously tracer MUSCL    '
+         WRITE(numout,*) '                advection and window averaged diagnostics of ML trends.   '
+         WRITE(numout,*) '                WHY? Everything in trdmxl_trc is coded for leap-frog, and '
+         WRITE(numout,*) '                MUSCL scheme is Euler forward for passive tracers (note   '
+         WRITE(numout,*) '                that MUSCL is leap-frog for active tracers T/S).          '
+         WRITE(numout,*) '                In particuliar, entrainment trend would be FALSE. However '
+         WRITE(numout,*) '                this residual is correct for instantaneous ML diagnostics.'
+         WRITE(numout,*) 
+         nstop = nstop + 1
+      ENDIF
+
+      ! I.2 Initialize arrays to zero or read a restart file
+      ! ----------------------------------------------------
+      nmoymltrd   = 0
+
+      rmld_trc           (:,:)     = 0.e0   ;   tml_trc            (:,:,:)   = 0.e0       ! inst.
+      tmltrdm_trc        (:,:,:)   = 0.e0   ;   tmlatfm_trc        (:,:,:)   = 0.e0
+      tmlradm_trc        (:,:,:)   = 0.e0
+
+      tml_sum_trc        (:,:,:)   = 0.e0   ;   tmltrd_sum_trc     (:,:,:,:) = 0.e0       ! mean
+      tmltrd_csum_ln_trc (:,:,:,:) = 0.e0   ;   rmld_sum_trc       (:,:)     = 0.e0
+
+#if defined key_pisces_reduced
+      nmoymltrdbio   = 0
+      tmltrd_sum_bio     (:,:,:) = 0.e0     ;   tmltrd_csum_ln_bio (:,:,:) = 0.e0
+      DO jl = 1, jp_pisces_trd
+          ctrd_bio(jl,1) = ctrbil(jl)   ! long name
+          ctrd_bio(jl,2) = ctrbio(jl)   ! short name
+       ENDDO
+#endif
+
+      IF( ln_rsttr .AND. ln_trdmxl_trc_restart ) THEN
+         CALL trd_mxl_trc_rst_read
+      ELSE
+         tmlb_trc           (:,:,:)   = 0.e0   ;   tmlbb_trc          (:,:,:)   = 0.e0     ! inst.
+         tmlbn_trc          (:,:,:)   = 0.e0
+
+         tml_sumb_trc       (:,:,:)   = 0.e0   ;   tmltrd_csum_ub_trc (:,:,:,:) = 0.e0     ! mean
+         tmltrd_atf_sumb_trc(:,:,:)   = 0.e0   ;   tmltrd_rad_sumb_trc(:,:,:)   = 0.e0 
+#if defined key_pisces_reduced
+         tmltrd_csum_ub_bio (:,:,:) = 0.e0
+#endif
+
+       ENDIF
+
+      icount = 1   ;   ionce  = 1  ! open specifier   
+
+#if defined key_pisces_reduced
+      icountbio = 1   ;   ioncebio  = 1  ! open specifier
+#endif
+
+      ! I.3 Read control surface from file ctlsurf_idx
+      ! ----------------------------------------------
+      IF( nn_ctls_trc == 1 ) THEN
+         CALL ctl_opn( inum, 'ctlsurf_idx', 'OLD', 'UNFORMATTED', 'SEQUENTIAL', -1, numout, lwp )
+         READ ( inum ) nbol_trc
+         CLOSE( inum )
+      ENDIF
+
+      ! ======================================================================
+      ! II. netCDF output initialization
+      ! ======================================================================
+
+#if defined key_dimgout 
+      ???
+#else
+      ! clmxl = legend root for netCDF output
+      IF( nn_ctls_trc == 0 ) THEN                                   ! control surface = mixed-layer with density criterion
+         clmxl = 'Mixed Layer '
+      ELSE IF( nn_ctls_trc == 1 ) THEN                              ! control surface = read index from file 
+         clmxl = '      Bowl '
+      ELSE IF( nn_ctls_trc >= 2 ) THEN                              ! control surface = model level
+         WRITE(clmxl,'(A10,I2,1X)') 'Levels 1 -', nn_ctls_trc
+      ENDIF
+
+      ! II.1 Define frequency of output and means
+      ! -----------------------------------------
+      IF( ln_mskland )   THEN   ;   clop = "only(x)"   ! put 1.e+20 on land (very expensive!!)
+      ELSE                      ;   clop = "x"         ! no use of the mask value (require less cp time)
+      ENDIF
+#  if defined key_diainstant
+      IF( .NOT. ln_trdmxl_trc_instant ) THEN
+         STOP 'trd_mxl_trc : this was never checked. Comment this line to proceed...'
+      ENDIF
+      zsto = nn_trd_trc * rdt
+      clop = "inst("//TRIM(clop)//")"
+#  else
+      IF( ln_trdmxl_trc_instant ) THEN
+         zsto = rdt                                               ! inst. diags : we use IOIPSL time averaging
+      ELSE
+         zsto = nn_trd_trc * rdt                                    ! mean  diags : we DO NOT use any IOIPSL time averaging
+      ENDIF
+      clop = "ave("//TRIM(clop)//")"
+#  endif
+      zout = nn_trd_trc * rdt
+      iiter = ( nittrc000 - 1 ) / nn_dttrc
+
+      IF(lwp) WRITE (numout,*) '                netCDF initialization'
+
+      ! II.2 Compute julian date from starting date of the run
+      ! ------------------------------------------------------
+      CALL ymds2ju( nyear, nmonth, nday, rdt, zjulian )
+      zjulian = zjulian - adatrj   !   set calendar origin to the beginning of the experiment
+      IF(lwp) WRITE(numout,*)' '  
+      IF(lwp) WRITE(numout,*)' Date 0 used :', nittrc000               &
+           &   ,' YEAR ', nyear, ' MONTH ', nmonth,' DAY ', nday       &
+           &   ,'Julian day : ', zjulian
+
+      ! II.3 Define the T grid trend file (nidtrd)
+      ! ------------------------------------------
+
+      !-- Define long and short names for the NetCDF output variables
+      !       ==> choose them according to trdmxl_trc_oce.F90 <==
+
+      ctrd_trc(jpmxl_trc_xad    ,1) = " Zonal advection"                 ;   ctrd_trc(jpmxl_trc_xad    ,2) = "_xad"
+      ctrd_trc(jpmxl_trc_yad    ,1) = " Meridional advection"            ;   ctrd_trc(jpmxl_trc_yad    ,2) = "_yad"
+      ctrd_trc(jpmxl_trc_zad    ,1) = " Vertical advection"              ;   ctrd_trc(jpmxl_trc_zad    ,2) = "_zad"
+      ctrd_trc(jpmxl_trc_ldf    ,1) = " Lateral diffusion"               ;   ctrd_trc(jpmxl_trc_ldf    ,2) = "_ldf"
+      ctrd_trc(jpmxl_trc_zdf    ,1) = " Vertical diff. (Kz)"             ;   ctrd_trc(jpmxl_trc_zdf    ,2) = "_zdf"
+      ctrd_trc(jpmxl_trc_bbl    ,1) = " Adv/diff. Bottom boundary layer" ;   ctrd_trc(jpmxl_trc_bbl    ,2) = "_bbl"
+      ctrd_trc(jpmxl_trc_dmp    ,1) = " Tracer damping"                  ;   ctrd_trc(jpmxl_trc_dmp    ,2) = "_dmp"
+      ctrd_trc(jpmxl_trc_sbc    ,1) = " Surface boundary cond."          ;   ctrd_trc(jpmxl_trc_sbc    ,2) = "_sbc"
+      ctrd_trc(jpmxl_trc_sms,    1) = " Sources minus sinks"             ;   ctrd_trc(jpmxl_trc_sms    ,2) = "_sms"
+      ctrd_trc(jpmxl_trc_radb   ,1) = " Correct negative concentrations" ;   ctrd_trc(jpmxl_trc_radb   ,2) = "_radb"
+      ctrd_trc(jpmxl_trc_radn   ,1) = " Correct negative concentrations" ;   ctrd_trc(jpmxl_trc_radn   ,2) = "_radn"
+      ctrd_trc(jpmxl_trc_atf    ,1) = " Asselin time filter"             ;   ctrd_trc(jpmxl_trc_atf    ,2) = "_atf"
+
+      DO jn = 1, jptra      
+      !-- Create a NetCDF file and enter the define mode 
+         IF( ln_trdtrc(jn) ) THEN
+            csuff="ML_"//ctrcnm(jn)
+            CALL dia_nam( clhstnam, nn_trd_trc, csuff )
+            CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,                                            &
+               &        1, jpi, 1, jpj, iiter, zjulian, rdt, nh_t(jn), nidtrd(jn), domain_id=nidom, snc4chunks=snc4set )
+      
+            !-- Define the ML depth variable
+            CALL histdef(nidtrd(jn), "mxl_depth", clmxl//" Mixed Layer Depth", "m",                        &
+               &        jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zsto, zout )
+
+         ENDIF
+      END DO
+
+#if defined key_pisces_reduced
+          !-- Create a NetCDF file and enter the define mode
+          CALL dia_nam( clhstnam, nn_trd_trc, 'trdbio' )
+          CALL histbeg( clhstnam, jpi, glamt, jpj, gphit,                                            &
+             &             1, jpi, 1, jpj, iiter, zjulian, rdt, nh_tb, nidtrdbio, domain_id=nidom, snc4chunks=snc4set )
+#endif
+
+      !-- Define physical units
+      IF( rn_ucf_trc == 1. ) THEN
+         cltrcu = "(mmole-N/m3)/sec"                              ! all passive tracers have the same unit 
+      ELSEIF ( rn_ucf_trc == 3600.*24.) THEN                         ! ??? trop long : seulement (mmole-N/m3)
+         cltrcu = "(mmole-N/m3)/day"                              ! ??? apparait dans les sorties netcdf 
+      ELSE
+         cltrcu = "unknown?"
+      ENDIF
+
+      !-- Define miscellaneous passive tracer mixed-layer variables 
+      IF( jpltrd_trc /= jpmxl_trc_atf .OR.  jpltrd_trc - 1 /= jpmxl_trc_radb ) THEN
+         STOP 'Error : jpltrd_trc /= jpmxl_trc_atf .OR.  jpltrd_trc - 1 /= jpmxl_trc_radb'  ! see below
+      ENDIF
+
+      DO jn = 1, jptra
+         !
+         IF( ln_trdtrc(jn) ) THEN
+            clvar = trim(ctrcnm(jn))//"ml"                           ! e.g. detml, zooml, no3ml, etc.
+            CALL histdef(nidtrd(jn), trim(clvar),           clmxl//" "//trim(ctrcnm(jn))//" Mixed Layer ",                         &
+              & "mmole-N/m3", jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zsto, zout )           
+            CALL histdef(nidtrd(jn), trim(clvar)//"_tot"  , clmxl//" "//trim(ctrcnm(jn))//" Total trend ",                         & 
+              &       cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zout, zout ) 
+            CALL histdef(nidtrd(jn), trim(clvar)//"_res"  , clmxl//" "//trim(ctrcnm(jn))//" dh/dt Entrainment (Resid.)",           & 
+              &       cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zout, zout )                   
+         
+            DO jl = 1, jpltrd_trc - 2                                ! <== only true if jpltrd_trc == jpmxl_trc_atf
+               CALL histdef(nidtrd(jn), trim(clvar)//trim(ctrd_trc(jl,2)), clmxl//" "//clvar//ctrd_trc(jl,1),                      & 
+                 &    cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zsto, zout ) ! IOIPSL: time mean
+            END DO                                                                         ! if zsto=rdt above
+         
+            CALL histdef(nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmxl_trc_radb,2)), clmxl//" "//clvar//ctrd_trc(jpmxl_trc_radb,1), & 
+              &       cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zout, zout ) ! IOIPSL: NO time mean
+         
+            CALL histdef(nidtrd(jn), trim(clvar)//trim(ctrd_trc(jpmxl_trc_atf,2)), clmxl//" "//clvar//ctrd_trc(jpmxl_trc_atf,1),   & 
+              &       cltrcu, jpi, jpj, nh_t(jn), 1  , 1, 1  , -99 , 32, clop, zout, zout ) ! IOIPSL: NO time mean
+         !
+         ENDIF
+      END DO
+
+#if defined key_pisces_reduced
+      DO jl = 1, jp_pisces_trd
+         CALL histdef(nidtrdbio, TRIM("ML_"//ctrd_bio(jl,2)), TRIM(clmxl//" ML_"//ctrd_bio(jl,1))   ,            &
+             &    cltrcu, jpi, jpj, nh_tb, 1  , 1, 1  , -99 , 32, clop, zsto, zout ) ! IOIPSL: time mean
+      END DO                                                                         ! if zsto=rdt above
+#endif
+
+      !-- Leave IOIPSL/NetCDF define mode
+      DO jn = 1, jptra
+         IF( ln_trdtrc(jn) )  CALL histend( nidtrd(jn), snc4set )
+      END DO
+
+#if defined key_pisces_reduced
+      !-- Leave IOIPSL/NetCDF define mode
+      CALL histend( nidtrdbio, snc4set )
+
+      IF(lwp) WRITE(numout,*)
+       IF(lwp) WRITE(numout,*) 'End of NetCDF Initialization for ML bio trends'
+#endif
+
+#endif        /* key_dimgout */
+   END SUBROUTINE trd_mxl_trc_init
+
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :                                       Empty module
+   !!----------------------------------------------------------------------
+CONTAINS
+   SUBROUTINE trd_mxl_trc( kt )                                   ! Empty routine
+      INTEGER, INTENT( in) ::   kt
+      WRITE(*,*) 'trd_mxl_trc: You should not have seen this print! error?', kt
+   END SUBROUTINE trd_mxl_trc
+   SUBROUTINE trd_mxl_bio( kt )
+      INTEGER, INTENT( in) ::   kt
+      WRITE(*,*) 'trd_mxl_bio: You should not have seen this print! error?', kt
+   END SUBROUTINE trd_mxl_bio
+   SUBROUTINE trd_mxl_trc_zint( ptrc_trdmxl, ktrd, ctype, kjn )
+      INTEGER               , INTENT( in ) ::  ktrd, kjn              ! ocean trend index and passive tracer rank
+      CHARACTER(len=2)      , INTENT( in ) ::  ctype                  ! surface/bottom (2D) or interior (3D) physics
+      REAL, DIMENSION(:,:,:), INTENT( in ) ::  ptrc_trdmxl            ! passive trc trend
+      WRITE(*,*) 'trd_mxl_trc_zint: You should not have seen this print! error?', ptrc_trdmxl(1,1,1)
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', ctype
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', ktrd
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kjn
+   END SUBROUTINE trd_mxl_trc_zint
+   SUBROUTINE trd_mxl_trc_init                                    ! Empty routine
+      WRITE(*,*) 'trd_mxl_trc_init: You should not have seen this print! error?'
+   END SUBROUTINE trd_mxl_trc_init
+#endif
+
+   !!======================================================================
+END MODULE trdmxl_trc
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmxl_trc_rst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmxl_trc_rst.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdmxl_trc_rst.F90	(revision 5075)
@@ -0,0 +1,220 @@
+MODULE trdmxl_trc_rst
+   !!======================================================================
+   !!                       ***  MODULE  trdmxl_rst  ***
+   !! Ocean dynamic :  Input/Output files for restart on mixed-layer diagnostics
+   !!======================================================================
+   !! History :  9.0  ! 07-03 (C. Deltel) Original code
+   !!----------------------------------------------------------------------
+  
+#if defined key_top && defined key_trdmxl_trc
+   !!----------------------------------------------------------------------
+   USE in_out_manager  ! I/O manager
+   USE iom             ! I/O module
+   USE trc             ! for nn_dttrc ctrcnm
+   USE trdmxl_trc_oce  ! for lk_trdmxl_trc
+
+   IMPLICIT NONE
+   PRIVATE
+  
+   PUBLIC   trd_mxl_trc_rst_read    ! routine called by trd_mxl_init
+   PUBLIC   trd_mxl_trc_rst_write   ! routine called by step.F90
+  
+   INTEGER ::   nummldw_trc               ! logical unit for mld restart
+   !!---------------------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Header: /home/opalod/NEMOCVSROOT/NEMO/OPA_SRC/TRD/trdmxl_rst.F90,v 1.6 2006/11/14 09:46:13 opalod Exp $ 
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!---------------------------------------------------------------------------------
+  
+CONTAINS
+  
+
+    SUBROUTINE trd_mxl_trc_rst_write( kt )
+      !!--------------------------------------------------------------------------------
+      !!                  ***  SUBROUTINE trd_mxl_rst_wri  ***
+      !!                
+      !! ** Purpose :   Write mixed-layer diagnostics restart fields.
+      !!--------------------------------------------------------------------------------
+      INTEGER, INTENT( in ) ::   kt     ! ocean time-step index
+      !
+      CHARACTER(LEN=20)   ::   clkt     ! ocean time-step deine as a character
+      CHARACTER(LEN=50)   ::   clname   ! ice output restart file name
+      CHARACTER (len=35) :: charout
+      INTEGER :: jl,  jk, jn               ! loop indice
+      !!--------------------------------------------------------------------------------
+
+      IF( kt == nitrst - nn_dttrc .OR. nitend - nit000 + 1 < 2 * nn_dttrc ) THEN ! idem trcrst.F90
+         IF( nitrst > 1.0e9 ) THEN
+            WRITE(clkt,*) nitrst
+         ELSE
+           WRITE(clkt,'(i8.8)') nitrst
+         ENDIF
+         clname = TRIM(cexper)//"_"//TRIM(ADJUSTL(clkt))//"_"//TRIM(cn_trdrst_trc_out)
+         IF(lwp) WRITE(numout,*) '             open ocean restart_mld_trc NetCDF  '//clname
+         CALL iom_open( clname, nummldw_trc, ldwrt = .TRUE., kiolib = jprstlib )
+      ENDIF
+
+      IF( kt == nitend .AND. lk_trdmxl_trc ) THEN
+
+         IF( kt == nitend .AND. lwp ) THEN
+            WRITE(numout,*)
+            WRITE(numout,*) 'trdmxl_trc_rst: output for ML diags. restart, with trd_mxl_trc_rst_write routine'
+            WRITE(numout,*) '~~~~~~~~~~~~~~'
+            WRITE(numout,*)
+         ENDIF
+
+         IF( ln_trdmxl_trc_instant ) THEN 
+            !
+            DO jn = 1, jptra
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlbb_trc_'  //ctrcnm(jn), tmlbb_trc  (:,:,jn) )
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlbn_trc_'  //ctrcnm(jn), tmlbn_trc  (:,:,jn) )
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlatfb_trc_'//ctrcnm(jn), tmlatfb_trc(:,:,jn) )
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlradb_trc_'//ctrcnm(jn), tmlradb_trc(:,:,jn) )
+            END DO
+            !
+         ELSE
+            !
+            CALL iom_rstput( kt, nitrst, nummldw_trc, 'rmldbn_trc', rmldbn_trc )  ! 2D x 1
+            
+            !                                                          ! ===========
+            DO jn = 1, jptra                                           ! tracer loop
+               !                                                       ! ===========
+
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlatfb_trc_' //ctrcnm(jn), tmlatfb_trc (:,:,jn) ) ! 2D x jptra
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlbb_trc_'   //ctrcnm(jn), tmlbb_trc   (:,:,jn) ) ! 2D x jptra
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlradb_trc_' //ctrcnm(jn), tmlradb_trc (:,:,jn) ) ! 2D x jptra
+
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmlbn_trc_'   //ctrcnm(jn), tmlbn_trc   (:,:,jn) ) ! 2D x jptra
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tml_sumb_trc_'//ctrcnm(jn), tml_sumb_trc(:,:,jn) ) ! 2D x jptra
+               
+               DO jk = 1, jpltrd_trc
+                  IF( jk < 10 )   THEN
+                     WRITE(charout,FMT="('tmltrd_csum_ub_trc_', A3, '_', I1)") ctrcnm(jn), jk
+                  ELSE
+                     WRITE(charout,FMT="('tmltrd_csum_ub_trc_', A3, '_', I2)") ctrcnm(jn), jk
+                  ENDIF
+                  CALL iom_rstput( kt, nitrst, nummldw_trc, charout, tmltrd_csum_ub_trc(:,:,jk,jn) )
+               END DO
+               
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmltrd_atf_sumb_trc_'//ctrcnm(jn) , &
+                    &           tmltrd_atf_sumb_trc(:,:,jn) ) ! 2D x jptra
+
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmltrd_rad_sumb_trc_'//ctrcnm(jn) , &
+                    &           tmltrd_rad_sumb_trc(:,:,jn) ) ! 2D x jptra
+               !                                                       ! ===========
+            END DO                                                     ! tracer loop
+            !                                                          ! ===========
+#if defined key_pisces_reduced
+            DO jl = 1, jp_pisces_trd
+               CALL iom_rstput( kt, nitrst, nummldw_trc, 'tmltrd_csum_ub_bio'//ctrd_bio(jl,2), tmltrd_csum_ub_bio(:,:,jl) )
+            ENDDO
+#endif
+
+         ENDIF
+         
+         CALL iom_close( nummldw_trc )
+         lrst_trc = .TRUE.
+
+      ENDIF
+
+    END SUBROUTINE trd_mxl_trc_rst_write
+
+
+    SUBROUTINE trd_mxl_trc_rst_read
+      !!----------------------------------------------------------------------------
+      !!                   ***  SUBROUTINE trd_mxl_rst_lec  ***
+      !!                   
+      !! ** Purpose :   Read file for mixed-layer diagnostics restart.
+      !!----------------------------------------------------------------------------
+      INTEGER  ::  inum       ! temporary logical unit
+      !
+      CHARACTER (len=35) :: charout
+      INTEGER ::  jk, jn, jl     ! loop indice
+      INTEGER ::  jlibalt = jprstlib
+      LOGICAL ::  llok
+      !!-----------------------------------------------------------------------------
+      
+      IF(lwp)  THEN
+         WRITE(numout,*)
+         WRITE(numout,*) ' trd_mxl_trc_rst_read : read the NetCDF MLD restart file'
+         WRITE(numout,*) ' ~~~~~~~~~~~~~~~~~~~~'
+      ENDIF
+      
+      IF ( jprstlib == jprstdimg ) THEN
+        ! eventually read netcdf file (monobloc)  for restarting on different number of processors
+        ! if {cn_trdrst_trc_in}.nc exists, then set jlibalt to jpnf90
+        INQUIRE( FILE = TRIM(cn_trdrst_trc_in)//'.nc', EXIST = llok )
+        IF ( llok ) THEN ; jlibalt = jpnf90  ; ELSE ; jlibalt = jprstlib ; ENDIF
+      ENDIF
+
+      CALL iom_open( cn_trdrst_trc_in, inum, kiolib = jlibalt ) 
+      
+      IF( ln_trdmxl_trc_instant ) THEN 
+         
+         DO jn = 1, jptra
+            CALL iom_get( inum, jpdom_autoglo, 'tmlbb_trc_'  //ctrcnm(jn), tmlbb_trc  (:,:,jn) )
+            CALL iom_get( inum, jpdom_autoglo, 'tmlbn_trc_'  //ctrcnm(jn), tmlbn_trc  (:,:,jn) )
+            CALL iom_get( inum, jpdom_autoglo, 'tmlatfb_trc_'//ctrcnm(jn), tmlatfb_trc(:,:,jn) )
+            CALL iom_get( inum, jpdom_autoglo, 'tmlradb_trc_'//ctrcnm(jn), tmlradb_trc(:,:,jn) )
+         END DO
+         
+      ELSE
+         CALL iom_get( inum, jpdom_autoglo, 'rmldbn_trc', rmldbn_trc ) ! needed for rmld_sum
+         
+         !                                                          ! ===========
+         DO jn = 1, jptra                                           ! tracer loop
+            !                                                       ! ===========
+            CALL iom_get( inum, jpdom_autoglo, 'tmlatfb_trc_' //ctrcnm(jn), tmlatfb_trc(:,:,jn) )
+            CALL iom_get( inum, jpdom_autoglo, 'tmlbb_trc_'   //ctrcnm(jn), tmlbb_trc  (:,:,jn) )
+            CALL iom_get( inum, jpdom_autoglo, 'tmlradb_trc_' //ctrcnm(jn), tmlradb_trc(:,:,jn) )
+
+            CALL iom_get( inum, jpdom_autoglo, 'tmlbn_trc_'   //ctrcnm(jn), tmlbn_trc   (:,:,jn) ) ! needed for tml_sum
+            CALL iom_get( inum, jpdom_autoglo, 'tml_sumb_trc_'//ctrcnm(jn), tml_sumb_trc(:,:,jn) )
+            
+            DO jk = 1, jpltrd_trc
+               IF( jk < 10 )   THEN
+                  WRITE(charout,FMT="('tmltrd_csum_ub_trc_', A3, '_', I1)") ctrcnm(jn), jk
+               ELSE
+                  WRITE(charout,FMT="('tmltrd_csum_ub_trc_', A3, '_', I2)") ctrcnm(jn), jk
+               ENDIF
+               CALL iom_get( inum, jpdom_autoglo, charout, tmltrd_csum_ub_trc(:,:,jk,jn) )
+            END DO
+            
+            CALL iom_get( inum, jpdom_autoglo, 'tmltrd_atf_sumb_trc_'//ctrcnm(jn) , &
+                 &        tmltrd_atf_sumb_trc(:,:,jn) )
+
+            CALL iom_get( inum, jpdom_autoglo, 'tmltrd_rad_sumb_trc_'//ctrcnm(jn) , &
+                 &        tmltrd_rad_sumb_trc(:,:,jn) )
+            !                                                       ! ===========
+         END DO                                                     ! tracer loop
+         !                                                          ! ===========
+
+#if defined key_pisces_reduced
+         DO jl = 1, jp_pisces_trd
+            CALL iom_get( inum, jpdom_autoglo, 'tmltrd_csum_ub_bio'//ctrd_bio(jl,2), tmltrd_csum_ub_bio(:,:,jl) )
+         ENDDO
+#endif
+         
+         CALL iom_close( inum )
+      ENDIF
+      
+    END SUBROUTINE trd_mxl_trc_rst_read
+  
+#else
+  !!=================================================================================
+  !!                       ***  MODULE  trdmxl_rst  ***
+  !! Ocean dynamic :  Input/Output files for restart on mixed-layer diagnostics
+  !!=================================================================================
+CONTAINS
+  SUBROUTINE trd_mxl_trc_rst_opn( kt )
+    WRITE(*,*) 'trd_mxl_trc_rst_opn: You should not have seen this print! error?', kt
+  END SUBROUTINE trd_mxl_trc_rst_opn
+  SUBROUTINE trd_mxl_trc_rst_write( kt )           !  No ML diags ==> empty routine
+    WRITE(*,*) 'trd_mxl_trc_rst_wri: You should not have seen this print! error?', kt
+  END SUBROUTINE trd_mxl_trc_rst_write
+  SUBROUTINE trd_mxl_trc_rst_read                  !  No ML Diags ==> empty routine
+  END SUBROUTINE trd_mxl_trc_rst_read
+#endif
+
+  !!=================================================================================
+END MODULE trdmxl_trc_rst
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdtrc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdtrc.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdtrc.F90	(revision 5075)
@@ -0,0 +1,158 @@
+MODULE trdtrc
+   !!======================================================================
+   !!                       ***  MODULE  trdtrc  ***
+   !! Ocean diagnostics:  mixed layer passive tracer trends 
+   !!======================================================================
+   !! History :  3.0  !  2010-07  (C. Ethe)  Original code (from trdtrc.F90)
+   !!----------------------------------------------------------------------
+#if   defined key_top && ( defined key_trdmxl_trc   ||   defined key_trdtrc )
+   !!----------------------------------------------------------------------
+   !!   'key_trdmxl_trc'                  mixed layer trend diagnostics
+   !!   'key_trdtrc'                      3D trend diagnostics
+   !!----------------------------------------------------------------------
+   !!   trdtrc      : passive tracer trends 
+   !!----------------------------------------------------------------------
+   USE trc               ! tracer definitions (trn, trb, tra, etc.)
+   USE trcnam_trp
+   USE trd_oce
+   USE trdtrc_oce       ! definition of main arrays used for trends computations
+   USE trdmxl_trc        ! Mixed layer trends diag.
+   USE iom               ! I/O library
+
+   IMPLICIT NONE
+   PRIVATE
+
+   INTERFACE trd_trc
+      MODULE PROCEDURE trd_trc_trp, trd_trc_bio
+   END INTERFACE
+
+   PUBLIC trd_trc
+
+   !! * Substitutions
+#  include "top_substitute.h90"
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Header:  $ 
+   !! Software governed by the CeCILL licence (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+
+CONTAINS
+
+   SUBROUTINE trd_trc_trp( ptrtrd, kjn, ktrd, kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_trc  ***
+      !!----------------------------------------------------------------------
+      INTEGER, INTENT( in )  ::   kt                                  ! time step
+      INTEGER, INTENT( in )  ::   kjn                                 ! tracer index
+      INTEGER, INTENT( in )  ::   ktrd                                ! tracer trend index
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( inout )  ::   ptrtrd  ! Temperature or U trend
+      CHARACTER (len=20) :: cltra
+      !!----------------------------------------------------------------------
+
+      IF( kt == nittrc000 ) THEN
+!         IF(lwp)WRITE(numout,*)
+!         IF(lwp)WRITE(numout,*) 'trd_trc:'
+!         IF(lwp)WRITE(numout,*) '~~~~~~~~~~~~'
+      ENDIF
+
+      !>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
+      ! Mixed layer trends for passive tracers
+      !<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+#if defined key_trdmxl_trc  
+      IF( lk_trdmxl_trc .AND. ln_trdtrc( kjn ) ) THEN
+         !
+         SELECT CASE ( ktrd )
+         CASE ( jptra_xad     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_xad, '3D', kjn )
+         CASE ( jptra_yad     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_yad, '3D', kjn )
+         CASE ( jptra_zad     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_zad, '3D', kjn )
+         CASE ( jptra_ldf     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_ldf, '3D', kjn )
+         CASE ( jptra_bbl     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_bbl, '3D', kjn )
+         CASE ( jptra_zdf     )
+            IF( ln_trcldf_iso ) THEN
+               CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_ldf, '3D', kjn )
+            ELSE
+               CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_zdf, '3D', kjn )
+            ENDIF
+         CASE ( jptra_dmp     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_dmp , '3D', kjn )
+         CASE ( jptra_nsr     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_sbc , '2D', kjn )
+         CASE ( jptra_sms     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_sms , '3D', kjn )
+         CASE ( jptra_radb    )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_radb, '3D', kjn )
+         CASE ( jptra_radn    )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_radn, '3D', kjn )
+         CASE ( jptra_atf     )   ;   CALL trd_mxl_trc_zint( ptrtrd, jpmxl_trc_atf , '3D', kjn )
+         END SELECT
+         !
+      END IF
+#endif
+
+      IF( lk_trdtrc .AND. ln_trdtrc( kjn ) ) THEN
+         !
+         SELECT CASE( ktrd )
+         CASE( jptra_xad  )       ;    WRITE (cltra,'("XAD_",4a)')
+         CASE( jptra_yad  )       ;    WRITE (cltra,'("YAD_",4a)')
+         CASE( jptra_zad  )       ;    WRITE (cltra,'("ZAD_",4a)')
+         CASE( jptra_ldf  )       ;    WRITE (cltra,'("LDF_",4a)')
+         CASE( jptra_bbl  )       ;    WRITE (cltra,'("BBL_",4a)')
+         CASE( jptra_nsr  )       ;    WRITE (cltra,'("FOR_",4a)')
+         CASE( jptra_zdf  )       ;    WRITE (cltra,'("ZDF_",4a)')
+         CASE( jptra_dmp  )       ;    WRITE (cltra,'("DMP_",4a)')
+         CASE( jptra_sms  )       ;    WRITE (cltra,'("SMS_",4a)')
+         CASE( jptra_atf  )       ;    WRITE (cltra,'("ATF_",4a)')
+         CASE( jptra_radb )       ;    WRITE (cltra,'("RDB_",4a)')
+         CASE( jptra_radn )       ;    WRITE (cltra,'("RDN_",4a)')
+         END SELECT
+                                          cltra = TRIM(cltra)//TRIM(ctrcnm(kjn))
+                                          CALL iom_put( cltra,  ptrtrd(:,:,:) )
+         !
+      END IF
+
+   END SUBROUTINE trd_trc_trp
+
+   SUBROUTINE trd_trc_bio( ptrbio, ktrd, kt )
+      !!----------------------------------------------------------------------
+      !!                  ***  ROUTINE trd_bio  ***
+      !!----------------------------------------------------------------------
+
+      INTEGER, INTENT( in )  ::   kt                                  ! time step
+      INTEGER, INTENT( in )  ::   ktrd                                ! bio trend index
+      REAL(wp), DIMENSION(jpi,jpj,jpk), INTENT( inout )  ::   ptrbio  ! Bio trend
+      !!----------------------------------------------------------------------
+
+#if defined key_trdmxl_trc  
+      CALL trd_mxl_bio_zint( ptrbio, ktrd ) ! Verticaly integrated biological trends
+#endif
+
+   END SUBROUTINE trd_trc_bio
+#else
+   !!----------------------------------------------------------------------
+   !!   Default option :                                       Empty module
+   !!----------------------------------------------------------------------
+
+   INTERFACE trd_trc
+      MODULE PROCEDURE trd_trc_trp, trd_trc_bio
+   END INTERFACE
+
+CONTAINS
+
+   SUBROUTINE trd_trc_trp( ptrtrd, kjn, ktrd, kt )
+      INTEGER               , INTENT( in )     ::   kt      ! time step
+      INTEGER               , INTENT( in )     ::   kjn     ! tracer index
+      INTEGER               , INTENT( in )     ::   ktrd    ! tracer trend index
+      REAL, DIMENSION(:,:,:), INTENT( inout )  ::   ptrtrd  ! Temperature or U trend
+      WRITE(*,*) 'trd_trc_trp : You should not have seen this print! error?', ptrtrd(1,1,1)
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kjn
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', ktrd
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kt
+   END SUBROUTINE trd_trc_trp
+
+   SUBROUTINE trd_trc_bio( ptrbio, ktrd, kt )
+      INTEGER               , INTENT( in )     ::   kt      ! time step
+      INTEGER               , INTENT( in )     ::   ktrd    ! tracer trend index
+      REAL, DIMENSION(:,:,:), INTENT( inout )  ::   ptrbio  ! Temperature or U trend
+      WRITE(*,*) 'trd_trc_trp : You should not have seen this print! error?', ptrbio(1,1,1)
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', ktrd
+      WRITE(*,*) '  "      "      : You should not have seen this print! error?', kt
+   END SUBROUTINE trd_trc_bio
+
+#endif
+   !!======================================================================
+END MODULE trdtrc
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdtrc_oce.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdtrc_oce.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/TRP/trdtrc_oce.F90	(revision 5075)
@@ -0,0 +1,180 @@
+MODULE trdtrc_oce
+   !!======================================================================
+   !!                   ***  MODULE trdtrc_oce  ***
+   !! Ocean trends :   set tracer and momentum trend variables
+   !!======================================================================
+#if defined key_top   ||   defined key_esopa
+   !!----------------------------------------------------------------------
+   !!   'key_top'                                                TOP models
+   !!----------------------------------------------------------------------
+   USE par_oce       ! ocean parameters
+   USE par_trc       ! passive tracers parameters
+
+   IMPLICIT NONE
+   PUBLIC
+
+   !                                         !!* Namelist namtoptrd:  diagnostics on passive tracers trends
+   INTEGER  ::    nn_trd_trc                  !: time step frequency dynamics and tracers trends
+   INTEGER  ::    nn_ctls_trc                 !: control surface type for trends vertical integration
+   REAL(wp) ::    rn_ucf_trc                  !: unit conversion factor (for netCDF trends outputs)
+   LOGICAL  ::    ln_trdmxl_trc_instant       !: flag to diagnose inst./mean ML trc trends
+   LOGICAL  ::    ln_trdmxl_trc_restart       !: flag to restart mixed-layer trc diagnostics
+   CHARACTER(len=50) ::  cn_trdrst_trc_in     !: suffix of pass. tracer restart name (input)
+   CHARACTER(len=50) ::  cn_trdrst_trc_out    !: suffix of pass. tracer restart name (output)
+   LOGICAL, DIMENSION(jptra) ::   ln_trdtrc   !: large trends diagnostic to write or not (namelist)
+
+# if defined key_trdtrc && defined key_iomput
+   LOGICAL, PARAMETER ::   lk_trdtrc = .TRUE. 
+# else
+   LOGICAL, PARAMETER ::   lk_trdtrc = .FALSE.   !: ML trend flag
+# endif
+
+# if defined key_trdmxl_trc   ||   defined key_esopa
+   !!----------------------------------------------------------------------
+   !!   'key_trdmxl_trc'                     mixed layer trends diagnostics
+   !!----------------------------------------------------------------------
+
+   LOGICAL, PARAMETER ::   lk_trdmxl_trc = .TRUE.    !: ML trend flag
+
+   INTEGER, PARAMETER ::            & !: mixed layer trends indices
+        jpmxl_trc_xad     =  1,     & !:     zonal       advection     
+        jpmxl_trc_yad     =  2,     & !:     meridonal   =========
+        jpmxl_trc_zad     =  3,     & !:     vertical    =========
+        jpmxl_trc_ldf     =  4,     & !:     lateral diffusion (geopot. or iso-neutral)
+        jpmxl_trc_zdf     =  5,     & !:     vertical diffusion (TKE)
+        jpmxl_trc_bbl     =  6,     & !:     bottom boundary layer (advective/diffusive)
+        jpmxl_trc_dmp     =  7,     & !:     internal restoring trend
+        jpmxl_trc_sbc     =  8,     & !:     forcing 
+        jpmxl_trc_sms     =  9,     & !:     sources minus sinks trend
+  !     jpmxl_trc_xxx     = xx,     & !:     add here any additional trend    (** AND UPDATE JPLTRD_TRC BELOW **)
+        jpmxl_trc_radn    = 10,     & !:     corr. trn<0 in trcrad
+        jpmxl_trc_radb    = 11,     & !:     corr. trb<0 in trcrad (like atf) (** MUST BE BEFORE THE LAST ONE **)
+        jpmxl_trc_atf     = 12        !:     asselin trend                    (** MUST BE    THE      LAST ONE**)
+
+   !! Trends diagnostics parameters
+   !!---------------------------------------------------------------------
+   INTEGER, PARAMETER :: jpltrd_trc = 12    !: number of mixed-layer trends arrays
+      
+   INTEGER            :: jpktrd_trc         !: max level for mixed-layer trends diag.
+
+   !! Arrays used for diagnosing mixed-layer trends 
+   !!---------------------------------------------------------------------
+   CHARACTER(LEN=80) :: clname_trc, ctrd_trc(jpltrd_trc+1,2)
+
+   INTEGER, ALLOCATABLE, SAVE, DIMENSION(:,:) ::   &
+      nmld_trc       , &                            !: mixed layer depth indexes 
+      nbol_trc                                   !: mixed-layer depth indexes when read from file
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  wkx_trc  !:
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::  rmld_trc     !: ML depth (m) corresponding to nmld_trc
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::  rmld_sum_trc !: needed to compute the leap-frog time mean of ML depth
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:) ::  rmldbn_trc   !: idem
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  &
+      tml_trc    ,                        &      !: \ "now" mixed layer temperature/salinity
+      tmlb_trc   ,                        &      !: /  and associated "before" fields
+      tmlbb_trc  ,                        &      !: \  idem, but valid at the 1rst time step of the
+      tmlbn_trc  ,                        &      !: /  current analysis window
+      tml_sum_trc,                        &      !: mixed layer T, summed over the current analysis period
+      tml_sumb_trc,                       &      !: idem, but from the previous analysis period
+      tmltrd_atf_sumb_trc,                &      !: Asselin trends, summed over the previous analysis period
+      tmltrd_rad_sumb_trc                        !: trends due to trb correction in trcrad.F90, summed over the
+                                                 !:     previous analysis period
+                                                 
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  &      
+      tmlatfb_trc, tmlatfn_trc ,          &      !: "before" Asselin contrib. at beginning of the averaging
+                                                 !:     period (i.e. last contrib. from previous such period)
+                                                 !:     and "now" Asselin contrib. to the ML trc. trends
+      tmlatfm_trc,                        &      !: accumulator for Asselin trends (needed for storage only)
+      tmlradb_trc, tmlradn_trc ,          &      !: similar to Asselin above, but for the trend due to trb
+                                                 !:     correction in trcrad.F90
+      tmlradm_trc                                !: accumulator for the previous trcrad trend
+
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:,:) ::  &
+      tmltrd_trc,                         &      !: \ physical contributions to the total trend (for T/S),
+                                                 !: / cumulated over the current analysis window
+      tmltrd_sum_trc,                     &      !: sum of these trends over the analysis period
+      tmltrd_csum_ln_trc,                 &      !: now cumulated sum of trends over the "lower triangle"
+      tmltrd_csum_ub_trc                         !: before (prev. analysis period) cumulated sum over the
+                                                 !: upper triangle
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  &
+      tmltrdm_trc                                !: total cumulative trends over the analysis window
+
+# else
+   LOGICAL, PARAMETER ::   lk_trdmxl_trc = .FALSE.   !: ML trend flag
+# endif
+
+# if defined key_pisces_reduced
+   CHARACTER(LEN=80) :: clname_bio, ctrd_bio(jpdiabio,2)
+   REAL(wp), ALLOCATABLE, SAVE, DIMENSION(:,:,:) ::  &
+      tmltrd_bio,                         &      !: \ biological contributions to the total trend ,
+                                                 !: / cumulated over the current analysis window
+      tmltrd_sum_bio,                     &      !: sum of these trends over the analysis period
+      tmltrd_csum_ln_bio,                 &      !: now cumulated sum of trends over the "lower triangle"
+      tmltrd_csum_ub_bio                         !: before (prev. analysis period) cumulated sum over the
+                                                 !: upper triangle
+#endif
+   !!----------------------------------------------------------------------
+   !! NEMO/TOP 3.3 , NEMO Consortium (2010)
+   !! $Header: /home/opalod/NEMOCVSROOT/NEMO/OPA_SRC/TRD/trdmxl_oce.F90,v 1.2 2005/03/27 18:35:23 opalod Exp $ 
+   !! Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+   !!----------------------------------------------------------------------
+CONTAINS
+
+   INTEGER FUNCTION trd_trc_oce_alloc()
+      !!----------------------------------------------------------------------
+      !!         *** ROUTINE trd_trc_oce_alloc ***
+      !!----------------------------------------------------------------------
+      USE lib_mpp, ONLY: ctl_warn
+      INTEGER :: ierr(2)
+      !!----------------------------------------------------------------------
+      ierr(:) = 0
+      !
+# if defined key_trdmxl_trc
+      ALLOCATE(nmld_trc(jpi,jpj),          nbol_trc(jpi,jpj),           &
+               wkx_trc(jpi,jpj,jpk),       rmld_trc(jpi,jpj),           &
+               rmld_sum_trc(jpi,jpj),      rmldbn_trc(jpi,jpj),         &
+               tml_trc(jpi,jpj,jptra),     tmlb_trc(jpi,jpj,jptra),     &
+               tmlbb_trc(jpi,jpj,jptra),   tmlbn_trc(jpi,jpj,jptra),    &
+               tml_sum_trc(jpi,jpj,jptra), tml_sumb_trc(jpi,jpj,jptra), &
+               tmltrd_atf_sumb_trc(jpi,jpj,jptra),                      &
+               tmltrd_rad_sumb_trc(jpi,jpj,jptra),                      &
+               !
+               tmlatfb_trc(jpi,jpj,jptra), tmlatfn_trc(jpi,jpj,jptra),  &
+               tmlatfm_trc(jpi,jpj,jptra), tmlradb_trc(jpi,jpj,jptra),  &
+               tmlradn_trc(jpi,jpj,jptra), tmlradm_trc(jpi,jpj,jptra),  &
+               !
+               tmltrd_trc(jpi,jpj,jpltrd_trc,jptra)         , &
+               tmltrd_sum_trc(jpi,jpj,jpltrd_trc,jptra)     , &
+               tmltrd_csum_ln_trc(jpi,jpj,jpltrd_trc,jptra) , &
+               tmltrd_csum_ub_trc(jpi,jpj,jpltrd_trc,jptra) , &
+               !
+               tmltrdm_trc(jpi,jpj,jptra)                   , STAT=ierr(1) )
+#endif
+      !
+# if defined key_pisces_reduced
+      ALLOCATE( tmltrd_bio        (jpi,jpj,jpdiabio) ,     &
+         &      tmltrd_sum_bio    (jpi,jpj,jpdiabio) ,     &
+         &      tmltrd_csum_ln_bio(jpi,jpj,jpdiabio) ,     &
+         &      tmltrd_csum_ub_bio(jpi,jpj,jpdiabio) , STAT=ierr(2) )
+# endif
+      !
+      trd_trc_oce_alloc = MAXVAL(ierr)
+      !
+      IF( trd_trc_oce_alloc /= 0 )   CALL ctl_warn('trd_trc_oce_alloc: failed to allocate arrays')
+      !
+# if defined key_trdmxl_trc
+      jpktrd_trc = jpk      ! Initialise what used to be a parameter - max level for mixed-layer trends diag.
+# endif
+      !
+   END FUNCTION trd_trc_oce_alloc
+
+#else
+   !!----------------------------------------------------------------------
+   !!  Empty module :                                     No passive tracer
+   !!----------------------------------------------------------------------
+#endif
+
+   !!======================================================================
+END MODULE trdtrc_oce
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/oce_trc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/oce_trc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/oce_trc.F90	(revision 5075)
@@ -66,4 +66,7 @@
    USE oce , ONLY :   rhop    =>    rhop    !: potential volumic mass (kg m-3) 
    USE oce , ONLY :   rhd     =>    rhd     !: in situ density anomalie rhd=(rho-rau0)/rau0 (no units)
+#if defined key_offline
+   USE oce , ONLY :   rab_n   =>    rab_n   !: local thermal/haline expension ratio at T-points
+#endif
    USE oce , ONLY :   hdivn   =>    hdivn   !: horizontal divergence (1/s)
    USE oce , ONLY :   rotn    =>    rotn    !: relative vorticity    [s-1]
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trc.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trc.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trc.F90	(revision 5075)
@@ -42,4 +42,6 @@
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)           ::  gtru           !: hor. gradient at u-points at bottom ocean level
    REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)           ::  gtrv           !: hor. gradient at v-points at bottom ocean level
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)           ::  gtrui          !: hor. gradient at u-points at top    ocean level
+   REAL(wp), PUBLIC, ALLOCATABLE, SAVE, DIMENSION(:,:,:)           ::  gtrvi          !: hor. gradient at v-points at top    ocean level
    
    !! passive tracers  (input and output)
@@ -183,5 +185,6 @@
       !
       ALLOCATE( trn(jpi,jpj,jpk,jptra), trb(jpi,jpj,jpk,jptra), tra(jpi,jpj,jpk,jptra),       &  
-         &      gtru(jpi,jpj,jpk)     , gtrv(jpi,jpj,jpk)                             ,       &
+         &      gtru (jpi,jpj,jptra)  , gtrv (jpi,jpj,jptra)                          ,       &
+         &      gtrui(jpi,jpj,jptra)  , gtrvi(jpi,jpj,jptra)                          ,       &
          &      cvol(jpi,jpj,jpk)     , rdttrc(jpk)           , trai(jptra)           ,       &
          &      ctrcnm(jptra)         , ctrcln(jptra)         , ctrcun(jptra)         ,       & 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcini.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcini.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcini.F90	(revision 5075)
@@ -143,7 +143,6 @@
  
       tra(:,:,:,:) = 0._wp
-      
       IF( ln_zps .AND. .NOT. lk_c1d )   &              ! Partial steps: before horizontal gradient of passive
-        &    CALL zps_hde( nit000, jptra, trn, gtru, gtrv )       ! tracers at the bottom ocean level
+        &    CALL zps_hde( nit000, jptra, trn, pgtu=gtru, pgtv=gtrv, sgtu=gtrui, sgtv=gtrvi )       ! tracers at the bottom ocean level
 
       !
@@ -192,7 +191,7 @@
       USE trcnxt        , ONLY:   trc_nxt_alloc
       USE trczdf        , ONLY:   trc_zdf_alloc
-      USE trdmod_trc_oce, ONLY:   trd_mod_trc_oce_alloc
-#if defined key_trdmld_trc 
-      USE trdmld_trc    , ONLY:   trd_mld_trc_alloc
+      USE trdtrc_oce    , ONLY:   trd_trc_oce_alloc
+#if defined key_trdmxl_trc 
+      USE trdmxl_trc    , ONLY:   trd_mxl_trc_alloc
 #endif
       !
@@ -204,7 +203,7 @@
       ierr = ierr + trc_nxt_alloc()
       ierr = ierr + trc_zdf_alloc()
-      ierr = ierr + trd_mod_trc_oce_alloc()
-#if defined key_trdmld_trc 
-      ierr = ierr + trd_mld_trc_alloc()
+      ierr = ierr + trd_trc_oce_alloc()
+#if defined key_trdmxl_trc 
+      ierr = ierr + trd_mxl_trc_alloc()
 #endif
       !
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcnam.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcnam.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcnam.F90	(revision 5075)
@@ -25,6 +25,6 @@
    USE trcnam_c14b       ! C14 SMS namelist
    USE trcnam_my_trc     ! MY_TRC SMS namelist
-   USE trdmod_oce       
-   USE trdmod_trc_oce
+   USE trd_oce       
+   USE trdtrc_oce
    USE iom               ! I/O manager
 
@@ -119,5 +119,5 @@
 
 
-#if defined key_trdmld_trc || defined key_trdtrc
+#if defined key_trdmxl_trc || defined key_trdtrc
 
          REWIND( numnat_ref )              ! Namelist namtrc_trd in reference namelist : Passive tracer trends
@@ -132,11 +132,11 @@
          IF(lwp) THEN
             WRITE(numout,*)
-            WRITE(numout,*) ' trd_mld_trc_init : read namelist namtrc_trd                    '
+            WRITE(numout,*) ' trd_mxl_trc_init : read namelist namtrc_trd                    '
             WRITE(numout,*) ' ~~~~~~~~~~~~~~~~                                               '
             WRITE(numout,*) '   * frequency of trends diagnostics   nn_trd_trc             = ', nn_trd_trc
             WRITE(numout,*) '   * control surface type              nn_ctls_trc            = ', nn_ctls_trc
-            WRITE(numout,*) '   * restart for ML diagnostics        ln_trdmld_trc_restart  = ', ln_trdmld_trc_restart
+            WRITE(numout,*) '   * restart for ML diagnostics        ln_trdmxl_trc_restart  = ', ln_trdmxl_trc_restart
             WRITE(numout,*) '   * flag to diagnose trends of                                 '
-            WRITE(numout,*) '     instantantaneous or mean ML T/S   ln_trdmld_trc_instant  = ', ln_trdmld_trc_instant
+            WRITE(numout,*) '     instantantaneous or mean ML T/S   ln_trdmxl_trc_instant  = ', ln_trdmxl_trc_instant
             WRITE(numout,*) '   * unit conversion factor            rn_ucf_trc             = ', rn_ucf_trc
             DO jn = 1, jptra
@@ -266,7 +266,7 @@
       !!---------------------------------------------------------------------
       INTEGER ::  ierr
-#if defined key_trdmld_trc  || defined key_trdtrc
+#if defined key_trdmxl_trc  || defined key_trdtrc
       NAMELIST/namtrc_trd/ nn_trd_trc, nn_ctls_trc, rn_ucf_trc, &
-         &                ln_trdmld_trc_restart, ln_trdmld_trc_instant, &
+         &                ln_trdmxl_trc_restart, ln_trdmxl_trc_instant, &
          &                cn_trdrst_trc_in, cn_trdrst_trc_out, ln_trdtrc
 #endif
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcrst.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcrst.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcrst.F90	(revision 5075)
@@ -137,5 +137,5 @@
           CALL trc_rst_stat            ! statistics
           CALL iom_close( numrtw )     ! close the restart file (only at last time step)
-#if ! defined key_trdmld_trc
+#if ! defined key_trdmxl_trc
           lrst_trc = .FALSE.
 #endif
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcstp.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcstp.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/NEMO/TOP_SRC/trcstp.F90	(revision 5075)
@@ -19,6 +19,6 @@
    USE trcwri
    USE trcrst
-   USE trdmod_trc_oce
-   USE trdmld_trc
+   USE trdtrc_oce
+   USE trdmxl_trc
    USE iom
    USE in_out_manager
@@ -59,5 +59,5 @@
       IF( nn_timing == 1 )   CALL timing_start('trc_stp')
       !
-      IF( kt == nittrc000 .AND. lk_trdmld_trc )  CALL trd_mld_trc_init    ! trends: Mixed-layer
+      IF( kt == nittrc000 .AND. lk_trdmxl_trc )  CALL trd_mxl_trc_init    ! trends: Mixed-layer
       !
       IF( lk_vvl ) THEN                                                   ! update ocean volume due to ssh temporal evolution
@@ -100,5 +100,5 @@
          ENDIF
          IF( lrst_trc )            CALL trc_rst_wri  ( kt )       ! write tracer restart file
-         IF( lk_trdmld_trc  )      CALL trd_mld_trc  ( kt )       ! trends: Mixed-layer
+         IF( lk_trdmxl_trc  )      CALL trd_mxl_trc  ( kt )       ! trends: Mixed-layer
          !
          IF( nn_dttrc /= 1   )     CALL trc_sub_reset( kt )       ! resetting physical variables when sub-stepping
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-PW7_MONSOON
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-PW7_MONSOON	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-PW7_MONSOON	(revision 5075)
@@ -0,0 +1,89 @@
+#!/bin/bash 
+#!
+# @ shell = /usr/bin/ksh
+# @ job_name = MPI_config
+# @ output = out.$(job_name).$(jobid)
+# @ error =  err.$(job_name).$(jobid)
+# @ job_type = parallel
+# @ total_tasks = NPROCS
+# @ wall_clock_limit = 0:30:00
+# @ resources = ConsumableMemory(1562mb)
+# @ class = parallel
+# @ node_usage = shared
+# @ notification = error
+# @ task_affinity = core
+# @ queue
+
+ulimit -c unlimited
+ulimit -s unlimited
+#
+# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
+# (via sed operating on this template job file). 
+#
+  OCEANCORES=NPROCS
+  export SETTE_DIR=DEF_SETTE_DIR
+
+###############################################################
+#
+# set up mpp computing environment
+#
+# Local settings for machine IBM Power7 (hpc2e at UK Met Office)
+#
+export MPIRUN="poe -pgmodel $MP_PGMMODEL -n $OCEANCORES -cmdfile"
+
+#
+# load sette functions (only post_test_tidyup needed)
+#
+  . ${SETTE_DIR}/all_functions.sh
+
+# Don't remove neither change the following comment line
+# BODY
+
+
+#
+# These variables are needed by post_test_tidyup function in all_functions.sh
+#
+  export EXE_DIR=DEF_EXE_DIR
+  export INPUT_DIR=DEF_INPUT_DIR
+  export CONFIG_DIR=DEF_CONFIG_DIR
+  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
+  export NEW_CONF=DEF_NEW_CONF
+  export CMP_NAM=DEF_CMP_NAM
+  export TEST_NAME=DEF_TEST_NAME
+#
+# end of set up
+
+
+###############################################################
+#
+# change to the working directory 
+#
+cd ${EXE_DIR}
+
+  echo Running on host `hostname`
+  echo Time is `date`
+  echo Directory is `pwd`
+# 
+#  Run the parallel MPI executable 
+#
+  if [ MPI_FLAG == "yes" ]; then
+     n=1
+     echo "./opa" > ./alltasks
+     while [ $n -lt $OCEANCORES ]
+     do
+       echo "./opa" >> ./alltasks
+       n=$(( $n + 1 ))
+     done
+     time ${MPIRUN} ./alltasks
+  else
+     time ./opa
+  fi
+
+
+#
+  post_test_tidyup
+
+# END_BODY
+# Don't remove neither change the previous comment line
+
+  exit
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_ADA
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_ADA	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_ADA	(revision 5075)
@@ -0,0 +1,81 @@
+#!/bin/bash 
+#!
+# @ job_name = MPI_config
+# standard output file  
+# @ output = $(job_name).$(jobid)
+# standard error file
+# @ error =  $(job_name).$(jobid)
+# job type
+# @ job_type = parallel
+# Number of procs 
+# @ total_tasks = NPROCS
+# time
+# @ wall_clock_limit = 0:30:00
+# @ queue
+
+#
+# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
+# (via sed operating on this template job file). 
+#
+  OCEANCORES=NPROCS
+  export SETTE_DIR=DEF_SETTE_DIR
+
+###############################################################
+#
+# set up mpp computing environment
+#
+# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
+#
+export MPIRUN="poe"
+
+#
+# load sette functions (only post_test_tidyup needed)
+#
+  . ${SETTE_DIR}/all_functions.sh
+#
+
+# Don't remove neither change the following line
+# BODY
+
+#
+# These variables are needed by post_test_tidyup function in all_functions.sh
+#
+  export EXE_DIR=DEF_EXE_DIR
+  export INPUT_DIR=DEF_INPUT_DIR
+  export CONFIG_DIR=DEF_CONFIG_DIR
+  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
+  export NEW_CONF=DEF_NEW_CONF
+  export CMP_NAM=DEF_CMP_NAM
+  export TEST_NAME=DEF_TEST_NAME
+#
+# end of set up
+###############################################################
+#
+# change to the working directory 
+#
+cd ${EXE_DIR}
+
+  echo Running on host `hostname`
+  echo Time is `date`
+  echo Directory is `pwd`
+# 
+#  Run the parallel MPI executable 
+#
+#  echo "Running time ${MPIRUN} ./opa"
+#
+  if [ MPI_FLAG == "yes" ]; then
+     echo "Running time ${MPIRUN} ./opa -procs $OCEANCORES"
+     time ${MPIRUN} ./opa -procs $OCEANCORES
+  else
+     echo "Running time ./opa"
+     time ./opa
+  fi
+
+#
+  post_test_tidyup
+
+# END_BODY
+# Don't remove neither change the previous line
+
+
+  exit
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_ADA_O0
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_ADA_O0	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_ADA_O0	(revision 5075)
@@ -0,0 +1,82 @@
+#!/bin/bash 
+#!
+# @ job_name = MPI_config
+# standard output file  
+# @ output = $(job_name).$(jobid)
+# standard error file
+# @ error =  $(job_name).$(jobid)
+# job type
+# @ job_type = parallel
+# Number of procs 
+# @ total_tasks = NPROCS
+# time
+# @ wall_clock_limit = 0:30:00
+# @ queue
+
+#
+# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
+# (via sed operating on this template job file). 
+#
+  OCEANCORES=NPROCS
+  export SETTE_DIR=DEF_SETTE_DIR
+
+###############################################################
+#
+# set up mpp computing environment
+#
+# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
+#
+#export MPIRUN="poe -procs $OCEANCORES"
+export MPIRUN="poe"
+
+#
+# load sette functions (only post_test_tidyup needed)
+#
+  . ${SETTE_DIR}/all_functions.sh
+#
+
+# Don't remove neither change the following line
+# BODY
+
+#
+# These variables are needed by post_test_tidyup function in all_functions.sh
+#
+  export EXE_DIR=DEF_EXE_DIR
+  export INPUT_DIR=DEF_INPUT_DIR
+  export CONFIG_DIR=DEF_CONFIG_DIR
+  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
+  export NEW_CONF=DEF_NEW_CONF
+  export CMP_NAM=DEF_CMP_NAM
+  export TEST_NAME=DEF_TEST_NAME
+#
+# end of set up
+###############################################################
+#
+# change to the working directory 
+#
+cd ${EXE_DIR}
+
+  echo Running on host `hostname`
+  echo Time is `date`
+  echo Directory is `pwd`
+# 
+#  Run the parallel MPI executable 
+#
+#  echo "Running time ${MPIRUN} ./opa"
+#
+  if [ MPI_FLAG == "yes" ]; then
+     echo "Running time ${MPIRUN} ./opa -procs $OCEANCORES"
+     time ${MPIRUN} ./opa  -procs $OCEANCORES
+  else
+     echo "Running time ./opa"
+     time ./opa
+  fi
+
+#
+  post_test_tidyup
+
+# END_BODY
+# Don't remove neither change the previous line
+
+
+  exit
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_MOBILIS
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_MOBILIS	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-X64_MOBILIS	(revision 5075)
@@ -0,0 +1,94 @@
+#!/bin/bash
+#SBATCH -N NODES
+#SBATCH --time=00:59:00 
+
+module purge
+module load shared
+module load gcc
+module load intel/compiler/64/14.0/2013_sp1.2.144
+module load openmpi/intel/64/1.6.5
+module load slurm/2.5.7
+
+#
+  export OMP_NUM_THREADS=1
+  export OCORES=NPROCS
+  export XCORES=NXIOPROCS
+  export SETTE_DIR=DEF_SETTE_DIR
+  export XIO_HOME=/home/acc/XIOS
+#
+# load sette functions (only post_test_tidyup needed)
+#
+  . ${SETTE_DIR}/all_functions.sh
+###############################################################
+#
+# set up mpp computing environment
+#
+#
+# Local settings. These settings are for a particular machine (the MOBILIS ClusterVision 
+# system at NOCS) at a particular stage of that machine's evolution. This template file
+# is provided for illustration purposes only and will not work on any other machine. There
+# should, however, be sufficient similarity with other MPP platforms and batch systems
+# for this example to provide a useful guide for experienced users
+#
+# Don't remove neither change the following line
+# BODY
+#
+# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
+# (via sed operating on this template job file). Note that the number of compute nodes required
+# is also set by the fcm_job.sh on the PBS select header line above.
+#
+# These variables are needed by post_test_tidyup function in all_functions.sh
+#
+  export INPUT_DIR=DEF_INPUT_DIR
+  export CONFIG_DIR=DEF_CONFIG_DIR
+  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
+  export NEW_CONF=DEF_NEW_CONF
+  export CMP_NAM=DEF_CMP_NAM
+  export TEST_NAME=DEF_TEST_NAME
+  export EXE_DIR=DEF_EXE_DIR
+#
+# end of set up
+###############################################################
+#
+# change to the working directory 
+#
+  cd $EXE_DIR
+  echo Directory is `pwd`
+  if [ $XCORES -eq 0 ]; then
+#
+# Run SPMD case
+#
+       echo time `which mpirun` --report-bindings -x MALLOC_MMAP_MAX_=-1                 \
+                                -x MALLOC_TRIM_THRESHOLD_=33554432 -np $OCORES --bynode  \
+                                --mca mpi_paffinity_alone 1 ./opa 
+            time `which mpirun` --report-bindings -x MALLOC_MMAP_MAX_=-1                 \
+                                -x MALLOC_TRIM_THRESHOLD_=33554432 -np $OCORES --bynode  \
+                                --mca mpi_paffinity_alone 1 ./opa 
+  else
+       if [ ! -f ./xios_server.exe ] && [ -f ${XIO_HOME}/bin/xios_server.exe ]; then
+          cp ${XIO_HOME}/bin/xios_server.exe .
+       fi
+       if [ ! -f ./xios_server.exe ]; then
+          echo "./xios_server.exe not found"
+          echo "run aborted"
+          exit
+       fi
+#
+#  Run MPMD case
+#
+       echo time `which mpirun` --report-bindings -x MALLOC_MMAP_MAX_=-1 \
+                                -x MALLOC_TRIM_THRESHOLD_=33554432       \
+                                -np $XCORES ./xios_server.exe            \
+                              : -np $OCORES --bynode  --mca mpi_paffinity_alone 1 ./opa 
+#
+            time `which mpirun` --report-bindings -x MALLOC_MMAP_MAX_=-1 \
+                                -x MALLOC_TRIM_THRESHOLD_=33554432       \
+                                -np $XCORES ./xios_server.exe            \
+                              : -np $OCORES --bynode  --mca mpi_paffinity_alone 1 ./opa 
+#
+  fi
+#
+  post_test_tidyup
+# END_BODY
+# Don't remove neither change the previous line
+  exit
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-XC_ARCHER_INTEL
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-XC_ARCHER_INTEL	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-XC_ARCHER_INTEL	(revision 5075)
@@ -0,0 +1,94 @@
+#!/bin/bash 
+#!
+#PBS -N nemo_sette
+#PBS -l walltime=00:59:00
+#PBS -l select=NODES
+#PBS -j oe
+#PBS -A n01-Global
+
+
+  export PBS_O_WORKDIR=$(readlink -f $PBS_O_WORKDIR)               
+  export OMP_NUM_THREADS=1
+  cd $PBS_O_WORKDIR
+#
+  echo " ";
+  export OMP_NUM_THREADS=1
+  O_PER_NODE=24
+  X_PER_NODE=4
+  OCORES=NPROCS
+  if [ $OCORES -le 23 ] ; then O_PER_NODE=$OCORES; fi
+  XCORES=NXIOPROCS
+  if [ $XCORES -le 3 ] ; then X_PER_NODE=$XCORES; fi
+  export SETTE_DIR=DEF_SETTE_DIR
+  export XIO_HOME=/home/acc/XIOS
+###############################################################
+#
+#
+# load sette functions (only post_test_tidyup needed)
+#
+  . ${SETTE_DIR}/all_functions.sh
+###############################################################
+#
+# set up mpp computing environment
+#
+#
+# Local settings. These settings are for a particular machine (the MOBILIS ClusterVision 
+# system at NOCS) at a particular stage of that machine's evolution. This template file
+# is provided for illustration purposes only and will not work on any other machine. There
+# should, however, be sufficient similarity with other MPP platforms and batch systems
+# for this example to provide a useful guide for experienced users
+#
+# Don't remove neither change the following line
+# BODY
+#
+# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
+# (via sed operating on this template job file). Note that the number of compute nodes required
+# is also set by the fcm_job.sh on the PBS select header line above.
+#
+# These variables are needed by post_test_tidyup function in all_functions.sh
+#
+  export INPUT_DIR=DEF_INPUT_DIR
+  export CONFIG_DIR=DEF_CONFIG_DIR
+  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
+  export NEW_CONF=DEF_NEW_CONF
+  export CMP_NAM=DEF_CMP_NAM
+  export TEST_NAME=DEF_TEST_NAME
+  export EXE_DIR=DEF_EXE_DIR
+  ulimit -c unlimited
+  ulimit -s unlimited
+  export FORT_FMT_RECL=132
+#
+# end of set up
+###############################################################
+#
+# change to the working directory 
+#
+  cd $EXE_DIR
+  echo Directory is `pwd`
+  if [ $XCORES -eq 0 ]; then
+#
+# Run SPMD case
+#
+       echo time aprun -b  -n $OCORES -N $O_PER_NODE ./opa
+            time aprun -b  -n $OCORES -N $O_PER_NODE ./opa
+  else
+       if [ ! -f ./xios_server.exe ] && [ -f ${XIO_HOME}/bin/xios_server.exe ]; then
+          cp ${XIO_HOME}/bin/xios_server.exe .
+       fi
+       if [ ! -f ./xios_server.exe ]; then
+          echo "./xios_server.exe not found"
+          echo "run aborted"
+          exit
+       fi
+#
+#  Run MPMD case
+#
+       echo time aprun -b -n $XCORES -N $X_PER_NODE ./xios_server.exe : -n $OCORES -N $O_PER_NODE ./opa
+            time aprun -b -n $XCORES -N $X_PER_NODE ./xios_server.exe : -n $OCORES -N $O_PER_NODE ./opa
+#
+  fi
+#
+  post_test_tidyup
+# END_BODY
+# Don't remove neither change the previous line
+  exit
Index: anches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-x3750_ADA
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/BATCH_TEMPLATE/batch-x3750_ADA	(revision 5074)
+++ 	(revision )
@@ -1,81 +1,0 @@
-#!/bin/bash 
-#!
-# @ job_name = MPI_config
-# standard output file  
-# @ output = $(job_name).$(jobid)
-# standard error file
-# @ error =  $(job_name).$(jobid)
-# job type
-# @ job_type = parallel
-# Number of procs 
-# @ total_tasks = NPROCS
-# time
-# @ wall_clock_limit = 0:30:00
-# @ queue
-
-#
-# Test specific settings. Do not hand edit these lines; the fcm_job.sh script will set these
-# (via sed operating on this template job file). 
-#
-  OCEANCORES=NPROCS
-  export SETTE_DIR=DEF_SETTE_DIR
-
-###############################################################
-#
-# set up mpp computing environment
-#
-# Local settings for machine IBM Power6 (VARGAS at IDRIS France)
-#
-export MPIRUN="poe"
-
-#
-# load sette functions (only post_test_tidyup needed)
-#
-  . ${SETTE_DIR}/all_functions.sh
-#
-
-# Don't remove neither change the following line
-# BODY
-
-#
-# These variables are needed by post_test_tidyup function in all_functions.sh
-#
-  export EXE_DIR=DEF_EXE_DIR
-  export INPUT_DIR=DEF_INPUT_DIR
-  export CONFIG_DIR=DEF_CONFIG_DIR
-  export NEMO_VALIDATION_DIR=DEF_NEMO_VALIDATION
-  export NEW_CONF=DEF_NEW_CONF
-  export CMP_NAM=DEF_CMP_NAM
-  export TEST_NAME=DEF_TEST_NAME
-#
-# end of set up
-###############################################################
-#
-# change to the working directory 
-#
-cd ${EXE_DIR}
-
-  echo Running on host `hostname`
-  echo Time is `date`
-  echo Directory is `pwd`
-# 
-#  Run the parallel MPI executable 
-#
-#  echo "Running time ${MPIRUN} ./opa"
-#
-  if [ MPI_FLAG == "yes" ]; then
-     echo "Running time ${MPIRUN} ./opa"
-     time ${MPIRUN} ./opa
-  else
-     echo "Running time ./opa"
-     time ./opa
-  fi
-
-#
-  post_test_tidyup
-
-# END_BODY
-# Don't remove neither change the previous line
-
-
-  exit
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ISOMIP.cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ISOMIP.cfg	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ISOMIP.cfg	(revision 5075)
@@ -0,0 +1,1 @@
+
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ORCA2_LIM3.cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ORCA2_LIM3.cfg	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ORCA2_LIM3.cfg	(revision 5075)
@@ -0,0 +1,1 @@
+ORCA2_LIM_nemo_v3.6.tar ORCA2_LIM_nemo_v3.6
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ORCA2_LIM_OBS.cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ORCA2_LIM_OBS.cfg	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/input_ORCA2_LIM_OBS.cfg	(revision 5075)
@@ -0,0 +1,1 @@
+ORCA2_LIM_nemo_v3.6.tar ORCA2_LIM_nemo_v3.6
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/iodef_sette.xml
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/iodef_sette.xml	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/iodef_sette.xml	(revision 5075)
@@ -2,5 +2,5 @@
 <simulation> 
 
- <context id="nemo" time_origin="1900-01-01 00:00:00" >
+ <context id="nemo" time_origin="1950-01-01 00:00:00" >
     
     <!-- $id$ -->
@@ -21,27 +21,25 @@
     -->
     
-    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="1d" min_digits="4">
+    <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" min_digits="4">
     
-      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".FALSE."/> <!-- 1h files -->
-      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".FALSE."/> <!-- 2h files -->
-      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".FALSE."/> <!-- 3h files -->     
-      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".FALSE."/> <!-- 4h files -->
-      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".FALSE."/> <!-- 6h files -->
-     
-      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".FALSE."/> <!-- 1d files -->
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."/> <!-- 1h files -->
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->     
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."/> <!-- 1d files -->
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d files -->  
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."/> <!-- real monthly files -->
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
 
-      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".FALSE."/> <!-- 3d files -->
-      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".FALSE."/> <!-- 5d files -->
-
-      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".FALSE."/> <!-- real monthly files -->
-      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".FALSE."/> <!-- real 2m files -->
-      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".FALSE."/> <!-- real 3m files -->
-      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".FALSE."/> <!-- real 4m files -->
-      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".FALSE."/> <!-- real 6m files -->
-
-      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".FALSE."/> <!-- real yearly files -->
-      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".FALSE."/> <!-- real 2y files -->
-      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".FALSE."/> <!-- real 5y files -->
-      <file_group id="10y" output_freq="10y" output_level="10" enabled=".FALSE."/> <!-- real 10y files -->
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."/> <!-- real yearly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
 
    </file_definition>
@@ -64,6 +62,14 @@
    <domain_definition src="./domain_def.xml"/>
    
-   <grid_definition />    
-  
+   <grid_definition>    
+     <grid id="grid_T_2D" domain_ref="grid_T"/>
+     <grid id="grid_T_3D" domain_ref="grid_T" axis_ref="deptht"/>
+     <grid id="grid_U_2D" domain_ref="grid_U"/>
+     <grid id="grid_U_3D" domain_ref="grid_U" axis_ref="depthu"/>
+     <grid id="grid_V_2D" domain_ref="grid_V"/>
+     <grid id="grid_V_3D" domain_ref="grid_V" axis_ref="depthv"/>
+     <grid id="grid_W_2D" domain_ref="grid_W"/>
+     <grid id="grid_W_3D" domain_ref="grid_W" axis_ref="depthw"/>
+    </grid_definition>   
   </context>
   
@@ -86,34 +92,27 @@
 ============================================================================================================
     -->
- 
+    
     <file_definition type="multiple_file" name="@expname@_@freq@_@startdate@_@enddate@" sync_freq="10d" min_digits="4">
     
-      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".FALSE."/> <!-- 1h files -->
-      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".FALSE."/> <!-- 2h files -->
-      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".FALSE."/> <!-- 3h files -->     
-      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".FALSE."/> <!-- 4h files -->
-      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".FALSE."/> <!-- 6h files -->
-     
-      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".FALSE."/> <!-- 1d files -->
+      <file_group id="1ts" output_freq="1ts"  output_level="10" enabled=".TRUE."/> <!-- 1 time step files -->
+      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".TRUE."/> <!-- 1h files -->
+      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".TRUE."/> <!-- 2h files -->
+      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".TRUE."/> <!-- 3h files -->     
+      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".TRUE."/> <!-- 4h files -->
+      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".TRUE."/> <!-- 6h files -->     
+      <file_group id="1d" output_freq="1d"  output_level="10" enabled=".TRUE."/> <!-- 1d files -->
+      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".TRUE."/> <!-- 3d files -->    
+      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".TRUE."/>  <!-- 5d files -->  
+      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".TRUE."/> <!-- real monthly files -->
+      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".TRUE."/> <!-- real 2m files -->
+      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".TRUE."/> <!-- real 3m files -->
+      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".TRUE."/> <!-- real 4m files -->
+      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".TRUE."/> <!-- real 6m files -->
 
-      <file_group id="3d" output_freq="3d"  output_level="10" enabled=".FALSE."/> <!-- 3d files -->
-      <file_group id="5d" output_freq="5d"  output_level="10" enabled=".FALSE."/> <!-- 5d files -->
+      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".TRUE."/> <!-- real yearly files -->
+      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".TRUE."/> <!-- real 2y files -->
+      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".TRUE."/> <!-- real 5y files -->
+      <file_group id="10y" output_freq="10y" output_level="10" enabled=".TRUE."/> <!-- real 10y files -->
 
-      <file_group id="1m" output_freq="1mo" output_level="10" enabled=".FALSE."/> <!-- real monthly files -->
-      <file_group id="2m" output_freq="2mo" output_level="10" enabled=".FALSE."/> <!-- real 2m files -->
-      <file_group id="3m" output_freq="3mo" output_level="10" enabled=".FALSE."/> <!-- real 3m files -->
-      <file_group id="4m" output_freq="4mo" output_level="10" enabled=".FALSE."/> <!-- real 4m files -->
-      <file_group id="6m" output_freq="6mo" output_level="10" enabled=".FALSE."/> <!-- real 6m files -->
-
-      <file_group id="1y"  output_freq="1y" output_level="10" enabled=".FALSE."/> <!-- real yearly files -->
-      <file_group id="2y"  output_freq="2y" output_level="10" enabled=".FALSE."/> <!-- real 2y files -->
-      <file_group id="5y"  output_freq="5y" output_level="10" enabled=".FALSE."/> <!-- real 5y files -->
-      <file_group id="10y" output_freq="10y" output_level="10" enabled=".FALSE."/> <!-- real 10y files -->
-      <file_group id="1h" output_freq="1h"  output_level="10" enabled=".FALSE."/> <!-- 1h files -->
-      <file_group id="2h" output_freq="2h"  output_level="10" enabled=".FALSE."/> <!-- 2h files -->
-      <file_group id="3h" output_freq="3h"  output_level="10" enabled=".FALSE."/> <!-- 3h files -->     
-      <file_group id="4h" output_freq="4h"  output_level="10" enabled=".FALSE."/> <!-- 4h files -->
-      <file_group id="6h" output_freq="6h"  output_level="10" enabled=".FALSE."/> <!-- 6h files -->
-     
    </file_definition>
     
@@ -130,4 +129,5 @@
       <axis id="depthw" long_name="Vertical W levels" unit="m" positive="down" />
       <axis id="nfloat" long_name="Float number"      unit="-"  />
+      <axis id="icbcla" long_name="Iceberg class"     unit="-"  />
    </axis_definition> 
     
@@ -146,5 +146,4 @@
   </context>
 
-
   <context id="xios">
 
@@ -154,5 +153,5 @@
         We must have buffer_size > jpi*jpj*jpk*8 (with jpi and jpj the subdomain size)
 -->
-	  <variable id="buffer_size"               type="integer">10000000</variable>
+	  <variable id="buffer_size"               type="integer">10155778</variable>
 	  <variable id="buffer_server_factor_size" type="integer">2</variable>
 	  <variable id="info_level"                type="integer">0</variable>
@@ -164,4 +163,3 @@
                
   </context>
-  
 </simulation>
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/prepare_exe_dir.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/prepare_exe_dir.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/prepare_exe_dir.sh	(revision 5075)
@@ -71,4 +71,4 @@
 
 cp -r ${CONFIG_DIR}/${NEW_CONF}/EXP00/* ${EXE_DIR}/.
-#cp -r ${SETTE_DIR}/iodef_sette.xml ${EXE_DIR}/iodef.xml
+cp -r ${SETTE_DIR}/iodef_sette.xml ${EXE_DIR}/iodef.xml
 cd ${EXE_DIR}
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/prepare_job.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/prepare_job.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/prepare_job.sh	(revision 5075)
@@ -182,22 +182,51 @@
 fi
 
-# example for NOCS Altix system using PBS batch submission (requires ${SETTE_DIR}/sette_batch_template file)
+# example for NOCS ClusterVision system using SLURM batch submission (requires ${SETTE_DIR}/sette_batch_template file)
 #
   #  if [ ${MPI_FLAG} == "no" ] ; then
 		case ${COMPILER} in 
-			ALTIX_NAUTILUS_MPT)
-                                NB_REM=$( echo $NB_PROC $NXIO_PROC | awk '{print ( $1 + $2 ) % 4}')
+			X64_MOBILIS)
+                                NB_REM=$( echo $NB_PROC $NXIO_PROC | awk '{print ( $1 + $2 ) % 16}')
 		        	if [ ${NB_REM} == 0 ] ; then
-					# number of processes required is an integer multiple of 4
+					# number of processes required is an integer multiple of 16
 					#
-					NB_NODES=$( echo $NB_PROC $NXIO_PROC | awk '{print ($1 + $2 ) / 4}')
+					NB_NODES=$( echo $NB_PROC $NXIO_PROC | awk '{print ($1 + $2 ) / 16}')
 				else
 					#
-					# number of processes required is not an integer multiple of 4
+					# number of processes required is not an integer multiple of 16
 					# round up the number of nodes required.
 					#
-					NB_NODES=$( echo $NB_PROC $NXIO_PROC | awk '{printf("%d",($1 + $2 ) / 4 + 1 )}')
+					NB_NODES=$( echo $NB_PROC $NXIO_PROC | awk '{printf("%d",($1 + $2 ) / 16 + 1 )}')
 	       			fi
 				;;
+                        XC_ARCHER_INTEL)
+                                # ocean cores are packed 24 to a node
+                                NB_REM=$( echo $NB_PROC | awk '{print ( $1 % 24 ) }')
+                                if [ ${NB_REM} == 0 ] ; then
+                                        # number of processes required is an integer multiple of 24
+                                        #
+                                        NB_NODES=$( echo $NB_PROC $NXIO_PROC | awk '{print ($1) / 24}')
+                                else
+                                        #
+                                        # number of processes required is not an integer multiple of 24
+                                        # round up the number of nodes required.
+                                        #
+                                        NB_NODES=$( echo $NB_PROC | awk '{printf("%d",($1) / 24 + 1 )}')
+                                fi
+                                # xios cores are sparsely packed at 4 to a node
+                                # but can not share nodes with the ocean cores
+                                NB_REM=$( echo $NXIO_PROC | awk '{print ( $2 % 4 ) }')
+                                if [ ${NB_REM} == 0 ] ; then
+                                        # number of processes required is an integer multiple of 4                           
+                                        #
+                                        NB_NODES=$( echo $NB_NODES $NXIO_PROC | awk '{print ($1 + ( $2 / 4 ))}')                    
+                                else
+                                        #
+                                        # number of processes required is not an integer multiple of 4                             
+                                        # round up the number of nodes required.
+                                        #
+                                        NB_NODES=$( echo $NB_NODES $NXIO_PROC | awk '{print ($1 + ( $2 / 4 ) + 1)}')                    
+                                fi
+                                ;;
                         ifort_MERCATOR_CLUSTER)
                                 echo NB_PROCS ${NB_PROC}
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette.sh	(revision 5075)
@@ -88,8 +88,8 @@
 #
 # Compiler among those in NEMOGCM/ARCH
-COMPILER=tobedefined
+COMPILER=X64_ADA
 export BATCH_COMMAND_PAR="llsubmit"
 export BATCH_COMMAND_SEQ=$BATCH_COMMAND_PAR
-export INTERACT_FLAG="yes"
+export INTERACT_FLAG="no"
 export MPIRUN_FLAG="yes"
 export USING_XIOS="yes"
@@ -136,8 +136,11 @@
 # ORCA2_LIM_PISCES: 3 &  4
 # ORCA2_OFF_PISCES: 5 &  6
-# AMM12           : 7 &  8
-# SAS             : 9 & 10
-# ORCA2_AGRIF_LIM: 11
-for config in 1 2 3 4 5 6 7 8 9 10 11
+# ORCA2_LIM3      : 7 &  8
+# AMM12           : 9 & 10
+# SAS             :11 & 12
+# ISOMIP          :13 & 14
+# ORCA2_LIM_OBS:   15
+# ORCA2_AGRIF_LIM :16
+for config in  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
 
 do
@@ -629,6 +632,134 @@
 fi
 
+
+# TESTS FOR ORCA2_LIM3 CONFIGURATION
+if [ ${config} -eq 7 ] ;  then
+    ## Restartability tests for ORCA2_LIM3
+    export TEST_NAME="LONG"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ORCA2LIM3_LONG -r ORCA2_LIM3 -j 8 del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=4
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg cn_exp \"O2L3_LONG\"
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 150
+    set_namelist namelist_cfg nn_stock 75
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg jpnij 4
+    set_namelist namelist_cfg nn_solv 2
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM3.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    
+    cd ${SETTE_DIR}
+    export TEST_NAME="SHORT"
+    . ./prepare_exe_dir.sh
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg cn_exp \"O2L3_SHORT\"
+    set_namelist namelist_cfg nn_it000 76
+    set_namelist namelist_cfg nn_itend 150
+    set_namelist namelist_cfg nn_stock 75
+    set_namelist namelist_cfg ln_rstart .true.
+    set_namelist namelist_cfg nn_rstctl 2
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg jpnij 4
+    set_namelist namelist_cfg nn_solv 2
+    set_namelist namelist_cfg cn_ocerst_in \"O2L3_LONG_00000075_restart\"
+    set_namelist namelist_ice_cfg cn_icerst_in \"O2L3_LONG_00000075_restart_ice\"
+    for (( i=1; i<=$NPROC; i++)) ; do
+        L_NPROC=$(( $i - 1 ))
+        L_NPROC=`printf "%04d\n" ${L_NPROC}`
+        ln -sf ../LONG/O2L3_LONG_00000075_restart_${L_NPROC}.nc .
+        ln -sf ../LONG/O2L3_LONG_00000075_restart_ice_${L_NPROC}.nc .
+    done
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM3.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+fi
+
+if [ ${config} -eq 8 ] ;  then
+    ## Reproducibility tests for ORCA2_LIM3
+    export TEST_NAME="REPRO_4_4"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ORCA2LIM3_16 -r ORCA2_LIM3 -j 8 add_key "key_mpp_rep" del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=16
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 75
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg jpni 4
+    set_namelist namelist_cfg jpnj 4
+    set_namelist namelist_cfg jpnij 16
+    set_namelist namelist_cfg nn_solv 2
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM3.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+    cd ${SETTE_DIR}
+    export TEST_NAME="REPRO_2_8"
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=16
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 75
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 8
+    set_namelist namelist_cfg jpnij 16
+    set_namelist namelist_cfg nn_solv 2
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM3.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+fi
+
+
 # TESTS FOR AMM12 CONFIGURATION
-if [ ${config} -eq 7 ] ;  then
+if [ ${config} -eq 9 ] ;  then
     ## Restartability tests for AMM12
     export TEST_NAME="LONG"
@@ -692,5 +823,5 @@
 fi
 
-if [ ${config} -eq 8 ] ;  then
+if [ ${config} -eq 10 ] ;  then
 ## Reproducibility tests for AMM12
     export TEST_NAME="REPRO_8_4"
@@ -748,5 +879,5 @@
 
 # TESTS FOR ORCA2_SAS_LIM CONFIGURATION
-if [ ${config} -eq 9 ] ;  then
+if [ ${config} -eq 11 ] ;  then
     ## Restartability tests for SAS
     export TEST_NAME="LONG"
@@ -810,5 +941,5 @@
 fi
 
-if [ ${config} -eq 10 ] ;  then
+if [ ${config} -eq 12 ] ;  then
 ## Reproducibility tests for ORCA2_SAS_LIM
     export TEST_NAME="REPRO_8_4"
@@ -864,7 +995,224 @@
     . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
 fi
-
+# TESTS FOR ISOMIP CONFIGURATION
+if [ ${config} -eq 13 ] ;  then
+    ## Restartability tests for ISOMIP
+    export TEST_NAME="LONG"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ISOMIP_LONG -r ISOMIP -j 8 del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=4
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg cn_exp \"ISOMIP_LONG\"
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 96
+    set_namelist namelist_cfg nn_stock 48
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg nn_solv 2
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg jpnij 4
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ISOMIP.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+
+    cd ${SETTE_DIR}
+    export TEST_NAME="SHORT"
+    . ./prepare_exe_dir.sh
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg cn_exp \"ISOMIP_SHORT\"
+    set_namelist namelist_cfg nn_it000 49
+    set_namelist namelist_cfg nn_itend 96
+    set_namelist namelist_cfg nn_stock 48
+    set_namelist namelist_cfg ln_rstart .true.
+    set_namelist namelist_cfg nn_rstctl 2
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg nn_solv 2
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg jpnij 4
+    set_namelist namelist_cfg cn_ocerst_in \"ISOMIP_LONG_00000048_restart\"
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    for (( i=1; i<=$NPROC; i++)) ; do
+        L_NPROC=$(( $i - 1 ))
+        L_NPROC=`printf "%04d\n" ${L_NPROC}`
+        ln -sf ../LONG/ISOMIP_LONG_00000048_restart_${L_NPROC}.nc .
+    done
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ISOMIP.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+fi
+if [ ${config} -eq 14 ] ;  then
+    ## Reproducibility tests for ISOMIP
+    export TEST_NAME="REPRO_1_4"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ISOMIP_4 -r ISOMIP -j 8 add_key "key_mpp_rep" del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=4
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg cn_exp \"ISOMIP_14\"
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 48
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg nn_bench 0
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_solv 2
+    set_namelist namelist_cfg jpni 1
+    set_namelist namelist_cfg jpnj 4
+    set_namelist namelist_cfg jpnij 4
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ISOMIP.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+    cd ${SETTE_DIR}
+    export TEST_NAME="REPRO_2_2"
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=4
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg cn_exp \"ISOMIP_22\"
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 48
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg nn_solv 2
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg jpnij 4
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ISOMIP.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+fi
+
+## Test assimilation interface code, OBS and ASM for reproducibility
+## Restartability not tested (ASM code not restartable while increments are being applied)
+if [ ${config} -eq 15 ] ; then
+   ## Reproducibility tests for ORCA2_LIM_OBS
+    export TEST_NAME="REPRO_4_4"
+    cd ${CONFIG_DIR}
+    . ./makenemo -m ${CMP_NAM} -n ORCA2_LIM_OBS -r ORCA2_LIM -j 8 add_key "key_mpp_rep key_diaobs key_asminc" del_key ${DEL_KEYS}
+    cd ${SETTE_DIR}
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=16
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 75
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg jpni 4
+    set_namelist namelist_cfg jpnj 4
+    set_namelist namelist_cfg jpnij 16
+    set_namelist namelist_cfg nn_solv 2   
+    set_namelist namelist_cfg ln_t3d .true.
+    set_namelist namelist_cfg ln_s3d .true.
+    set_namelist namelist_cfg ln_profb .true.
+    set_namelist namelist_cfg ln_sst .true.
+    set_namelist namelist_cfg ln_sstfb .true.
+    set_namelist namelist_cfg ln_sla .true.
+    set_namelist namelist_cfg ln_slafb .true.
+    set_namelist namelist_cfg ln_seaice .false.
+    set_namelist namelist_cfg ln_bkgwri .true.
+    set_namelist namelist_cfg ln_trainc .true.
+    set_namelist namelist_cfg ln_dyninc .true.
+    set_namelist namelist_cfg ln_sshinc .true.
+    set_namelist namelist_cfg ln_asmiau .true.
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM_OBS.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+   cd ${SETTE_DIR}
+    export TEST_NAME="REPRO_2_8"
+    . ./prepare_exe_dir.sh
+    JOB_FILE=${EXE_DIR}/run_job.sh
+    NPROC=16
+    if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
+    cd ${EXE_DIR}
+    set_namelist namelist_cfg nn_it000 1
+    set_namelist namelist_cfg nn_itend 75
+    set_namelist namelist_cfg nn_fwb 0
+    set_namelist namelist_cfg ln_ctl .false.
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg jpni 2
+    set_namelist namelist_cfg jpnj 8
+    set_namelist namelist_cfg jpnij 16
+    set_namelist namelist_cfg nn_solv 2
+    set_namelist namelist_cfg ln_t3d .true.
+    set_namelist namelist_cfg ln_s3d .true.
+    set_namelist namelist_cfg ln_profb .true.
+    set_namelist namelist_cfg ln_sst .true.
+    set_namelist namelist_cfg ln_sstfb .true.
+    set_namelist namelist_cfg ln_sla .true.
+    set_namelist namelist_cfg ln_slafb .true.
+    set_namelist namelist_cfg ln_seaice .false.
+    set_namelist namelist_cfg ln_bkgwri .true.
+    set_namelist namelist_cfg ln_trainc .true.
+    set_namelist namelist_cfg ln_dyninc .true.
+    set_namelist namelist_cfg ln_sshinc .true.
+    set_namelist namelist_cfg ln_asmiau .true.
+    if [ ${USING_MPMD} == "yes" ] ; then
+       set_xio_using_server iodef.xml true
+    else
+       set_xio_using_server iodef.xml false
+    fi
+    cd ${SETTE_DIR}
+    . ./prepare_job.sh input_ORCA2_LIM_OBS.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
+    cd ${SETTE_DIR}
+    . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+fi
 # TEST FOR ORCA2_LIM_AGRIF : simple test of running AGRIF (no restartability neither reproducibility tests)
-if [ ${config} -eq 11 ] ;  then
+if [ ${config} -eq 16 ] ;  then
     ## ORCA2_LIM with Agulhas AGRIF zoom in MPI
     export TEST_NAME="SHORT"
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_beginner.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_beginner.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_beginner.sh	(revision 5075)
@@ -4,5 +4,5 @@
 # Contact : sflod@locean-ipsl.upmc.fr
 #
-# sette.sh   : principal script of SET TEsts for NEMO (SETTE)
+# sette_beginner.sh   : example of script of SET TEsts for NEMO (SETTE)
 # ----------------------------------------------------------------------
 # NEMO/SETTE , NEMO Consortium (2010)
@@ -21,26 +21,102 @@
 # ===================
 #
-# ----------------------------------------------
-# Set of tests for NEMO for beginners
-# ----------------------------------------------
+# COMPILER          : name of compiler as defined in NEMOGCM/ARCH directory 
+# BATCH_COMMAND_PAR :  name of the command for submitting parallel batch jobs
+# BATCH_COMMAND_SEQ :  name of the command for submitting sequential batch jobs  
+# INTERACT_FLAG     : flag to run in interactive mode "yes"
+#                           to run in batch mode "no"
+# MPIRUN_FLAG       : flag to run in parallel (MPI) "yes"
+#                           to run in sequential mode (NB_PROC = 1) "no"
+# USING_XIOS        : flag to control the activation of key_iomput
+#                      "yes" to compile using key_iomput and link to the external XIOS library
+#                      "no"  to compile without key_iomput and link to the old IOIPSL library
+# USING_MPMD        : flag to control the use of stand-alone IO servers
+#                     requires USING_XIOS="yes"
+#                      "yes" to run in MPMD (detached) mode with stand-alone IO servers
+#                      "no"  to run in SPMD (attached) mode without separate IO servers 
+# NUM_XIOSERVERS    : number of stand-alone IO servers to employ
+#                     set to zero if USING_MPMD="no"
 #
-# SYNOPSIS
-# ========
+# Principal script is sette.sh, that calls 
 #
-# ::
+#  makenemo  : to create successive exectuables in ${CONFIG_NAME}/BLD/bin/nemo.exe 
+#              and links to opa in ${CONFIG_NAME}/EXP00)
 #
-#  $ ./sette_beginner.sh
+#  param.cfg : sets and loads following directories:
 #
-# DESCRIPTION
-# ===========
-# First simple example of how to use SETTE: create GYRE_SHORT configuration, compile it with 1 proc, and test it for a SHORT test: 5days
-#-
+#   FORCING_DIR         : is the directory for forcing files (tarfile)
+#   INPUT_DIR           : is the directory for input files storing 
+#   TMPDIR              : is the temporary directory (if needed)
+#   NEMO_VALIDATION_DIR : is the validation directory
+#
+#   (NOTE: this file is the same for all configrations to be tested with sette)
+#
+#   all_functions.sh : loads functions used by sette (note: new functions can be added here)
+#   set_namelist     : function declared in all_functions that sets namelist parameters 
+#   post_test_tidyup : creates validation storage directory and copies required output files 
+#                      (solver.stat and ocean.output) in it after execution of test.
+#
+#  VALIDATION tree is:
+#
+#   NEMO_VALIDATION_DIR/WCONFIG_NAME/WCOMPILER_NAME/TEST_NAME/REVISION_NUMBER(or DATE)
+#
+#  prepare_exe_dir.sh : defines and creates directory where the test is executed
+#                       execution directory takes name of TEST_NAME defined for every test 
+#                       in sette.sh. (each test in executed in its own directory)
+#
+#  prepare_job.sh     : to generate the script run_job.sh
+#
+#  fcm_job.sh         : run in batch (INTERACT_FLAG="no") or interactive (INTERACT_FLAG="yes")
+#                        see sette.sh and BATCH_TEMPLATE directory
+#
+#  NOTE: jobs requiring initial or forcing data need to have an input_CONFIG.cfg in which 
+#        can be found paths to the input tar file)
+#  NOTE: if job is not launched for any reason you have the executable ready in ${EXE_DIR} 
+#        directory
+#  NOTE: the changed namelists are left in ${EXE_DIR} directory whereas original namelists 
+#        remain in ${NEW_CONF}/EXP00
+# 
+#  NOTE: a log file, output.sette, is created in ${SETTE_DIR} with the echoes of 
+#        executed commands
+#
+#  NOTE: if sette.sh is stopped in output.sette there is written the last command 
+#        executed by sette.sh
+#
+# example use: ./sette_beginner.sh 
+#########################################################################################
 #
 # Compiler among those in NEMOGCM/ARCH
-COMPILER=macport_osx
+COMPILER=x3750_ADA
 export BATCH_COMMAND_PAR="llsubmit"
 export BATCH_COMMAND_SEQ=$BATCH_COMMAND_PAR
 export INTERACT_FLAG="yes"
 export MPIRUN_FLAG="yes"
+
+export DEL_KEYS="key_iomput"
+if [ ${USING_XIOS} == "yes" ]
+ then 
+   export DEL_KEYS=""
+fi
+
+#
+# Settings which control the use of stand alone servers (only relevant if using xios)
+#
+export USING_MPMD="no"
+export NUM_XIOSERVERS=4
+export JOB_PREFIX=batch-mpmd
+#
+if [ ${USING_MPMD} == "no" ] 
+ then
+   export NUM_XIOSERVERS=0
+   export JOB_PREFIX=batch
+fi
+#
+#
+if [ ${USING_MPMD} == "yes" ] && [ ${USING_XIOS} == "no"]
+ then
+   echo "Incompatible choices. MPMD mode requires the XIOS server"
+   exit
+fi
+#
 
 # Directory to run the tests
@@ -54,7 +130,5 @@
 # Copy job_batch_COMPILER file for specific compiler into job_batch_template
 cd ${SETTE_DIR}
-##if [ ${INTERACT_FLAG} == no ] ;  then
-    cp BATCH_TEMPLATE/batch-${COMPILER} job_batch_template || exit
-##fi 
+cp BATCH_TEMPLATE/batch-${COMPILER} job_batch_template || exit
 
 # Run for GYRE CONFIG
@@ -63,13 +137,14 @@
 export TEST_NAME="SHORT_TEST"
 cd ${CONFIG_DIR}
-. ./makenemo -m ${CMP_NAM} -n GYRE_SHORT -r GYRE -j 10 add_key "key_mpp_mpi key_nosignedzero"
+. ./makenemo -m ${CMP_NAM} -n GYRE_SHORT -r GYRE -j 10 add_key "key_nosignedzero" del_key ${DEL_KEYS}
 cd ${SETTE_DIR}
-. param.cfg 
-. all_functions.sh
+. ./param.cfg 
+. ./all_functions.sh
+. ./prepare_exe_dir.sh
 # creation of execution directory
-. prepare_exe_dir.sh
 JOB_FILE=${EXE_DIR}/run_job.sh
+# setting number of procs used
 NPROC=4
-\rm $JOB_FILE
+if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
 cd ${EXE_DIR}
 # setting namelist parameters
@@ -82,7 +157,11 @@
 # frequency of creation of a restart file
 set_namelist namelist_cfg nn_stock 60
-
+if [ ${USING_MPMD} == "yes" ] ; then
+      set_xio_using_server iodef.xml true
+   else
+      set_xio_using_server iodef.xml false
+fi
 cd ${SETTE_DIR}
-. ./prepare_job.sh input_GYRE.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE}
+. ./prepare_job.sh input_GYRE.cfg $NPROC ${TEST_NAME} ${MPIRUN_FLAG} ${JOB_FILE} ${NUM_XIOSERVERS}
 # run job, with 4 processors, test named SHORT (= 60 time steps)
 cd ${SETTE_DIR}   
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_rpt
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_rpt	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_rpt	(revision 5075)
@@ -8,5 +8,5 @@
 #
   set mach = `grep "COMPILER=" ./sette.sh | sed -e 's/COMPILER=//'`
-  set NEMO_VALID = ../CONFIG/NEMO_VALIDATION
+  set NEMO_VALID = `grep "NEMO_VALIDATION_DIR=" ./param.cfg | sed -e 's/NEMO_VALIDATION_DIR=//'`
 #
   if ( ! -d $NEMO_VALID ) then
@@ -17,9 +17,6 @@
   cd $NEMO_VALID
 #
-# The script also needs the date or revision tag. Currently this is taken from the latest sub-directory
-# found in the WGYRE_LONG directory
-#
-  set dorv = `ls -1rtd ./WGYRE_LONG/{$mach}/* | tail -1l `
-  set dorv = $dorv:t
+# The script also needs the date or revision tag. Currently this is taken from the latest sub-directory found in each directory
+#
 #
 # Now loop through all the test directories. On the second pass the user can optionally examine any mismatched
@@ -30,4 +27,6 @@
 foreach pass (0 1 )
   if ( -d ./WGYRE_LONG ) then
+    set dorv = `ls -1rtd ./WGYRE_LONG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WGYRE_LONG/{$mach}/{$dorv}/LONG/ocean.output
     set f1s = ./WGYRE_LONG/{$mach}/{$dorv}/LONG/solver.stat
@@ -39,22 +38,54 @@
     cmp -s f1.tmp$$ $f2s
     if ( $status == 0 ) then
-      echo "GYRE     restartability  passed"
-    else
-      echo "GYRE     restartability  FAILED"
-      if ( $pass == 1 ) then
-        echo "<return> to view solver.stat differences"
-        set y = $<
-        sdiff f1.tmp$$ $f2s
-        echo "<return> to view ocean.output differences"
-        set y = $<
-        sdiff $f1o $f2o | grep "|"
-        echo "<return> to continue"
-        set y = $<
-      endif
-    endif
-    rm f1.tmp$$
-  endif
+      echo "GYRE        restartability  passed"
+    else
+      echo "GYRE        restartability  FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff f1.tmp$$ $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+    rm f1.tmp$$
+  endif
+
+  if ( -d ./WISOMIP_LONG ) then
+    set dorv = `ls -1rtd ./WISOMIP_LONG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WISOMIP_LONG/{$mach}/{$dorv}/LONG/ocean.output
+    set f1s = ./WISOMIP_LONG/{$mach}/{$dorv}/LONG/solver.stat
+    set f2o = ./WISOMIP_LONG/{$mach}/{$dorv}/SHORT/ocean.output
+    set f2s = ./WISOMIP_LONG/{$mach}/{$dorv}/SHORT/solver.stat
+
+    set nl = `wc -l $f2s`
+    tail -$nl[1] $f1s > f1.tmp$$
+    cmp -s f1.tmp$$ $f2s
+    if ( $status == 0 ) then
+      echo "ISOMIP      restartability  passed"
+    else
+      echo "ISOMIP      restartability  FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff f1.tmp$$ $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+    rm f1.tmp$$
+  endif
+
   
   if ( -d ./WORCA2LIMPIS_LONG ) then
+    set dorv = `ls -1rtd ./WORCA2LIMPIS_LONG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WORCA2LIMPIS_LONG/{$mach}/{$dorv}/LONG/ocean.output
     set f1s = ./WORCA2LIMPIS_LONG/{$mach}/{$dorv}/LONG/solver.stat
@@ -84,4 +115,6 @@
 
   if ( -d ./WORCA2OFFPIS_LONG ) then
+    set dorv = `ls -1rtd ./WORCA2OFFPIS_LONG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WORCA2OFFPIS_LONG/{$mach}/{$dorv}/LONG/ocean.output
     set f1s = ./WORCA2OFFPIS_LONG/{$mach}/{$dorv}/LONG/tracer.stat
@@ -111,4 +144,6 @@
   
   if ( -d ./WAMM12_LONG ) then
+    set dorv = `ls -1rtd ./WAMM12_LONG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WAMM12_LONG/{$mach}/{$dorv}/LONG/ocean.output
     set f1s = ./WAMM12_LONG/{$mach}/{$dorv}/LONG/solver.stat
@@ -136,8 +171,72 @@
     rm f1.tmp$$
   endif
-
-echo
+  if ( -d ./WORCA2LIM3_LONG ) then
+    set dorv = `ls -1rtd ./WORCA2LIM3_LONG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WORCA2LIM3_LONG/{$mach}/{$dorv}/LONG/ocean.output
+    set f1s = ./WORCA2LIM3_LONG/{$mach}/{$dorv}/LONG/solver.stat
+    set f2o = ./WORCA2LIM3_LONG/{$mach}/{$dorv}/SHORT/ocean.output
+    set f2s = ./WORCA2LIM3_LONG/{$mach}/{$dorv}/SHORT/solver.stat
+    set nl = `wc -l $f2s`
+    tail -$nl[1] $f1s > f1.tmp$$
+    cmp -s f1.tmp$$ $f2s
+    if ( $status == 0 ) then
+      echo "ORCA2LIM3   restartability  passed"
+    else
+      echo "ORCA2LIM3   restartability  FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff f1.tmp$$ $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+    rm f1.tmp$$
+  endif
+
+  if ( -d ./WSAS_LONG ) then
+    set dorv = `ls -1rtd ./WSAS_LONG/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WSAS_LONG/{$mach}/{$dorv}/LONG/ocean.output
+    set f1s = ./WSAS_LONG/{$mach}/{$dorv}/LONG/solver.stat
+    set f2o = ./WSAS_LONG/{$mach}/{$dorv}/SHORT/ocean.output
+    set f2s = ./WSAS_LONG/{$mach}/{$dorv}/SHORT/solver.stat
+    foreach f ( $f1o $f1s $f2o $f2s )
+     if ( ! -f $f ) then
+      echo 'SAS         restartability  inconclusive ( ' $f:t ' not found )'
+      goto NEXT1
+     endif
+    end
+
+    set nl = `wc -l $f2s`
+    tail -$nl[1] $f1s > f1.tmp$$
+    cmp -s f1.tmp$$ $f2s
+    if ( $status == 0 ) then
+      echo "SAS         restartability  passed"
+    else
+      echo "SAS         restartability  FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff f1.tmp$$ $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+    rm f1.tmp$$
+  endif
+
+NEXT1:
   
   if ( -d ./WGYRE_4 ) then
+    set dorv = `ls -1rtd ./WGYRE_4/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WGYRE_4/{$mach}/{$dorv}/REPRO_1_4/ocean.output
     set f1s = ./WGYRE_4/{$mach}/{$dorv}/REPRO_1_4/solver.stat
@@ -147,21 +246,49 @@
     cmp -s $f1s $f2s
     if ( $status == 0 ) then
-      echo "GYRE     reproducibility passed"
-    else
-      echo "GYRE     reproducibility FAILED"
-      if ( $pass == 1 ) then
-        echo "<return> to view solver.stat differences"
-        set y = $<
-        sdiff $f1s $f2s
-        echo "<return> to view ocean.output differences"
-        set y = $<
-        sdiff $f1o $f2o | grep "|"
-        echo "<return> to continue"
-        set y = $<
-      endif
-    endif
-  endif
-  
+      echo "GYRE        reproducibility passed"
+    else
+      echo "GYRE        reproducibility FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff $f1s $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+  endif
+
+  if ( -d ./WISOMIP_4 ) then
+    set dorv = `ls -1rtd ./WISOMIP_4/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WISOMIP_4/{$mach}/{$dorv}/REPRO_1_4/ocean.output
+    set f1s = ./WISOMIP_4/{$mach}/{$dorv}/REPRO_1_4/solver.stat
+    set f2o = ./WISOMIP_4/{$mach}/{$dorv}/REPRO_2_2/ocean.output
+    set f2s = ./WISOMIP_4/{$mach}/{$dorv}/REPRO_2_2/solver.stat
+
+    cmp -s $f1s $f2s
+    if ( $status == 0 ) then
+      echo "ISOMIP      reproducibility passed"
+    else
+      echo "ISOMIP      reproducibility FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff $f1s $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+  endif
+ 
   if ( -d ./WORCA2LIMPIS_16 ) then
+    set dorv = `ls -1rtd ./WORCA2LIMPIS_16/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WORCA2LIMPIS_16/{$mach}/{$dorv}/REPRO_2_8/ocean.output
     set f1s = ./WORCA2LIMPIS_16/{$mach}/{$dorv}/REPRO_2_8/solver.stat
@@ -188,4 +315,6 @@
 
   if ( -d ./WORCA2OFFPIS_16 ) then
+    set dorv = `ls -1rtd ./WORCA2OFFPIS_16/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WORCA2OFFPIS_16/{$mach}/{$dorv}/REPRO_2_8/ocean.output
     set f1s = ./WORCA2OFFPIS_16/{$mach}/{$dorv}/REPRO_2_8/tracer.stat
@@ -212,4 +341,6 @@
   
   if ( -d ./WAMM12_32 ) then
+    set dorv = `ls -1rtd ./WAMM12_32/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WAMM12_32/{$mach}/{$dorv}/REPRO_4_8/ocean.output
     set f1s = ./WAMM12_32/{$mach}/{$dorv}/REPRO_4_8/solver.stat
@@ -235,5 +366,68 @@
   endif
 
+  if ( -d ./WORCA2LIM3_16 ) then
+    set dorv = `ls -1rtd ./WORCA2LIM3_16/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WORCA2LIM3_16/{$mach}/{$dorv}/REPRO_2_8/ocean.output
+    set f1s = ./WORCA2LIM3_16/{$mach}/{$dorv}/REPRO_2_8/solver.stat
+    set f2o = ./WORCA2LIM3_16/{$mach}/{$dorv}/REPRO_4_4/ocean.output
+    set f2s = ./WORCA2LIM3_16/{$mach}/{$dorv}/REPRO_4_4/solver.stat
+
+    cmp -s $f1s $f2s
+    if ( $status == 0 ) then
+      echo "ORCA2LIM3   reproducibility passed"
+    else
+      echo "ORCA2LIM3   reproducibility FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff $f1s $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+  endif
+
+
+  if ( -d ./WSAS_32 ) then
+    set dorv = `ls -1rtd ./WSAS_32/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
+    set f1o = ./WSAS_32/{$mach}/{$dorv}/REPRO_4_8/ocean.output
+    set f1s = ./WSAS_32/{$mach}/{$dorv}/REPRO_4_8/solver.stat
+    set f2o = ./WSAS_32/{$mach}/{$dorv}/REPRO_8_4/ocean.output
+    set f2s = ./WSAS_32/{$mach}/{$dorv}/REPRO_8_4/solver.stat
+
+    foreach f ( $f1o $f1s $f2o $f2s )
+     if ( ! -f $f ) then
+      echo 'SAS         reproducibility inconclusive ( ' $f:t ' not found )'
+      goto NEXT2
+     endif
+    end
+
+    cmp -s $f1s $f2s
+    if ( $status == 0 ) then
+      echo "SAS reproducibility passed"
+    else
+      echo "SAS reproducibility FAILED"
+      if ( $pass == 1 ) then
+        echo "<return> to view solver.stat differences"
+        set y = $<
+        sdiff $f1s $f2s
+        echo "<return> to view ocean.output differences"
+        set y = $<
+        sdiff $f1o $f2o | grep "|"
+        echo "<return> to continue"
+        set y = $<
+      endif
+    endif
+  endif
+NEXT2:
+
   if ( -d ./WORCA2AGUL_1_2 ) then
+    set dorv = `ls -1rtd ./WORCA2AGUL_1_2/{$mach}/* | tail -1l `
+    set dorv = $dorv:t
     set f1o = ./WORCA2AGUL_1_2/{$mach}/{$dorv}/SHORT/ocean.output
     set f1s = ./WORCA2AGUL_1_2/{$mach}/{$dorv}/SHORT/solver.stat
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_xios.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_xios.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/SETTE/sette_xios.sh	(revision 5075)
@@ -1,11 +1,11 @@
 #!/bin/bash
 ############################################################
-# Author : Simona Flavoni for NEMO
-# Contact: sflod@locean-ipsl.upmc.fr
-# 2013   : A.C. Coward added options for testing with XIOS in dettached mode
-#
-# sette.sh   : principal script of SET TEsts for NEMO (SETTE)
+# Author : Italo Epicoco - CMCC
+# Contact: italo.epicoco@unisalento.it
+# 2014   : A.C. Coward added new namelist settings for GYRE configuration
+#
+# sette_xios.sh   : additional script of SET TEsts for XIOS within NEMO
 # ----------------------------------------------------------------------
-# NEMO/SETTE , NEMO Consortium (2010)
+# NEMO/SETTE , NEMO Consortium (2014)
 # Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
 # ----------------------------------------------------------------------
@@ -29,15 +29,11 @@
 # MPIRUN_FLAG       : flag to run in parallel (MPI) "yes"
 #                           to run in sequential mode (NB_PROC = 1) "no"
-# USING_XIOS        : flag to control the activation of key_iomput
-#                      "yes" to compile using key_iomput and link to the external XIOS library
-#                      "no"  to compile without key_iomput and link to the old IOIPSL library
 # USING_MPMD        : flag to control the use of stand-alone IO servers
-#                     requires USING_XIOS="yes"
-#                      "yes" to run in MPMD (detached) mode with stand-alone IO servers
-#                      "no"  to run in SPMD (attached) mode without separate IO servers 
+#                      "true" to run in MPMD (detached) mode with stand-alone IO servers
+#                      "false"  to run in SPMD (attached) mode without separate IO servers 
 # NUM_XIOSERVERS    : number of stand-alone IO servers to employ
-#                     set to zero if USING_MPMD="no"
-#
-# Principal script is sette.sh, that calls 
+#                     set to zero if USING_MPMD="false"
+#
+# Principal script is sette_xios.sh, that calls 
 #
 #  makenemo  : to create successive exectuables in ${CONFIG_NAME}/BLD/bin/nemo.exe 
@@ -81,12 +77,12 @@
 #        executed commands
 #
-#  NOTE: if sette.sh is stopped in output.sette there is written the last command 
-#        executed by sette.sh
-#
-# example use: ./sette.sh 
+#  NOTE: if sette_xios.sh is stopped in output.sette there is written the last command 
+#        executed by sette_xios.sh
+#
+# example use: ./sette_xios.sh 
 #########################################################################################
 #
 # Compiler among those in NEMOGCM/ARCH
-COMPILER=tobedefined
+COMPILER=
 export BATCH_COMMAND_PAR="llsubmit"
 export BATCH_COMMAND_SEQ=$BATCH_COMMAND_PAR
@@ -103,17 +99,31 @@
 
 CMP_NAM=${1:-$COMPILER}
+#
+#=================================================================================
 # Copy job_batch_COMPILER file for specific compiler into job_batch_template
+# Note this batch template needs to be capable of launching both SPMD and MPMD
+# tasks with internal selection depending on the value of NUM_XIOSERVERS
+# (0=SPMD; >0 = MPMD)
+#=================================================================================
+#
 cd ${SETTE_DIR}
 cp BATCH_TEMPLATE/batch-${COMPILER} job_batch_template || exit
 
-for config in 2  
+for config in 1 2  
 
 do
 
-# TESTS FOR GYRE CONFIGURATION
+#==========================================================
+# TESTS FOR XIOS USING GYRE CONFIGURATION AT LOW RESOLUTION
+#==========================================================
+
 if [ ${config} -eq 1 ] ;  then
-    ## Restartability tests for GYRE
+    ## Test of XIOS configured in attached mode with multiple output files (one for each process). 
+    ## $NPROC processes are used 
 
     NPROC=4
+    jp_cfg=1
+    jpni=2
+    jpnj=2
     export NUM_XIOSERVERS=0
     export USING_MPMD="false"
@@ -124,7 +134,7 @@
     . ../CONFIG/makenemo -m ${CMP_NAM} -n GYRE_XIOS_LR -r GYRE_XIOS -j 8 
     cd ${SETTE_DIR}
-    . param.cfg
-    . all_functions.sh
-    . prepare_exe_dir.sh
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
     JOB_FILE=${EXE_DIR}/run_job.sh
     if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
@@ -133,9 +143,13 @@
     set_namelist namelist_cfg nn_it000 1
     set_namelist namelist_cfg nn_itend 120
-    set_namelist namelist_cfg nn_stock 60
-    set_namelist namelist_cfg ln_clobber .true.
-    set_namelist namelist_cfg jp_cfg 1
-    set_namelist namelist_cfg jpni 2
-    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg nn_stock 120
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg jp_cfg $jp_cfg
+    set_namelist namelist_cfg jpidta $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjdta $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpiglo $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjglo $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpni $jpni
+    set_namelist namelist_cfg jpnj $jpnj
     set_namelist namelist_cfg jpnij $NPROC
 
@@ -149,4 +163,6 @@
     . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
 
+
+    ## Test of XIOS configured in attached mode with a single output file. 
 
     export TEST_NAME="ATTACHED_ONE"
@@ -154,5 +170,5 @@
     export USING_MPMD="false"
     cd ${SETTE_DIR} 
-    . prepare_exe_dir.sh
+    . ./prepare_exe_dir.sh
     JOB_FILE=${EXE_DIR}/run_job.sh
     if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
@@ -161,9 +177,13 @@
     set_namelist namelist_cfg nn_it000 1
     set_namelist namelist_cfg nn_itend 120
-    set_namelist namelist_cfg nn_stock 60
-    set_namelist namelist_cfg ln_clobber .true.
-    set_namelist namelist_cfg jp_cfg 1
-    set_namelist namelist_cfg jpni 2
-    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg nn_stock 120
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg jp_cfg $jp_cfg
+    set_namelist namelist_cfg jpidta $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjdta $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpiglo $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjglo $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpni $jpni
+    set_namelist namelist_cfg jpnj $jpnj
     set_namelist namelist_cfg jpnij $NPROC
 
@@ -177,4 +197,8 @@
     . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
 
+
+    ## Test of XIOS configured in detached mode with a single output file. 
+    ## $NUM_XIOSERVERS IO server are used.
+    ## the total number of allocated cores is $NUM_XIOSERVERS + $NPROC 
 
     export TEST_NAME="DETACHED_ONE"
@@ -182,5 +206,6 @@
     export USING_MPMD="true"
     cd ${SETTE_DIR}
-    . prepare_exe_dir.sh
+#
+    . ./prepare_exe_dir.sh
     JOB_FILE=${EXE_DIR}/run_job.sh
     if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
@@ -189,9 +214,13 @@
     set_namelist namelist_cfg nn_it000 1
     set_namelist namelist_cfg nn_itend 120
-    set_namelist namelist_cfg nn_stock 60
-    set_namelist namelist_cfg ln_clobber .true.
-    set_namelist namelist_cfg jp_cfg 1
-    set_namelist namelist_cfg jpni 2
-    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg nn_stock 120
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg jp_cfg $jp_cfg
+    set_namelist namelist_cfg jpidta $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjdta $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpiglo $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjglo $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpni $jpni
+    set_namelist namelist_cfg jpnj $jpnj
     set_namelist namelist_cfg jpnij $NPROC
 
@@ -204,4 +233,9 @@
     cd ${SETTE_DIR}
     . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+    ## Test of XIOS configured in detached mode with multiple output files (one for each IO server). 
+    ## $NUM_XIOSERVERS IO server are used.
+    ## the total number of allocated cores is $NUM_XIOSERVERS + $NPROC 
+
 
     export TEST_NAME="DETACHED_MULTIPLE"
@@ -209,5 +243,5 @@
     export USING_MPMD="true"
     cd ${SETTE_DIR}
-    . prepare_exe_dir.sh
+    . ./prepare_exe_dir.sh
     JOB_FILE=${EXE_DIR}/run_job.sh
     if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
@@ -216,9 +250,13 @@
     set_namelist namelist_cfg nn_it000 1
     set_namelist namelist_cfg nn_itend 120
-    set_namelist namelist_cfg nn_stock 60
-    set_namelist namelist_cfg ln_clobber .true.
-    set_namelist namelist_cfg jp_cfg 1
-    set_namelist namelist_cfg jpni 2
-    set_namelist namelist_cfg jpnj 2
+    set_namelist namelist_cfg nn_stock 120
+    set_namelist namelist_cfg ln_clobber .true.
+    set_namelist namelist_cfg jp_cfg $jp_cfg
+    set_namelist namelist_cfg jpidta $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjdta $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpiglo $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjglo $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpni $jpni
+    set_namelist namelist_cfg jpnj $jpnj
     set_namelist namelist_cfg jpnij $NPROC
 
@@ -234,8 +272,16 @@
 fi
 
+#==========================================================
+# TESTS FOR XIOS USING GYRE CONFIGURATION AT HIGH RESOLUTION
+#==========================================================
+
 if [ ${config} -eq 2 ] ;  then
-    ## Restartability tests for GYRE
-
-    NPROC=152
+    ## Test of XIOS configured in attached mode with multiple output files (one for each process). 
+    ## $NPROC processes are used 
+
+    NPROC=64
+    jp_cfg=30
+    jpni=8
+    jpnj=8
     export NUM_XIOSERVERS=0
     export USING_MPMD="false"
@@ -246,7 +292,9 @@
     . ../CONFIG/makenemo -m ${CMP_NAM} -n GYRE_XIOS_HR -r GYRE_XIOS -j 8
     cd ${SETTE_DIR}
-    . param.cfg
-    . all_functions.sh
-    . prepare_exe_dir.sh
+#
+    . ./param.cfg
+    . ./all_functions.sh
+    . ./prepare_exe_dir.sh
+#
     JOB_FILE=${EXE_DIR}/run_job.sh
     if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
@@ -258,7 +306,11 @@
     set_namelist namelist_cfg nn_bench 1
     set_namelist namelist_cfg ln_clobber .true.
-    set_namelist namelist_cfg jp_cfg 144
-    set_namelist namelist_cfg jpni 19
-    set_namelist namelist_cfg jpnj 8
+    set_namelist namelist_cfg jp_cfg $jp_cfg
+    set_namelist namelist_cfg jpidta $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjdta $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpiglo $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjglo $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpni $jpni
+    set_namelist namelist_cfg jpnj $jpnj
     set_namelist namelist_cfg jpnij $NPROC
 
@@ -273,4 +325,5 @@
 
 
+    ## Test of XIOS configured in attached mode with a single output file. 
 
     export TEST_NAME="ATTACHED_ONE"
@@ -278,5 +331,7 @@
     export USING_MPMD="false"
     cd ${SETTE_DIR}
-    . prepare_exe_dir.sh
+#
+    . ./prepare_exe_dir.sh
+#
     JOB_FILE=${EXE_DIR}/run_job.sh
     if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
@@ -288,7 +343,11 @@
     set_namelist namelist_cfg nn_bench 1
     set_namelist namelist_cfg ln_clobber .true.
-    set_namelist namelist_cfg jp_cfg 144
-    set_namelist namelist_cfg jpni 19
-    set_namelist namelist_cfg jpnj 8
+    set_namelist namelist_cfg jp_cfg $jp_cfg
+    set_namelist namelist_cfg jpidta $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjdta $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpiglo $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjglo $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpni $jpni
+    set_namelist namelist_cfg jpnj $jpnj
     set_namelist namelist_cfg jpnij $NPROC
 
@@ -301,4 +360,9 @@
     cd ${SETTE_DIR}
     . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+
+    ## Test of XIOS configured in detached mode with a single output file. 
+    ## $NUM_XIOSERVERS IO server are used.
+    ## the total number of allocated cores is $NUM_XIOSERVERS + $NPROC 
 
     export TEST_NAME="DETACHED_ONE"
@@ -306,5 +370,7 @@
     export USING_MPMD="true"
     cd ${SETTE_DIR}
-    . prepare_exe_dir.sh
+#
+    . ./prepare_exe_dir.sh
+#
     JOB_FILE=${EXE_DIR}/run_job.sh
     if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
@@ -316,7 +382,11 @@
     set_namelist namelist_cfg nn_bench 1
     set_namelist namelist_cfg ln_clobber .true.
-    set_namelist namelist_cfg jp_cfg 144
-    set_namelist namelist_cfg jpni 19
-    set_namelist namelist_cfg jpnj 8
+    set_namelist namelist_cfg jp_cfg $jp_cfg
+    set_namelist namelist_cfg jpidta $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjdta $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpiglo $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjglo $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpni $jpni
+    set_namelist namelist_cfg jpnj $jpnj
     set_namelist namelist_cfg jpnij $NPROC
 
@@ -329,4 +399,8 @@
     cd ${SETTE_DIR}
     . ./fcm_job.sh $NPROC ${JOB_FILE} ${INTERACT_FLAG} ${MPIRUN_FLAG}
+
+    ## Test of XIOS configured in detached mode with multiple output files (one for each IO server). 
+    ## $NUM_XIOSERVERS IO server are used.
+    ## the total number of allocated cores is $NUM_XIOSERVERS + $NPROC 
 
     export TEST_NAME="DETACHED_MULTIPLE"
@@ -334,5 +408,5 @@
     export USING_MPMD="true"
     cd ${SETTE_DIR}
-    . prepare_exe_dir.sh
+    . ./prepare_exe_dir.sh
     JOB_FILE=${EXE_DIR}/run_job.sh
     if [ -f ${JOB_FILE} ] ; then \rm ${JOB_FILE} ; fi
@@ -344,7 +418,11 @@
     set_namelist namelist_cfg nn_bench 1
     set_namelist namelist_cfg ln_clobber .true.
-    set_namelist namelist_cfg jp_cfg 144
-    set_namelist namelist_cfg jpni 19
-    set_namelist namelist_cfg jpnj 8
+    set_namelist namelist_cfg jp_cfg $jp_cfg
+    set_namelist namelist_cfg jpidta $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjdta $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpiglo $(( $jp_cfg * 30 + 2 ))
+    set_namelist namelist_cfg jpjglo $(( $jp_cfg * 20 + 2 ))
+    set_namelist namelist_cfg jpni $jpni
+    set_namelist namelist_cfg jpnj $jpnj
     set_namelist namelist_cfg jpnij $NPROC
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fadd_keys.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fadd_keys.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fadd_keys.sh	(revision 5075)
@@ -33,6 +33,6 @@
 #
 #
-# Script to add a set off key when compiling a configuration.
-# The list off key to be added has to be enclosed with " ". 
+# Script to add a set of key when compiling a configuration.
+# The list of key to be added has to be enclosed with " ". 
 # A 'sed' is performed to modify the CONFIG_NAME/cpp.fcm file to    
 # add the new key(s). 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcheck_config.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcheck_config.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcheck_config.sh	(revision 5075)
@@ -39,5 +39,5 @@
 # - Nothing set, use the previous in use 
 #
-# We use TOOLS/CONFIG_DIR/cfg.txt to check if the onfiguration exists.
+# We use TOOLS/CONFIG_DIR/cfg.txt to check if the configuration exists.
 #
 # EXAMPLES
@@ -76,5 +76,5 @@
    echo "Use makenemo -n MYCONFIG"
    echo "or  makenemo -h for help"
-   echo "Using defaut configuration : ${NEW_CONF}"
+   echo "Using default configuration : ${NEW_CONF}"
 fi
 if [ "$1" == cfg.txt ]; then
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fclean_var.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fclean_var.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fclean_var.sh	(revision 5075)
@@ -11,5 +11,5 @@
 #
 # ----------------------------
-# Clean environement variables
+# Clean environment variables
 # ----------------------------
 #
@@ -26,5 +26,5 @@
 #
 #
-# Clean environement variables
+# Clean environment variables
 #
 # EXAMPLES
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcopy_dir.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcopy_dir.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcopy_dir.sh	(revision 5075)
@@ -26,5 +26,5 @@
 #
 #
-# When a refenrence configuration is set, 
+# When a reference configuration is set, 
 # Copy NEMO sub-directories needed (OPA_SRC, TOP_SRC ...)
 #
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcopy_extdir.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcopy_extdir.sh	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fcopy_extdir.sh	(revision 5075)
@@ -0,0 +1,39 @@
+#!/bin/bash
+#set -x
+set -o posix
+#set -u
+#set -e
+#+
+# ============
+# Fcopy_extdir.sh
+# ============
+# --------------------------
+# Copy a reference directory
+# --------------------------
+# SYNOPSIS
+# ========
+# ::
+#  $ Fcopy_extdir.sh
+# DESCRIPTION
+# ===========
+# When an unsupported configuration is requested, 
+# Prepare sources for the NEMO sub-directories needed (OPA_SRC, TOP_SRC ...)
+# EXAMPLES
+# ========
+# ::
+#  $ ./Fcopy_extdir.sh ORCA2_LIM
+# TODO
+# ====
+# option debug
+# EVOLUTIONS
+# ==========
+# $Id: Fcopy_extdir.sh 3294 2012-01-28 16:44:18Z rblod $
+#   * creation
+#-
+grep "$1 " ${CONFIG_DIR}/uspcfg.txt > ${CONFIG_DIR}/cfg.tmp
+#
+LOCAL_REF=$(cat cfg.tmp | awk 'BEGIN {FS = "#" }{print $2}')
+TAB=$(cat cfg.tmp | awk 'BEGIN {FS = "#" }{print $3}')
+REMOTE_CTL=$(cat cfg.tmp | awk 'BEGIN {FS = "#" }{print $4}')
+#
+\rm ${CONFIG_DIR}/cfg.tmp
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fdel_keys.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fdel_keys.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fdel_keys.sh	(revision 5075)
@@ -34,5 +34,5 @@
 #
 # Add cpp keys when compiling a configuration, key list has to be enclosed with " ".
-# We perform a 'sed' on the CONFIG_NAME/CPP.fcm file, contianing the list of keys. 
+# We perform a 'sed' on the CONFIG_NAME/CPP.fcm file, containing the list of keys. 
 #
 # EXAMPLES
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Ffetch_extdir.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Ffetch_extdir.sh	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Ffetch_extdir.sh	(revision 5075)
@@ -0,0 +1,53 @@
+#!/bin/bash
+#set -x
+set -o posix
+#set -u
+#set -e
+#+
+# ===============
+# Ffetch_extdir.sh
+# ===============
+# ---------------
+# Make the config 
+# ---------------
+# SYNOPSIS
+# ========
+# ::
+#  $ Ffetch_extdir.sh
+# DESCRIPTION
+# ===========
+# - Make the config directory 
+# - Create repositories needed :
+#  
+#  - EXP00 for namelist
+#  - MY_SRC for user sources
+#  - BLD for compilation 
+# EXAMPLES
+# ========
+# ::
+#  $ ./Ffetch_extdir.sh CONFIG_NAME REMOTE_CTL 
+# TODO
+# ====
+# option debug
+# EVOLUTIONS
+# ==========
+# $Id: Ffetch_extdir.sh 3715 2012-11-28 16:06:02Z acc $
+#   * creation
+#-
+basedir=$(pwd)
+cd ${1}
+wget ${2} -O remote_file.list
+#
+if [ -f remote_file.list ] ; then
+ cat remote_file.list | grep -v '^#' |
+  while
+   read remfile locfile
+   do
+    if [ $remfile == 'create_directory' ] ;then
+      mkdir $locfile
+    else
+      wget $remfile -O $locfile
+    fi
+   done
+fi
+cd $basedir
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fmake_WORK.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fmake_WORK.sh	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fmake_WORK.sh	(revision 5075)
@@ -35,5 +35,5 @@
 # Make the WORK directory:
 #
-# - Create lin in NEW_CONF/WORK
+# - Create line in NEW_CONF/WORK
 # - Use specified sub-directories previously
 # - OPA has to be done first !!!
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fmake_extconfig.sh
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fmake_extconfig.sh	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/Fmake_extconfig.sh	(revision 5075)
@@ -0,0 +1,48 @@
+#!/bin/bash
+#set -x
+set -o posix
+#set -u
+#set -e
+#+
+# ===============
+# Fmake_extconfig.sh
+# ===============
+# ---------------
+# Make the directories for an externally supported configuration
+# and base the initial versions on the nearest equivalent from the
+# reference set (as named in uspcfg.txt)
+# ---------------
+# SYNOPSIS
+# ========
+# ::
+#  $ Fmake_extconfig.sh
+# DESCRIPTION
+# ===========
+# - Make the config directory 
+# - Create repositories needed :
+#  - EXP00 for namelist
+#  - MY_SRC for user sources
+#  - BLD for compilation 
+# EXAMPLES
+# ========
+# ::
+#  $ ./Fmake_extconfig.sh CONFIG_NAME REF_CONFIG_NAME 
+# TODO
+# ====
+# option debug
+# EVOLUTIONS
+# ==========
+# $Id: Fmake_extconfig.sh 3715 2012-11-28 16:06:02Z acc $
+#   * creation
+#-
+\mkdir  ${1}
+\mkdir  ${1}/EXP00
+\mkdir  ${1}/MY_SRC
+\cp -R  ${2}/cpp_${2}.fcm ${1}/cpp_${1}.fcm
+\cp -R  ${2}/EXP00/*namelist* ${1}/EXP00/.
+[ -f ${2}/EXP00/AGRIF_FixedGrids.in ] &&  \cp -R  ${2}/EXP00/AGRIF_FixedGrids.in ${1}/EXP00/.
+[ -f ${2}/EXP00/iodef.xml ]           &&  \cp -R  ${2}/EXP00/iodef.xml ${1}/EXP00/.
+[ -f ${2}/EXP00/field_def.xml ]       &&  \cp -R  ${2}/EXP00/field_def.xml ${1}/EXP00/.
+[ -f ${2}/EXP00/domain_def.xml ]      &&  \cp -R  ${2}/EXP00/domain_def.xml ${1}/EXP00/.
+[ -f ${2}/EXP00/xmlio_server.def ]    &&  \cp -R  ${2}/EXP00/xmlio_server.def ${1}/EXP00/.
+[ -d    ${2}/MY_SRC ]                 &&  \cp  ${2}/MY_SRC/* ${1}/MY_SRC/. 2> /dev/null
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld.cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld.cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld.cfg	(revision 5075)
@@ -24,4 +24,6 @@
 
 
+bld::tool::cpp       %CPP
+bld::tool::fpp       %CPP
 bld::tool::fc        %FC 
 bld::tool::fflags    %FCFLAGS %USER_INC
@@ -51,10 +53,5 @@
 bld::excl_dep        inc::mpe_logf.h
 bld::excl_dep        use::mpi
-bld::excl_dep        use::mod_prism_proto
-bld::excl_dep        use::mod_prism_def_partition_proto
-bld::excl_dep        use::mod_prism_get_comm
-bld::excl_dep        use::mod_prism_get_proto
-bld::excl_dep        use::mod_prism_put_proto
-bld::excl_dep        use::mod_comprism_proto
+bld::excl_dep        use::mod_oasis
 bld::excl_dep        use::mkl_dfti
 # Don't generate interface files
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld_preproagr.cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld_preproagr.cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld_preproagr.cfg	(revision 5075)
@@ -34,5 +34,6 @@
 bld::pp::nemo     1
 bld::pp::nemo/agrif2model     0
-bld::tool::fpp       cpp
+bld::tool::cpp       %CPP
+bld::tool::fpp       %CPP
 bld::tool::fppflags::nemo  %FPPFLAGS
 
@@ -46,10 +47,5 @@
 bld::excl_dep        inc::mpe_logf.h
 bld::excl_dep        use::mpi
-bld::excl_dep        use::mod_prism_proto
-bld::excl_dep        use::mod_prism_def_partition_proto
-bld::excl_dep        use::mod_prism_get_comm
-bld::excl_dep        use::mod_prism_get_proto
-bld::excl_dep        use::mod_prism_put_proto
-bld::excl_dep        use::mod_comprism_proto
+bld::excl_dep        use::mod_oasis
 bld::excl_dep        use::mkl_dfti
 bld::excl_dep	     use::nc4interface
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld_tools.cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld_tools.cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bld_tools.cfg	(revision 5075)
@@ -16,4 +16,6 @@
 dir::root            $NEMO_TDIR/$NEW_CONF/BLD
 
+bld::tool::cpp       %CPP
+bld::tool::fpp       %CPP
 bld::tool::fc        %FC 
 bld::tool::fflags    %FCFLAGS %USER_INC
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bldxag.cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bldxag.cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/COMPILE/bldxag.cfg	(revision 5075)
@@ -23,4 +23,6 @@
 
 
+bld::tool::cpp       %CPP
+bld::tool::fpp       %CPP
 bld::tool::fc        %FC 
 bld::tool::fflags    %FCFLAGS %USER_INC
@@ -47,10 +49,5 @@
 bld::excl_dep        inc::mpe_logf.h
 bld::excl_dep        use::mpi
-bld::excl_dep        use::mod_prism_proto
-bld::excl_dep        use::mod_prism_def_partition_proto
-bld::excl_dep        use::mod_prism_get_comm
-bld::excl_dep        use::mod_prism_get_proto
-bld::excl_dep        use::mod_prism_put_proto
-bld::excl_dep        use::mod_comprism_proto
+bld::excl_dep        use::mod_oasis
 bld::excl_dep        use::mkl_dfti
 # Don't generate interface files
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/MISCELLANEOUS/icb_pp.py
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/MISCELLANEOUS/icb_pp.py	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/MISCELLANEOUS/icb_pp.py	(revision 5075)
@@ -0,0 +1,159 @@
+from netCDF4 import Dataset
+from argparse import ArgumentParser
+import numpy as np
+import sys
+
+#
+# Basic iceberg trajectory post-processing python script.
+# This script collates iceberg trajectories from the distributed datasets written
+# out by each processing region and rearranges the ragged arrays into contiguous
+# streams for each unique iceberg. The output arrays are 2D (ntraj, ntimes) arrays.
+# Note that some icebergs may only exist for a subset of the possible times. In these
+# cases the missing instances are filled with invalid (NaN) values.
+#
+
+parser = ArgumentParser(description='produce collated trajectory file from distributed output\
+                                     files, e.g. \n python ./icb_pp.py \
+                                     -t  trajectory_icebergs_004248_ -n 296 -o trajsout.nc' )
+
+parser.add_argument('-t',dest='froot',help='fileroot_of_distrbuted_data; root name of \
+                     distributed trajectory output (usually completed with XXXX.nc, where \
+                     XXXX is the 4 digit processor number)', 
+                     default='trajectory_icebergs_004248_')
+
+parser.add_argument('-n',dest='fnum',help='number of distributed files to process', 
+                     type=int, default=None)
+
+parser.add_argument('-o',dest='fout',help='collated_output_file; file name to receive the \
+                     collated trajectory data', default='trajsout.nc')
+
+args = parser.parse_args()
+
+default_used = 0
+if args.froot is None:
+    pathstart = 'trajectory_icebergs_004248_'
+    default_used = 1
+else:
+    pathstart = args.froot
+
+if args.fnum is None:
+    procnum = 0
+    default_used = 1
+else:
+    procnum = args.fnum
+
+if args.fout is None:
+    pathout = 'trajsout.nc'
+    default_used = 1
+else:
+    pathout = args.fout
+
+if default_used == 1:
+   print('At least one default value will be used; command executing is:')
+   print('icb_pp.py -t ',pathstart,' -n ',procnum,' -o ',pathout)
+
+if procnum < 1:
+   print('Need some files to collate! procnum = ',procnum)
+   sys.exit()
+
+icu = []
+times = []
+#
+# Loop through all distributed datasets to obtain the complete list
+# of iceberg identification numbers and timesteps
+#
+for n in range(procnum):
+ nn = '%4.4d' % n
+ fw = Dataset(pathstart+nn+'.nc')
+ if len(fw.dimensions['n']) > 0:
+   print pathstart+nn+'.nc'
+   ic = fw.variables['iceberg_number'][:,0]
+   ts = fw.variables['timestep'][:]
+   icv = np.unique(ic)
+   ts = np.unique(ts)
+   print('Min Max ts: ',ts.min(), ts.max())
+   print('Number unique icebergs= ',icv.shape[0])
+   icu.append(icv)
+   times.append(ts)
+ fw.close()
+#
+# Now flatten the lists and reduce to the unique spanning set
+#
+icu = np.concatenate(icu)
+icu = np.unique(icu)
+times = np.concatenate(times)
+times = np.unique(times)
+ntraj = icu.shape[0]
+print(ntraj, ' unique icebergs found across all datasets')
+print('Icebergs ids range from: ',icu.min(), 'to: ',icu.max())
+print('times range from:        ',times.min(), 'to: ', times.max())
+#
+# Declare 2-D arrays to receive the data from all files
+#
+nt = times.shape[0]
+lons = np.zeros((ntraj, nt))
+lats = np.zeros((ntraj, nt))
+tims = np.zeros((ntraj, nt))
+xis  = np.zeros((ntraj, nt))
+yjs  = np.zeros((ntraj, nt))
+#
+# initially fill with invalid data
+#
+lons.fill(np.nan)
+lats.fill(np.nan)
+xis.fill(np.nan)
+yjs.fill(np.nan)
+tims.fill(np.nan)
+#
+# loop through distributed datasets again, this time
+# checking indices against icu and times lists and
+# inserting data into the correct locations in the 
+# 2-D collated sets.
+#
+for n in range(procnum):
+ nn = '%4.4d' % n
+ fw = Dataset(pathstart+nn+'.nc')
+# Note many distributed datafiles will contain no iceberg data
+# so skip quickly over these
+ m  = len(fw.dimensions['n'])
+ if m > 0:
+   inx = np.zeros(m, dtype=int)
+   tsx = np.zeros(m, dtype=int)
+   print pathstart+nn+'.nc'
+   ic = fw.variables['iceberg_number'][:,0]
+   ts = fw.variables['timestep'][:]
+   lns = fw.variables['lon'][:]
+   lts = fw.variables['lat'][:]
+   xxs = fw.variables['xi'][:]
+   yys = fw.variables['yj'][:]
+   for k in range(m):
+     inxx   = np.where(icu == ic[k])
+     inx[k] = inxx[0]
+   for k in range(m):
+     inxx   = np.where(times == ts[k])
+     tsx[k] = inxx[0]
+   lons[inx[:],tsx[:]] = lns[:]
+   lats[inx[:],tsx[:]] = lts[:]
+   tims[inx[:],tsx[:]] = ts[:]
+   xis[inx[:],tsx[:]] = xxs[:]
+   yjs[inx[:],tsx[:]] = yys[:]
+ fw.close()
+
+# Finally create the output file and write out the collated sets
+#
+fo = Dataset(pathout, 'w', format='NETCDF4')
+ntrj = fo.createDimension('ntraj', ntraj)
+nti  = fo.createDimension('ntime', None)
+olon = fo.createVariable('lon', 'f4',('ntraj','ntime'))
+olat = fo.createVariable('lat', 'f4',('ntraj','ntime'))
+otim = fo.createVariable('ttim', 'f4',('ntraj','ntime'))
+oxis = fo.createVariable('xis', 'f4',('ntraj','ntime'))
+oyjs = fo.createVariable('yjs', 'f4',('ntraj','ntime'))
+icbn = fo.createVariable('icbn', 'f4',('ntraj'))
+olon[:,:] = lons
+olat[:,:] = lats
+otim[:,:] = tims
+oxis[:,:] = xis
+oyjs[:,:] = yjs
+icbn[:] = icu
+fo.close()
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/python/increments_gen.py
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/python/increments_gen.py	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/python/increments_gen.py	(revision 5075)
@@ -0,0 +1,93 @@
+'''
+Generate a test increments file
+and the SlaReference file
+
+Requires coordinates and depth file
+
+D. J. Lea   Sep 2014
+'''
+
+import netCDF4
+import numpy as np
+
+# example files to get lon and lat
+exdir='/hpc/data/nwp/ofrd/frld/FORCING/ORCA2_LIM_nemo_v3.6'
+exfile1='coordinates.nc'
+
+infile1=exdir+'/'+exfile1
+fileid=netCDF4.Dataset(infile1, mode='r')
+nav_lon=fileid.variables['nav_lon'][:,:]
+nav_lat=fileid.variables['nav_lat'][:,:]
+fileid.close
+
+print np.shape(nav_lon)
+
+exfile2='data_1m_potential_temperature_nomask.nc'
+infile2=exdir+'/'+exfile2
+fileid=netCDF4.Dataset(infile2, mode='r')
+nav_lev=fileid.variables['depth'][:]
+fileid.close()
+
+nshp=np.shape(nav_lon)
+ny=nshp[0]
+nx=nshp[1]
+nz=np.size(nav_lev)
+nt=1
+
+#create a new file
+outdir='.'
+outfile='assim_background_increments_test.nc'
+
+print "creating: ",outfile
+ncfile=netCDF4.Dataset(outdir+'/'+outfile, mode='w', format='NETCDF3_CLASSIC')
+ncfile.createDimension('x',nx)
+ncfile.createDimension('y',ny)
+ncfile.createDimension('z',nz)
+ncfile.createDimension('t',size=0)
+ncnav_lat = ncfile.createVariable('nav_lat','f4',('y','x'))
+ncnav_lat[:,:]=nav_lat
+ncnav_lon = ncfile.createVariable('nav_lon','f4',('y','x'))
+ncnav_lon[:,:]=nav_lon
+ncnav_lev = ncfile.createVariable('nav_lev','f4',('z'))
+ncnav_lev[:]=nav_lev
+ncvar = ncfile.createVariable('bckineta','f8',('t','y','x'))
+ncvar[0,:,:]=0.1
+ncvar = ncfile.createVariable('bckins','f8',('t','z','y','x'))
+ncvar[0,:,:,:]=0.1
+ncvar = ncfile.createVariable('bckint','f8',('t','z','y','x'))
+ncvar[0,:,:,:]=0.1
+ncvar = ncfile.createVariable('bckinu','f8',('t','z','y','x'))
+ncvar[0,:,:,:]=0.1
+ncvar = ncfile.createVariable('bckinv','f8',('t','z','y','x'))
+ncvar[0,:,:,:]=0.1
+ncvar = ncfile.createVariable('bckinseaice','f8',('t','y','x'))
+ncvar[0,:,:]=0.1
+ncvar = ncfile.createVariable('bckinsshobias','f8',('t','y','x'))
+ncvar[0,:,:]=0.1
+ncvar = ncfile.createVariable('time_counter','f8',('t'))
+ncvar[0]=0
+ncvar = ncfile.createVariable('time','f8')
+ncvar[:]=10101
+ncvar = ncfile.createVariable('z_inc_dateb','f8')
+ncvar[:]=10101
+ncvar = ncfile.createVariable('z_inc_datef','f8')
+ncvar[:]=10102
+
+
+ncfile.close()
+
+#create sla reference file
+outfile='slaReferenceLevel_test.nc'
+
+print "creating: ",outfile
+ncfile=netCDF4.Dataset(outdir+'/'+outfile, mode='w', format='NETCDF3_CLASSIC')
+ncfile.createDimension('x',nx)
+ncfile.createDimension('y',ny)
+ncnav_lat = ncfile.createVariable('nav_lat','f4',('y','x'))
+ncnav_lat[:,:]=nav_lat
+ncnav_lon = ncfile.createVariable('nav_lon','f4',('y','x'))
+ncnav_lon[:,:]=nav_lon
+ncvar = ncfile.createVariable('sossheig','f4',('y','x'),fill_value=1e20)
+ncvar[:,:]=0.01
+
+ncfile.close()
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/date_utils.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/date_utils.F90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/date_utils.F90	(revision 5075)
@@ -34,4 +34,36 @@
 
    END SUBROUTINE add_date
+
+
+   SUBROUTINE add_days_to_date(initial_date,days,final_date)
+
+      ! Add a number of days to initial_date and return it in final_date
+
+      IMPLICIT NONE
+
+
+      !! Arguments
+      INTEGER,INTENT(in) :: initial_date ! Initial date (YYYYMMDD)
+      INTEGER,INTENT(in) :: days         ! Number of days to add
+      INTEGER,INTENT(out) :: final_date  ! Final date (YYYYMMDD)
+
+      !! Local variables
+
+      INTEGER :: isec,imin,ihours,iyear,imon,iday ! temporary results
+      REAL(dp):: juld
+
+		! Account for lack of hours in date format (initial_date*100)
+      CALL split_date(initial_date*100,iyear,imon,iday,ihours)
+
+      CALL greg2jul(0,0,ihours,iday,imon,iyear,juld)
+
+      juld=juld+REAL(days)
+
+      CALL jul2greg(isec,imin,ihours,iday,imon,iyear,juld)
+
+      final_date=(iyear*1000000+imon*10000+iday*100+ihours)/100
+
+   END SUBROUTINE add_days_to_date
+
 
    SUBROUTINE split_date(iyyyymmddhh,iyyyy,imm,idd,ihh)
@@ -379,4 +411,72 @@
    END FUNCTION diffdate
 
+   INTEGER FUNCTION difftime(itime1,itime2)
+
+      ! Compute difference in minutes between times
+      ! Assumes HHMM or HMM or MM or M format for dates
+		!
+		! ORDER MATTERS - itime1 is ealier time
+		! Result is an integer number of minutes
+
+      IMPLICIT NONE
+      INTEGER, INTENT(IN) :: itime1,itime2    ! Times to be diffed.
+      INTEGER :: imin1, imin2, ihr1, ihr2
+
+		ihr1 = (itime1/100)
+		ihr2 = (itime2/100)
+		
+		imin1 = (itime1 - ihr1*100) + (60 * ihr1)
+		imin2 = (itime2 - ihr2*100) + (60 * ihr2)
+		
+		! Assume that itime2 is later, so wrap around midnight if necessary.
+		IF (imin2 < imin1) THEN
+			imin2 = imin2 + 24*60
+		END IF
+		
+		difftime = imin2 - imin1
+		
+   END FUNCTION difftime
+
+
+   INTEGER FUNCTION add_mins_to_time(itime1, imin_add)
+
+      ! Add number of minutes onto given time
+      ! Assumes time in HHMM or HMM or MM or M format
+		!
+		! Result is in HHMM format
+
+      IMPLICIT NONE
+      INTEGER, INTENT(IN) :: itime1,imin_add
+      INTEGER :: imin1, ihr1, imin2, ihr2
+
+		ihr1 = (itime1/100)
+		
+		! itime1 in minutes from previous midnight
+		imin1 = (itime1 - ihr1*100) + (60 * ihr1)
+		
+		imin1 = imin1 + imin_add
+		
+		! Add 1day if time went nagative
+		IF (imin1 < 0) THEN
+			imin1 = imin1 + 24*60
+		END IF
+		
+		! Turn number of minutes back into HHMM
+		ihr2 = imin1/60
+		imin2 = imin1 - ihr2*60
+
+		DO
+			IF (ihr2<0) THEN
+				ihr2 = ihr2 + 24
+			ELSE IF (ihr2>=24) THEN
+				ihr2 = ihr2 - 24
+			END IF
+			IF ((ihr2>=0).OR.(ihr2<24)) EXIT
+		END DO
+
+		add_mins_to_time = ihr2*100 + imin2
+	
+   END FUNCTION add_mins_to_time
+
 
 END MODULE date_utils
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/fbgenerate.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/fbgenerate.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/fbgenerate.F90	(revision 5075)
@@ -0,0 +1,327 @@
+PROGRAM fbgenerate
+   !!---------------------------------------------------------------------
+   !!
+   !!                     ** PROGRAM fbmatchup **
+   !!
+   !!  ** Purpose : Generate a feedback file of pseudo obs
+   !!
+   !!  ** Method  : Use of utilities from obs_fbm.
+   !!
+   !!  ** Action  : Read in data from a namelist file and generate a feedback
+   !!               file of pseudo observations
+   !! 
+   !!   Usage: 		For any parameter, if 3 values are given, these will be treated as
+   !!                   bounds (start, stop, step), EXCEPT when only 3 values are expected.
+   !!
+   !!                For spatial coord, date and time
+	!! 						3 values with nlat=3 will be treated as three separate values
+	!! 						3 values with nobs=3 will be treated as three separate values
+	!! 						3 values with nobs>3 will be treated as a start, end and step
+	!! 						Giving a FillValue in one of namelist entries may have unexpected consequences
+	!! 							e.g., discarding rest of list of values
+	!!
+	!! 					For time bounds, start(HHMM), end(HHMM), step(minutes)
+	!!						For date bounds, start(YYYYMMDD), end(YYYYMMDD), step(days)
+   !!
+   !!                To split obs evenly in time, date and time should be given two values 
+   !!                describing the start and end times. 
+   !!
+   !!                Can use logical flag to shuffle timestamps to remove position-time correlation.
+   !!
+   !!                Can use logical flag to add uniformly sampled perturbation (up to defined limit) to positions
+	!!
+	!! 					For obs values, can list either single value for all (x,y,z)
+	!! 					or can specify single profile for all (x,y)
+	!! 					or can specify all values 1 profile after another.
+	!!	 					
+	!! 					In namelist to set vals(nlev,nobs,nvar)
+	!! 						set all obs (for variable 1) at all levels to one value
+	!! 							vals(:,:,1)= 1.0
+	!! 						set all obs (for variable 2) at all levels to one value
+	!! 							vals(:,:,2)= 35.0
+	!! 						set one profile (for variable 1), apply to all	
+	!! 							vals(:,:,1)= 1.0, 2.0, 3.0, 4.0
+	!! 						set all profiles profile (for variable 1)	
+	!! 							vals(:,1,1)= 1.0, 2.0, 3.0, 4.0
+	!! 							vals(:,2,1)= 1.0, 2.0, 3.0, 4.0
+	!! 							vals(:,nobs,1)= 1.0, 2.0, 3.0, 4.0
+   !!     
+   !!
+   !!   Limitations: Uses an allocatable array in a namelist. This is not meant 
+	!!                 to be allowed in F95, but it works when compiled with xlf90_r
+	!!                 (and is allowed in Fortran2003).
+	!!
+	!!                Forces same depth levels on all profiles.
+	!!
+   !!   History :
+   !!        ! 2014    (J. Waters) Initial version
+   !!        ! 2014-02 (R. King)   Adapted for profiles and bounds on vars
+   !!----------------------------------------------------------------------
+   USE obs_fbm
+	USE fbgenerate_coords
+	USE test_fbgenerate
+   IMPLICIT NONE
+   TYPE(obfbdata) :: fbobsdata
+   CHARACTER(len=256) :: filenameout
+#ifndef NOIARGCPROTO
+   INTEGER,EXTERNAL :: iargc
+#endif
+   INTEGER :: nobs, nvar, nlev, ntyp, nadd, next, lgrid, ierr, nlats, nlons
+   INTEGER :: i, j
+   INTEGER :: FillValue_int
+	REAL(KIND=fbdp) :: FillValue_real
+   INTEGER, ALLOCATABLE :: dates(:), times(:)
+   REAL(KIND=fbdp), ALLOCATABLE :: julian_dates(:)
+	REAL(KIND=fbdp) :: phys_spacing, lat_step, current_lat, perturb_limit
+   REAL(KIND=fbdp), ALLOCATABLE :: lats(:), lons(:), deps(:), vals(:,:,:), model_vals(:,:,:) 
+   CHARACTER(LEN=ilenwmo) :: cdwmo, cdtyp
+   CHARACTER(LEN=ilenwmo), ALLOCATABLE :: variable(:)
+	CHARACTER(LEN=ilenlong), ALLOCATABLE :: variable_longname(:)
+	CHARACTER(LEN=ilenunit), ALLOCATABLE :: variable_units(:)
+	LOGICAL, PARAMETER :: test_prog = .FALSE.
+	LOGICAL :: ln_listobs, ln_physpace, ln_gridobs, ln_shuffletimes, ln_perturb_posn
+   REAL(KIND=fbdp), PARAMETER :: earth_radius = 6371.0_fbdp
+   REAL(KIND=fbdp), PARAMETER :: pi = 3.14159_fbdp
+	
+	!!!! set up default values and read in namelist namfbgen.in !!!!!!!!!!!!!!!!!!!!
+   NAMELIST/namfbgeneratesetup/ln_listobs,ln_physpace,ln_gridobs,ln_shuffletimes,ln_perturb_posn,perturb_limit,nobs,nlats,nlons,phys_spacing,nlev,nvar,nadd
+   NAMELIST/namfbgenerate/ntyp,lats,lons,deps,times,dates,vals,model_vals,variable,variable_longname,variable_units,cdwmo,cdtyp
+
+	IF (test_prog) THEN
+		WRITE(*,*) "In test mode:"
+		CALL tester
+	ELSE
+	
+   
+	IF (iargc()/=1) THEN
+      WRITE(*,*)'Usage:'
+      WRITE(*,*)'fbgenerate <output filename>'
+      CALL abort
+   ENDIF
+
+   CALL getarg(1,filenameout)
+	
+   ! set up default values for namfbgeneratesetup
+   ln_listobs=.FALSE.
+   ln_physpace=.FALSE.
+   ln_gridobs=.FALSE.
+   ln_shuffletimes=.FALSE.
+   ln_perturb_posn=.FALSE.
+   nobs=0
+   nlats=0
+   nlons=0
+   phys_spacing =100.0_fbdp
+   nlev=0
+	nvar=0
+
+   ! Read in number of obs and number of depths from namelist (before reading other variables)
+	FillValue_real = 99999.0_fbdp
+	FillValue_int = 99999
+   OPEN(10,file='namfbgen.in')
+   READ(10,namfbgeneratesetup) 
+   CLOSE(10)
+   
+   ! Calculate number of observations
+   IF ((ln_gridobs) .AND. (.NOT.ln_physpace) .AND. (.NOT.ln_listobs)) THEN
+      IF( ( nlats .LE. 0 ) .OR. (nlons .LE. 0) )THEN
+         WRITE(6,*)'ERROR: nlats and nlons must be greater than 0 if ln_gridobs set'
+      ELSE
+         nobs=nlats*nlons
+         WRITE(*,*) "Constructing a grid of lat-lons"
+      ENDIF
+
+   ELSE IF ((.NOT.ln_gridobs) .AND. (ln_physpace) .AND. (.NOT.ln_listobs)) THEN
+      IF ((phys_spacing .LE. 0) .OR.(phys_spacing .GE. earth_radius)) THEN
+         WRITE(6,*)'ERROR: phys_spacing must be greater than 0 and less than 6371km.'
+      ELSE
+        nlats = INT(pi * earth_radius / phys_spacing)
+        IF (MOD(nlats,2)==0) nlats=nlats-1   ! Ensure nlats is odd to have even number around equator.  
+        lat_step = 180.0_fbdp / (nlats-1)
+        nobs=0
+        current_lat=0.0_fbdp
+        ! Sum up number of lons at each latitude
+        DO i=1,(nlats-1)/2
+           current_lat = current_lat + lat_step * (pi/180.0_fbdp)
+           nobs = nobs + INT(2.0_fbdp * pi * earth_radius * cos(current_lat) / phys_spacing) 
+        END DO
+        nobs = nobs * 2 + INT(2.0_fbdp * pi * earth_radius / phys_spacing)
+        WRITE(*,*) "Using a physical seperation of ~", INT(phys_spacing),"km"
+      END IF
+
+   ELSE IF ((.NOT.ln_gridobs) .AND. (.NOT.ln_physpace) .AND. (ln_listobs)) THEN
+      IF( nobs .LE. 0 ) THEN
+         WRITE(6,*)'ERROR: nobs must be greater than 0'
+      ENDIF
+      WRITE(*,*) "Constructing a list of lat-lons"
+   ELSE
+      WRITE(*,*)'ERROR: one (and only one) of the logical flags must be true!'
+      CALL abort 
+   ENDIF
+
+
+   ALLOCATE(dates(nobs),       	&
+	    		times(nobs),       	&
+	    		julian_dates(nobs),  &
+	    		lats(nobs),	       	&
+	    		lons(nobs),	       	&
+	    		deps(nlev),        	&
+	    		variable(nvar),    	&
+	    		variable_longname(nvar),   &
+	    		variable_units(nvar),&
+	    		vals(nlev,nobs,nvar),&
+	    		model_vals(nlev,nobs,nvar),&
+				STAT=ierr          	&
+	    		)
+	IF (ierr /= 0) THEN
+		WRITE(*,*) "Could not allocate observation arrays:"
+		WRITE(*,*) "dates(", nobs, ")"
+		WRITE(*,*) "times(", nobs, ")"
+		WRITE(*,*) "lats(", nobs, ")"
+		WRITE(*,*) "lons(", nobs, ")"
+		WRITE(*,*) "deps(", nlev, ")"
+		WRITE(*,*) "variable(", nvar, ")"
+		WRITE(*,*) "variable_longname(", nvar, ")"
+		WRITE(*,*) "variable_units(", nvar, ")"
+		WRITE(*,*) "vals(", nlev, nobs, nvar, ")"
+		WRITE(*,*) "model_vals(", nlev, nobs, nvar, ")"
+
+		CALL abort
+	END IF			    
+	    
+		 
+   !!!! set up default values and read in namelist namfbgen.in !!!!!!!!!!!!!!!!!!!!
+   ntyp=-1
+   lats(:) = FillValue_real
+   lons(:) = FillValue_real
+   deps(:) = FillValue_real
+   times(:) = FillValue_int
+   dates(:) = FillValue_int
+   vals(:,:,:) = FillValue_real
+   model_vals(:,:,:) = FillValue_real
+   variable=REPEAT('X',ilenwmo)
+   variable_longname=REPEAT('X',ilenwmo)
+   variable_units=REPEAT('X',ilenwmo)
+   cdwmo=REPEAT('X',ilenwmo)  !station identifier
+   cdtyp="90"    !station type
+
+   WRITE(*,*) "Creating a fdbk file with", nobs, "observations"
+   WRITE(*,*) "with", nvar, "variables and",nlev, "depths."
+
+   OPEN(10,file='namfbgen.in')
+   READ(10,namfbgenerate)
+   CLOSE(10)
+	
+	! Use bounds to construct the full arrays of coords and values
+
+   IF (ln_physpace) THEN
+      CALL set_spatial_coords_physpace(lats,lons,nobs,FillValue_real,phys_spacing)
+   ELSE IF (ln_gridobs) THEN
+      CALL set_spatial_coords_grid(lats,lons,nobs,nlats,nlons,FillValue_real)
+   ELSE
+      CALL set_spatial_coords(lats,lons,nobs,FillValue_real)
+   END IF
+   
+   ! Add random perturbation to position if ln_perturb_posn=.TRUE.   
+   IF (ln_perturb_posn) CALL perturb_positions(lats,lons,perturb_limit)
+   
+   CALL set_datetime(dates,times,julian_dates,nobs,FillValue_int)
+   CALL set_depths(deps,nlev,FillValue_real)
+   CALL set_obs_values(vals,nvar,nobs,nlev,FillValue_real)
+   CALL set_obs_values(model_vals,nvar,nobs,nlev,FillValue_real)
+
+
+   !nadd=1	! Hx
+   next=0	! e.g. TEMP 
+	! Add TEMP as extra variable if POTM is defined.
+	DO i=1,nvar
+		IF (variable(i)(1:4) == "POTM") THEN
+		   next=1	! e.g. If set to zero, will not add extra TEMP variable			
+			EXIT
+		END IF
+	END DO
+
+   CALL init_obfbdata(fbobsdata)
+   
+   !!!! Allocate the obfb type !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+   
+   CALL alloc_obfbdata( fbobsdata, nvar, nobs, nlev, nadd, next, .FALSE.)
+   
+   !!!! Read data specified in the namelist into obfd type!!!!!!!!!!!!!!!
+	    
+   fbobsdata%cname = variable(:)
+	fbobsdata%coblong = variable_longname(:)
+	fbobsdata%cobunit = variable_units(:)
+   fbobsdata%cdjuldref = "19500101000000"
+   fbobsdata%cdwmo = cdwmo
+   fbobsdata%cdtyp = cdtyp
+	
+   ! Add model counterpart values if nadd=1
+	IF (nadd > 0) THEN
+		IF (nadd /= 1) THEN
+			CALL abort
+			WRITE(*,*) "Not set-up to add more than 1 additional variable."
+		ELSE
+			fbobsdata%caddname = "Hx"
+   		fbobsdata%caddlong(1,:) = "Model interpolated " // variable_longname(:)
+   		fbobsdata%caddunit(1,:) = variable_units(:)
+         fbobsdata%padd(:,:,1,:)=model_vals(:,:,:)
+		END IF
+	END IF
+	
+	! Add TEMP as extra variable if POTM is defined.
+	IF (next==1) THEN
+		fbobsdata%cextname = "TEMP"
+	END IF
+	
+   ! set up pos/time variables
+   fbobsdata%plam(:)=lons(:)
+   fbobsdata%pphi(:)=lats(:)
+	DO i=1,nobs 
+      fbobsdata%pdep(:,i)=deps(:)
+   END DO
+
+   
+   fbobsdata%ptim(:)= julian_dates(:)
+   
+   ! Shuffle the time array to spread the profiles across the time period
+   IF (ln_shuffletimes) CALL shuffle(fbobsdata%ptim)
+
+   ! read in variable data and flags
+   fbobsdata%ivqc(:,:)=1
+   fbobsdata%ivqcf(:,:,:)=1
+   fbobsdata%ivlqc(:,:,:)=1
+   fbobsdata%pob(:,:,:)=vals(:,:,:)
+
+   !set up all QC flags
+   fbobsdata%ioqc(:)=1
+   fbobsdata%ioqcf(:,:)=0
+   fbobsdata%ipqc(:)=1  
+   fbobsdata%ipqcf(:,:)=0 
+   fbobsdata%idqc(:,:)=1		!0
+   fbobsdata%idqcf(:,:,:)=0
+   fbobsdata%itqc(:)=1
+   fbobsdata%kindex(:)=0
+   
+   !!!! Write out the obfb type !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+	
+   CALL write_obfbdata(TRIM(filenameout),fbobsdata)
+
+   DEALLOCATE(dates,       &
+              times,       &
+              julian_dates,&
+	    		  lats,	      &
+	    		  lons,	      &
+	    		  deps,        &
+	    		  variable,    &
+	    		  variable_longname,    &
+	    		  variable_units,       &
+	    		  vals,        &
+	    		  model_vals   &
+	    		  )
+
+	END IF !test prog
+
+
+END PROGRAM fbgenerate
+
+
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/fbgenerate_coords.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/fbgenerate_coords.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/fbgenerate_coords.F90	(revision 5075)
@@ -0,0 +1,509 @@
+MODULE fbgenerate_coords
+USE obs_fbm
+USE date_utils
+
+CONTAINS
+
+   REAL(KIND=fbdp) FUNCTION fb_dates(timein,datein) 
+      IMPLICIT NONE   
+      INTEGER, INTENT(IN) :: timein 	! Format: HHMM
+		INTEGER, INTENT(IN) :: datein 	! Format: YYYYMMDD
+      INTEGER :: iyea,imon,iday
+      INTEGER :: ihr,imin,isec
+  
+      iyea=datein/10000
+      imon=datein/100-iyea*100
+      iday=datein-iyea*10000-imon*100
+		
+		ihr = timein/100
+		imin = timein - ihr*100
+		isec = 0
+		
+      CALL greg2jul(isec,imin,ihr,iday,imon,iyea,fb_dates)
+   
+   END FUNCTION fb_dates
+
+
+
+	SUBROUTINE set_spatial_coords(lats,lons,n,FillVal)
+	IMPLICIT NONE	
+	INTEGER :: i, j, k, p, nlats, nlons, nlats_in_list, nlons_in_list
+	INTEGER, INTENT(IN) :: n
+	REAL(KIND=fbdp), INTENT(INOUT) :: lats(:), lons(:)
+	REAL(KIND=fbdp) :: FillVal 
+	
+	! A single non-FillVal value should be replicated n times
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	!	unless n is three, in which case treat as list, not bounds.
+	! A full list of n non-FillVals should be left unaltered.
+	
+	!Find number of lats and lons
+	! by finding number of non-FillVal entries in arrays
+	! and expanding bounds if necessary
+	
+	nlats_in_list = last_element(lats,FillVal)
+	nlons_in_list = last_element(lons,FillVal)
+
+   !Expand bounds only if 3 values given and number obs>3
+	IF (nlats_in_list == 1) THEN
+		lats(1:nlats) = lats(1)
+	ELSE IF ((nlats_in_list==3).AND.((n>3))) THEN ! Treat as list of three, not bounds
+		CALL expand_bounds(lats, FillVal)
+	END IF
+
+	IF (nlons_in_list == 1) THEN
+		lons(1:nlons) = lons(1)
+	ELSE IF ((nlons_in_list==3).AND.((n>3))) THEN ! Treat as list of three, not bounds
+		CALL expand_bounds(lons, FillVal)
+	END IF
+
+	nlats = last_element(lats,FillVal)
+	nlons = last_element(lons,FillVal)
+	
+	IF ((n /= nlats) .AND. (n /= nlons)) THEN
+		WRITE(*,*) "ERROR: Number of lat/lons not equal to nobs", nlats, nlons, n
+		CALL abort	
+	END IF
+	
+	END SUBROUTINE set_spatial_coords
+
+
+	SUBROUTINE set_spatial_coords_grid(lats,lons,n,nlats,nlons,FillVal)
+	IMPLICIT NONE	
+	INTEGER :: i, j, k, p, nlats_in_list, nlons_in_list
+	INTEGER, INTENT(IN) :: n, nlats, nlons
+	REAL(KIND=fbdp), INTENT(INOUT) :: lats(:), lons(:)
+	REAL(KIND=fbdp), ALLOCATABLE :: tmp_lats(:), tmp_lons(:)
+	REAL(KIND=fbdp) :: FillVal 
+	
+	! A single non-FillVal value should be replicated n times
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	!	unless n is three, in which case treat as list, not bounds.
+	! A full list of n non-FillVals should be left unaltered.
+	
+	!Find number of lats and lons in list
+	! by finding number of non-FillVal entries in arrays
+	! and then expand bounds if necessary
+	
+	nlats_in_list = last_element(lats,FillVal)
+	nlons_in_list = last_element(lons,FillVal)
+	
+   !Expand bounds only if 3 values given and number lats (or lons) not equal to 3
+	IF (nlats_in_list == 1) THEN
+		lats(1:nlats) = lats(1)
+	ELSE IF ((nlats_in_list==3).AND.((nlats>3))) THEN ! Treat as bounds
+		CALL expand_bounds(lats, FillVal)
+	END IF
+
+	IF (nlons_in_list == 1) THEN
+		lons(1:nlons) = lons(1)
+	ELSE IF ((nlons_in_list==3).AND.((nlons>3))) THEN ! Treat as bounds
+		CALL expand_bounds(lons, FillVal)
+	END IF
+
+	nlats_in_list = last_element(lats,FillVal)
+	nlons_in_list = last_element(lons,FillVal)
+
+
+	IF ((nlats_in_list * nlons_in_list) == n) THEN
+		ALLOCATE(tmp_lons(n))
+		ALLOCATE(tmp_lats(n))
+		k = 0
+		p = 0
+		DO i = 1, nlats
+		   p = p + 1
+			DO j = 1, nlons
+				k = k + 1
+				tmp_lons(k) = lons(j)   
+				tmp_lats(k) = lats(p)   
+			END DO
+		END DO
+		lats(:) = tmp_lats(:)
+		lons(:) = tmp_lons(:)
+		DEALLOCATE(tmp_lons)
+		DEALLOCATE(tmp_lats)
+	ELSE 
+		WRITE(*,*) 
+		WRITE(*,*) "ERROR: Number of lat * lon values not equal to nobs", nlats_in_list, nlons_in_list, n
+		CALL abort	
+	END IF
+	
+	END SUBROUTINE set_spatial_coords_grid
+
+
+	SUBROUTINE set_spatial_coords_physpace(lats,lons,n,FillVal,phys_spacing)
+	IMPLICIT NONE	
+	INTEGER :: i, j, k, nlats, nlons
+	INTEGER, INTENT(IN) :: n
+	REAL(KIND=fbdp), INTENT(INOUT) :: lats(:), lons(:)
+	REAL(KIND=fbdp), ALLOCATABLE :: tmp_lats(:)
+	REAL(KIND=fbdp) :: FillVal 
+   REAL(KIND=fbdp), PARAMETER :: earth_radius = 6371.0_fbdp ! km
+   REAL(KIND=fbdp), PARAMETER :: pi = 3.141592654_fbdp
+	REAL(KIND=fbdp), INTENT(IN) :: phys_spacing
+   REAL(KIND=fbdp) :: lat_step
+	
+	! Use physical spacing to set lats and lons
+
+   nlats = INT(pi * earth_radius / phys_spacing)
+   IF (MOD(nlats,2)==0) nlats=nlats-1   ! Ensure nlats is odd to have even number around equator.  
+      
+   ALLOCATE(tmp_lats(nlats))
+
+   lat_step = 180.0_fbdp / (nlats-1)
+
+   tmp_lats(1) = 0.0_fbdp
+   DO i=1,(nlats-1)/2
+      tmp_lats(i+1) = tmp_lats(i) + lat_step
+      tmp_lats(((nlats-1)/2)+i+1) = tmp_lats(i+1) * (-1.0_fbdp)
+   END DO
+
+   k = 0
+   DO i=1,nlats
+      nlons = INT(2.0_fbdp * pi * earth_radius * cos(tmp_lats(i)* (pi/180.0_fbdp)) / phys_spacing)
+      IF (nlons>0) THEN
+         DO j = 1, nlons
+            k = k + 1
+            lons(k) = REAL(j-1) * 360.0_fbdp / nlons
+            lats(k) = tmp_lats(i)
+         END DO
+      END IF
+   END DO
+   DEALLOCATE(tmp_lats)
+	
+	END SUBROUTINE set_spatial_coords_physpace
+
+
+	SUBROUTINE expand_bounds(array, fillval)
+	!
+	! Checks if there are three entries and expands bounds.
+	!
+	IMPLICIT NONE
+	INTEGER :: i, nentries
+	REAL(KIND=fbdp), INTENT(INOUT) :: array(:)
+	REAL(KIND=fbdp), INTENT(IN) :: fillval
+	REAL(KIND=fbdp) :: nsteps, start, step
+
+	! Find number of elements given in list
+	nentries = last_element(array, fillval)
+
+	IF (nentries==3) THEN 			! Bounds given	
+		nsteps = (array(2) - array(1)) /  array(3) 
+	   IF ((array(2) < array(1)) .AND. (array(3) >= 0.0)) THEN
+		   WRITE(*,*) "Error: if upper bound is less than lower bound, step must be negative.", array
+			CALL abort
+		ELSE IF ( NINT(nsteps)+1 > SIZE(array) ) THEN
+		   WRITE(*,*) "Error: bounds not compatible with length of array.", array
+		   WRITE(*,*) "Error: bounds not compatible with length of array.", nsteps
+			CALL abort
+		END IF
+		start = array(1) 
+		step = array(3)
+		DO i=1,NINT(nsteps)+1
+			array(i) = start + (i-1)*step 	   	
+		END DO
+	END IF
+	
+	END SUBROUTINE expand_bounds
+
+
+
+	INTEGER FUNCTION last_element(array,fillval)
+	!
+	! Returns index of the last non-fill value element in a list
+	! Will return 1, even in first element is the FillValue
+	!
+	IMPLICIT NONE
+	REAL(KIND=fbdp), INTENT(IN) :: array(:), fillval
+	INTEGER :: i
+
+	last_element = 1
+	IF (SIZE(array) > 1) THEN
+		DO i=2, SIZE(array)
+			IF (array(i) /= fillval) THEN 
+				last_element = i
+			END IF
+		END DO
+	END IF
+		
+	END FUNCTION last_element
+
+
+
+	SUBROUTINE set_depths(array,n,FillVal)
+	IMPLICIT NONE	
+	INTEGER :: i
+	INTEGER, INTENT(IN) :: n
+	REAL(KIND=fbdp), INTENT(INOUT) :: array(:)
+	REAL(KIND=fbdp) :: FillVal
+	REAL(KIND=fbdp) :: start, step, nstep
+	! Top bound not necessarily inclusive - will use start, step and number of obs
+	
+	! A single non-FillVal value should be replicated n times
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	!	unless n is three, in which case treat as list, not bounds.
+	! A full list of n non-FillVals should be left unaltered.
+	IF (n==1) THEN
+		array(:) = array(1)
+	ELSE IF ((n > 1) .AND. (array(2)==FillVal)) THEN
+		array(:) = array(1)
+	ELSE IF ((n==2) .AND. (array(2)/=FillVal)) THEN
+		array(:) = array(:)
+	ELSE IF (n==3) THEN ! Treat as list of three, not bounds
+		array(:) = array(:)
+	ELSE IF ((n>=4) .AND. (array(4)==FillVal)) THEN ! Assume start, stop, step
+		nstep = (array(2) - array(1)) /  array(3) 
+	   IF ((array(2) < array(1)) .AND. (array(3) >= 0.0)) THEN
+		   WRITE(*,*) "Error: if upper bound is less than lower bound, step must be negative.", array
+			CALL abort
+		ELSE IF ( ( nstep < (0.99 * real(n-1)) ) .OR. &
+		          ( nstep > (1.01 * real(n-1)) ) ) THEN
+		   WRITE(*,*) "Error: depth bounds not compatible.", array
+		   WRITE(*,*) "Error: depth bounds not compatible.", nstep
+			CALL abort
+		END IF
+		start = array(1) 
+		step = array(3)
+		DO i=1,n
+			array(i) = start + (i-1)*step 	   	
+		END DO
+	END IF
+	
+	END SUBROUTINE set_depths
+
+
+
+
+
+	SUBROUTINE set_datetime(date,time,julian_date,n,FillVal)
+	!
+	! Transform input array from m values describing n dates to a list of n dates.
+	!
+	IMPLICIT NONE	
+	INTEGER :: i
+	INTEGER, INTENT(IN) :: n
+	INTEGER, INTENT(INOUT) :: date(:), time(:)
+	INTEGER :: FillVal
+	REAL(KIND=fbdp), INTENT(INOUT) :: julian_date(:)
+	REAL(KIND=fbdp) :: start, step, finish
+
+   ! Check if user has supplied start and end times to be split amongst number of obs
+   ! (i.e. more than 2 obs, but only 2 dates and 2 times given.)
+   IF ((n>2) .AND. (date(2)/=FillVal) .AND. (date(3)==FillVal) &
+      &      .AND. (time(2)/=FillVal) .AND. (time(3)==FillVal)) THEN
+      
+      !work out JD of each
+      start = fb_dates(time(1),date(1)) 
+      finish = fb_dates(time(2),date(2)) 
+
+      ! use info to calc step
+      step = ( finish - start ) / n
+      ! calc all JDs and put output in dates
+      DO i=1,n 
+	      ! Could make this an elemental function if dateutils were pure funcs
+         julian_date(i)= start + (i-1)*step
+      END DO
+
+   ELSE
+      CALL set_date(date,n,FillVal)
+      CALL set_time(time,n,FillVal)
+      ! Replace dates with JD including time info
+      DO i=1,n 
+	      ! Could make this an elemental function if dateutils were pure funcs
+         julian_date(i)= fb_dates(time(i),date(i))
+      END DO
+   END IF
+
+
+	END SUBROUTINE set_datetime
+
+
+	SUBROUTINE set_date(array,n,FillVal)
+	!
+	! Transform input array from m values describing n dates to a list of n dates.
+	!
+	IMPLICIT NONE	
+	INTEGER :: i
+	INTEGER, INTENT(IN) :: n
+	INTEGER, INTENT(INOUT) :: array(:)
+	INTEGER :: FillVal
+	INTEGER :: start, step, diff
+	! Top bound not necessarily inclusive - will use start, step and number of obs
+	
+	! A single non-FillVal value should be replicated n times
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	!	unless n is three, in which case treat as list, not bounds.
+	! A full list of n non-FillVals should be left unaltered.
+	IF (n==1) THEN
+		array(:) = array(1)
+	ELSE IF ((n > 1) .AND. (array(2)==FillVal)) THEN
+		array(:) = array(1)
+	ELSE IF ((n==2) .AND. (array(2)/=FillVal)) THEN
+		array(:) = array(:)
+	ELSE IF (n==3) THEN ! Treat as list of three, not bounds
+		array(:) = array(:)
+	ELSE IF ((n>=4) .AND. (array(4)==FillVal)) THEN ! Assume start, stop, step
+   	diff = diffdate(array(2),array(1))	! in number of days
+	   IF ((array(2) < array(1)) .AND. (array(3) >= 0)) THEN
+		   WRITE(*,*) "Error: if upper bound is less than lower bound, step must be negative.", array
+			CALL abort
+		ELSE IF ( ( diff / ABS(array(3)) ) /= (n-1) ) THEN
+		   WRITE(*,*) "Error: date bounds not compatible.", array
+			CALL abort
+		END IF
+		start = array(1) 
+		step = array(3)
+		DO i=1,n
+			CALL add_days_to_date(start,(i-1)*step,array(i)) 	   	
+		END DO
+	END IF
+	
+	END SUBROUTINE set_date
+
+
+
+	SUBROUTINE set_time(array,n,FillVal)
+	!
+	! Transform input array from m (m<=n) values describing n times to a list of n times.
+	!
+	IMPLICIT NONE	
+	INTEGER :: i
+	INTEGER, INTENT(IN) :: n
+	INTEGER, INTENT(INOUT) :: array(:)
+	INTEGER :: FillVal
+	INTEGER :: start, step, nstep
+	! Top bound not necessarily inclusive - will use start, step and number of obs
+	
+	! A single non-FillVal value should be replicated n times
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	!	unless n is three, in which case treat as list, not bounds.
+	! A full list of n non-FillVals should be left unaltered.
+	IF (n==1) THEN
+		array(:) = array(1)
+	ELSE IF ((n > 1) .AND. (array(2)==FillVal)) THEN
+		array(:) = array(1)
+	ELSE IF ((n==2) .AND. (array(2)/=FillVal)) THEN
+		array(:) = array(:)
+	ELSE IF (n==3) THEN ! Treat as list of three, not bounds
+		array(:) = array(:)
+	ELSE IF ((n>=4) .AND. (array(4)==FillVal)) THEN ! Assume start, stop, step
+		IF (array(3)<0) nstep = difftime(array(2),array(1)) / ABS(array(3)) 
+		IF (array(3)>=0) nstep = difftime(array(1),array(2)) / ABS(array(3)) 
+		IF ( nstep /= (n-1) ) THEN
+		   WRITE(*,*) "Error: time bounds not compatible.", array
+			CALL abort
+		END IF
+		start = array(1) 
+		step = array(3)
+		DO i=1,n
+			array(i) = add_mins_to_time(start,(i-1)*step) 	   	
+		END DO
+	END IF
+	
+	END SUBROUTINE set_time
+	
+	
+
+	SUBROUTINE set_obs_values(array,p,n,m,FillVal)
+	!
+	! n profiles at m depths
+	!
+	IMPLICIT NONE	
+	INTEGER :: i, j, k
+	INTEGER, INTENT(IN) :: n, m, p
+	REAL(KIND=fbdp), INTENT(INOUT) :: array(:,:,:) 			! (nlevels, nprofiles, nvars) = (m,n,p)
+	REAL(KIND=fbdp) :: FillVal 
+	
+	
+	DO k=1,p
+	   IF ((k > 1) .AND. (array(1,1,k) == FillVal)) THEN  ! set to same values as first variable
+			array(:,:,k) = array(:,:,1)
+		ELSE
+			IF ((n==1).AND.(m==1)) THEN
+				array(:,:,k) = array(1,1,k)
+
+			! If mult depths, but not specified, set all to one value	
+			ELSE IF ((m > 1) .AND. (array(2,1,k) == FillVal)) THEN
+				array(:,:,k) = array(1,1,k)
+
+			! If mult profiles and mult depths and only one value set in first profile	
+			ELSE IF ((n > 1) .AND. (m > 1) .AND. (array(2,1,k) == FillVal)) THEN
+				array(:,:,k) = array(1,1,k)
+				
+			! If mult profiles and mult depths and only one first profile set	
+			ELSE IF ((n > 1) .AND. (m > 1) .AND. (array(1,2,k) == FillVal)) THEN
+				DO j=1,m
+					array(j,:,k) = array(j,1,k)
+				END DO
+				
+			ELSE 
+	   		array(:,:,k) = array(:,:,k)
+			END IF
+		END IF
+	END DO	
+	
+	END SUBROUTINE set_obs_values
+
+
+   ! Unbiased shuffle of array
+   SUBROUTINE shuffle(a)
+   REAL(KIND=fbdp), INTENT(INOUT) :: a(:)
+   INTEGER :: i, randpos
+   REAL(KIND=fbdp) :: r, temp
+
+   CALL random_seed()
+   DO i = SIZE(a), 2, -1
+      CALL random_number(r)
+      randpos = int(r * i) + 1
+      temp = a(randpos)
+      a(randpos) = a(i)
+      a(i) = temp
+   END DO
+   
+   END SUBROUTINE shuffle
+   
+   
+   ! Add a random perturbation to the lats and lons
+   ! Perturbation is sampled from a uniform distribution +/-perturb_limit
+   SUBROUTINE perturb_positions(lats,lons,perturb_limit)
+   INTEGER :: i
+   REAL(KIND=fbdp), INTENT(INOUT) :: lats(:), lons(:)
+   REAL(KIND=fbdp), INTENT(IN) :: perturb_limit
+   REAL(KIND=fbdp) :: randpos, lat_perturb, lon_perturb
+   REAL(KIND=fbdp), PARAMETER :: earth_radius = 6371.0_fbdp
+   REAL(KIND=fbdp), PARAMETER :: pi = 3.141592654_fbdp
+   
+ 	IF ( SIZE(lats) /= SIZE(lons) ) THEN
+		WRITE(*,*) "Error: different number of lat and lon elements", SIZE(lats), SIZE(lons)
+		CALL abort
+	END IF
+
+   CALL random_seed()
+   
+   ! Convert physical sep into a latidue sep in degrees
+   lat_perturb = 360.0_fbdp * perturb_limit / (2.0_fbdp * pi * earth_radius)
+   
+   DO i=1,SIZE(lats)
+   
+      ! Perturb lats first, as lon conversion uses lat
+      CALL random_number(randpos)
+      lats(i) = lats(i) + randpos*lat_perturb
+      IF (lats(i) > 90.0_fbdp) lats(i) = 180.0_fbdp - lats(i) 
+      IF (lats(i) < -90.0_fbdp) lats(i) = (lats(i) + 180.0_fbdp) * (-1.0_fbdp)
+      
+      ! Use lat to convert physical size to delta_longitude   
+      IF (ABS(lats(i)) == 90.0_fbdp) THEN 
+         lon_perturb = 0.0_fbdp
+      ELSE
+         lon_perturb = 360.0_fbdp * perturb_limit / (2.0_fbdp * pi * earth_radius * cos(lats(i)*(pi/180.0_fbdp)))
+      END IF
+      CALL random_number(randpos)
+      lons(i) = lons(i) + randpos*lon_perturb
+      IF (lons(i) >= 360.0_fbdp) lons(i) = lons(i) - 360.0_fbdp 
+      IF (lons(i) < 0.0_fbdp) lons(i) = lons(i) + 360.0_fbdp 
+   
+   END DO
+   
+   END SUBROUTINE perturb_positions
+    
+END MODULE fbgenerate_coords
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/ooo_data.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/ooo_data.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/ooo_data.F90	(revision 5075)
@@ -0,0 +1,1 @@
+link ../../../NEMO/OOO_SRC/ooo_data.F90
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/ooo_write.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/ooo_write.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/ooo_write.F90	(revision 5075)
@@ -0,0 +1,1 @@
+link ../../../NEMO/OOO_SRC/ooo_write.F90
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/test_arrays_mod.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/test_arrays_mod.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/test_arrays_mod.F90	(revision 5075)
@@ -0,0 +1,94 @@
+MODULE test_arrays_mod
+USE obs_fbm
+
+INTERFACE test_arrays
+	MODULE PROCEDURE test_real_arrays
+	MODULE PROCEDURE test_real_arrays_2D
+	MODULE PROCEDURE test_real_arrays_3D
+	MODULE PROCEDURE test_integer_arrays
+END INTERFACE test_arrays
+
+CONTAINS
+
+   LOGICAL FUNCTION test_real_arrays(array_in,array_out)
+	IMPLICIT NONE
+	INTEGER :: i
+	REAL(KIND=fbdp) :: array_in(:), array_out(:)
+
+	test_real_arrays=.TRUE.
+	DO i=1,SIZE(array_in)
+		IF (array_in(i) /= array_out(i)) THEN
+			test_real_arrays=.FALSE.
+		END IF
+	END DO
+
+	IF (SIZE(array_in) /= SIZE(array_out)) THEN
+			test_real_arrays=.FALSE.
+	END IF
+
+	END FUNCTION test_real_arrays
+
+
+   LOGICAL FUNCTION test_real_arrays_2D(array_in,array_out)
+	IMPLICIT NONE
+	INTEGER :: i, j
+	REAL(KIND=fbdp) :: array_in(:,:), array_out(:,:)
+
+	test_real_arrays_2D=.TRUE.
+	DO j=1,SIZE(array_in,2)
+		DO i=1,SIZE(array_in,1)
+			IF (array_in(i,j) /= array_out(i,j)) THEN
+				test_real_arrays_2D=.FALSE.
+			END IF
+		END DO
+	END DO
+
+	IF (SIZE(array_in) /= SIZE(array_out)) THEN
+			test_real_arrays_2D=.FALSE.
+	END IF
+
+	END FUNCTION test_real_arrays_2D
+
+
+   LOGICAL FUNCTION test_real_arrays_3D(array_in,array_out)
+	IMPLICIT NONE
+	INTEGER :: i, j, k
+	REAL(KIND=fbdp) :: array_in(:,:,:), array_out(:,:,:)
+
+	test_real_arrays_3D=.TRUE.
+	DO k=1,SIZE(array_in,3)
+		DO j=1,SIZE(array_in,2)
+			DO i=1,SIZE(array_in,1)
+				IF (array_in(i,j,k) /= array_out(i,j,k)) THEN
+					test_real_arrays_3D=.FALSE.
+				END IF
+			END DO
+		END DO
+	END DO
+
+	IF (SIZE(array_in) /= SIZE(array_out)) THEN
+			test_real_arrays_3D=.FALSE.
+	END IF
+
+	END FUNCTION test_real_arrays_3D
+
+
+   LOGICAL FUNCTION test_integer_arrays(array_in,array_out)
+	IMPLICIT NONE
+	INTEGER :: i
+	INTEGER :: array_in(:), array_out(:)
+
+	test_integer_arrays=.TRUE.
+	DO i=1,SIZE(array_in)
+		IF (array_in(i) /= array_out(i)) THEN
+			test_integer_arrays=.FALSE.
+		END IF
+	END DO
+
+	IF (SIZE(array_in) /= SIZE(array_out)) THEN
+			test_integer_arrays=.FALSE.
+	END IF
+
+	END FUNCTION test_integer_arrays
+
+END MODULE test_arrays_mod
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/test_fbgenerate.F90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/test_fbgenerate.F90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/OBSTOOLS/src/test_fbgenerate.F90	(revision 5075)
@@ -0,0 +1,787 @@
+MODULE test_fbgenerate	
+USE obs_fbm
+USE test_arrays_mod
+USE fbgenerate_coords
+
+CONTAINS
+
+   SUBROUTINE tester
+	IMPLICIT NONE
+	REAL(KIND=fbdp) :: array10_in(10), array1_in(1), array2_in(2), array3_in(3)
+	REAL(KIND=fbdp) :: array10_out(10), array1_out(1), array2_out(2), array3_out(3)
+	REAL(KIND=fbdp) :: array_4x3_in(3,4,1), array_4x3_out(3,4,1)
+	REAL(KIND=fbdp), ALLOCATABLE :: lat_array_in(:), lat_array_out(:)
+	REAL(KIND=fbdp), ALLOCATABLE :: lon_array_in(:), lon_array_out(:)
+	INTEGER :: iarray10_in(10), iarray1_in(1), iarray2_in(2), iarray3_in(3)
+	INTEGER :: iarray10_out(10), iarray1_out(1), iarray2_out(2), iarray3_out(3)
+	LOGICAL :: okay = .TRUE.
+	LOGICAL :: okay_too = .TRUE.
+	LOGICAL :: all_okay = .TRUE.
+	INTEGER, PARAMETER :: FV_int = 99999
+	REAL(KIND=fbdp), PARAMETER :: FV_real = 99999.0_fbdp
+	
+   ! A single non-FillVal value should be replicated n times
+	array1_in(:)=(/1.0_fbdp/)
+	array1_out(:)=(/1.0_fbdp/)
+	CALL set_depths(array1_in,1,FV_real)
+	okay = test_arrays(array1_in,array1_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 1 failed"
+		all_okay = .FALSE.
+	END IF
+
+   ! A single non-FillVal value should be replicated n times
+	array2_in(:) = (/1.0_fbdp, FV_real/)
+	array2_out(:) = (/1.0_fbdp, 1.0_fbdp/)
+	CALL set_depths(array2_in,2,FV_real)
+	okay = test_arrays(array2_in,array2_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 2 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A single non-FillVal value should be replicated n times
+	array10_in(:) = (/1.0_fbdp,FV_real,FV_real,FV_real,FV_real,FV_real,FV_real,FV_real,FV_real,FV_real/)
+	array10_out(:) = 1.0_fbdp
+	CALL set_depths(array10_in,10,FV_real)
+	okay = test_arrays(array10_in,array10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 3 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A single non-FillVal value should be replicated n times
+	array3_in(:) = (/1.0_fbdp,FV_real,FV_real/)
+	array3_out(:) = 1.0_fbdp
+	CALL set_depths(array3_in,3,FV_real)
+	okay = test_arrays(array3_in,array3_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 4 failed"
+		all_okay = .FALSE.
+	END IF
+		
+	! A full list of n non-FillVals should be left unaltered.
+	array2_in(:) = (/1.0_fbdp, 2.0_fbdp/)
+	array2_out(:) = (/1.0_fbdp, 2.0_fbdp/)
+	CALL set_depths(array2_in,2,FV_real)
+	okay = test_arrays(array2_in,array2_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 5 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A full list of n non-FillVals should be left unaltered.
+	array3_in(:) = (/3.0_fbdp, 2.0_fbdp, 56.23_fbdp/)
+	array3_out(:) = (/3.0_fbdp, 2.0_fbdp, 56.23_fbdp/)
+	CALL set_depths(array3_in,3,FV_real)
+	okay = test_arrays(array3_in,array3_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 6 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A full list of n non-FillVals should be left unaltered.
+	array10_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, -5.0_fbdp, 5.0_fbdp, 67.0_fbdp, 7.0_fbdp, 8.0_fbdp, 9.0_fbdp, 10.0_fbdp/)
+	array10_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, -5.0_fbdp, 5.0_fbdp, 67.0_fbdp, 7.0_fbdp, 8.0_fbdp, 9.0_fbdp, 10.0_fbdp/)
+	CALL set_depths(array10_in,10,FV_real)
+	okay = test_arrays(array10_in,array10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 7 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	array10_in(:) = (/1.0_fbdp,10.0_fbdp,1.0_fbdp,FV_real,FV_real,FV_real,FV_real,FV_real,FV_real,FV_real/)
+	array10_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp, 6.0_fbdp, 7.0_fbdp, 8.0_fbdp, 9.0_fbdp, 10.0_fbdp/)
+	CALL set_depths(array10_in,10,FV_real)
+	okay = test_arrays(array10_in,array10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 8 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	array10_in(:) = (/1.0_fbdp, 3.25_fbdp, 0.25_fbdp, FV_real,FV_real,FV_real,FV_real,FV_real,FV_real,FV_real/)
+	array10_out(:) = (/1.0_fbdp, 1.25_fbdp, 1.5_fbdp, 1.75_fbdp, 2.0_fbdp, 2.25_fbdp, 2.5_fbdp, 2.75_fbdp, 3.0_fbdp, 3.25_fbdp/)
+	CALL set_depths(array10_in,10,FV_real)
+	okay = test_arrays(array10_in,array10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 9 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	array10_in(:) = (/3.25_fbdp, 1.0_fbdp, -0.25_fbdp, FV_real,FV_real,FV_real,FV_real,FV_real,FV_real,FV_real/)
+	array10_out(:) = (/3.25_fbdp, 3.0_fbdp, 2.75_fbdp, 2.5_fbdp, 2.25_fbdp, 2.0_fbdp, 1.75_fbdp, 1.5_fbdp, 1.25_fbdp, 1.0_fbdp/)
+	CALL set_depths(array10_in,10,FV_real)
+	okay = test_arrays(array10_in,array10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 11 failed"
+		all_okay = .FALSE.
+	END IF
+	
+   ! A single non-FillVal value should be replicated n times
+	iarray1_in(:)=(/19991231/)
+	iarray1_out(:)=(/19991231/)
+	CALL set_date(iarray1_in,1,FV_int)
+	okay = test_arrays(iarray1_in,iarray1_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 12 failed"
+		all_okay = .FALSE.
+	END IF
+
+   ! A single non-FillVal value should be replicated n times
+	iarray2_in(:) = (/19991231, FV_int/)
+	iarray2_out(:) = (/19991231, 19991231/)
+	CALL set_date(iarray2_in,2,FV_int)
+	okay = test_arrays(iarray2_in,iarray2_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 13 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A single non-FillVal value should be replicated n times
+	iarray10_in(:) = (/20110101,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = 20110101
+	CALL set_date(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 14 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A single non-FillVal value should be replicated n times
+	iarray3_in(:) = (/20110101,FV_int,FV_int/)
+	iarray3_out(:) = 20110101
+	CALL set_date(iarray3_in,3,FV_int)
+	okay = test_arrays(iarray3_in,iarray3_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 15 failed"
+		all_okay = .FALSE.
+	END IF
+		
+	! A full list of n non-FillVals should be left unaltered.
+	iarray2_in(:) = (/19991231, 20000101/)
+	iarray2_out(:) = (/19991231, 20000101/)
+	CALL set_date(iarray2_in,2,FV_int)
+	okay = test_arrays(iarray2_in,iarray2_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 16 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A full list of n non-FillVals should be left unaltered.
+	iarray3_in(:) = (/19840101, 19001231, 20500612/)
+	iarray3_out(:) = (/19840101, 19001231, 20500612/)
+	CALL set_date(iarray3_in,3,FV_int)
+	okay = test_arrays(iarray3_in,iarray3_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 17 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A full list of n non-FillVals should be left unaltered.
+	iarray10_in(:) = (/20091231, 20100101, 20100102, 20100103, 20091231, &
+	                    20100105, 20100106, 20091231, 20100108, 20100109/)
+	iarray10_out(:) = (/20091231, 20100101, 20100102, 20100103, 20091231, &
+	                    20100105, 20100106, 20091231, 20100108, 20100109/)
+	CALL set_date(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 18 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	iarray10_in(:) = (/20091231,20100109,1,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = (/20091231, 20100101, 20100102, 20100103, 20100104, &
+	                    20100105, 20100106, 20100107, 20100108, 20100109/)
+	CALL set_date(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 19 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	iarray10_in(:) = (/20100109,20091231,-1,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = (/20100109, 20100108, 20100107, 20100106, 20100105, &
+	                    20100104, 20100103, 20100102, 20100101, 20091231/)
+	CALL set_date(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 20 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	iarray10_in(:) = (/20100101,20100401,10,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = (/20100101, 20100111, 20100121, 20100131, 20100210, &
+	                    20100220, 20100302, 20100312, 20100322, 20100401/)
+	CALL set_date(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 21 failed"
+		all_okay = .FALSE.
+	END IF
+
+   ! A single non-FillVal value should be replicated n times
+	iarray1_in(:)=(/0000/)
+	iarray1_out(:)=(/0/)
+	CALL set_time(iarray1_in,1,FV_int)
+	okay = test_arrays(iarray1_in,iarray1_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 22 failed"
+		all_okay = .FALSE.
+	END IF
+
+   ! A single non-FillVal value should be replicated n times
+	iarray2_in(:) = (/0600, FV_int/)
+	iarray2_out(:) = (/600, 600/)
+	CALL set_time(iarray2_in,2,FV_int)
+	okay = test_arrays(iarray2_in,iarray2_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 23 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A full list of n non-FillVals should be left unaltered.
+	iarray2_in(:) = (/0600, 1200/)
+	iarray2_out(:) = (/0600, 1200/)
+	CALL set_time(iarray2_in,2,FV_int)
+	okay = test_arrays(iarray2_in,iarray2_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 24 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! A full list of n non-FillVals should be left unaltered.
+	iarray10_in(:) = (/1, 2, 3, -5, 5, 67, 7, 8, 9, 10/)
+	iarray10_out(:) = (/1, 2, 3, -5, 5, 67, 7, 8, 9, 10/)
+	CALL set_time(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 25 failed"
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	iarray10_in(:) = (/0000,0430,0030,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = (/0, 30, 100, 130, 200, &
+	                    230, 300, 330, 400, 430/)
+	CALL set_time(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 26 failed"
+		WRITE(*,*) iarray10_in
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	iarray10_in(:) = (/2200,0230,0030,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = (/2200, 2230, 2300, 2330, 0, &
+	                    30, 100, 130, 200, 230/)
+	CALL set_time(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 27 failed"
+		WRITE(*,*) iarray10_in
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	iarray10_in(:) = (/2200,1730,-0030,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = (/2200, 2130, 2100, 2030, 2000, &
+	                    1930, 1900, 1830, 1800, 1730/)
+	CALL set_time(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 28 failed"
+		WRITE(*,*) iarray10_in
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	iarray10_in(:) = (/0100,2200,-0020,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = (/0100, 0040, 0020, 0000, 2340, &
+	                    2320, 2300, 2240, 2220, 2200/)
+	CALL set_time(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 29 failed"
+		WRITE(*,*) iarray10_in
+		all_okay = .FALSE.
+	END IF
+
+	! Three non-FillVal values should be used as the start, end, step in conjunction with n
+	iarray10_in(:) = (/1700,0630,90,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int,FV_int/)
+	iarray10_out(:) = (/1700, 1830, 2000, 2130, 2300, &
+	                    0030, 0200, 0330, 0500, 0630/)
+	CALL set_time(iarray10_in,10,FV_int)
+	okay = test_arrays(iarray10_in,iarray10_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 30 failed"
+		WRITE(*,*) iarray10_in
+		all_okay = .FALSE.
+	END IF
+
+	! A single obs value should be replicated throught the array(obs,levels)
+	array_4x3_in(:,1,1) = (/1.0,FV_real,FV_real/)
+	array_4x3_in(:,2,1) = (/FV_real,FV_real,FV_real/)
+	array_4x3_in(:,3,1) = (/FV_real,FV_real,FV_real/)
+	array_4x3_in(:,4,1) = (/FV_real,FV_real,FV_real/)
+	array_4x3_out(:,1,1) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	array_4x3_out(:,2,1) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	array_4x3_out(:,3,1) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	array_4x3_out(:,4,1) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	CALL set_obs_values(array_4x3_in,1,4,3,FV_real)
+	okay = test_arrays(array_4x3_in,array_4x3_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 31 failed"
+		WRITE(*,*) array_4x3_in
+		WRITE(*,*)
+		WRITE(*,*) array_4x3_out
+		all_okay = .FALSE.
+	END IF
+
+	! A full specification of the obs values should be unaltered
+	array_4x3_in(:,1,1) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp/)
+	array_4x3_in(:,2,1) = (/4.0_fbdp, 5.0_fbdp, 6.0_fbdp/)
+	array_4x3_in(:,3,1) = (/7.0_fbdp, 8.0_fbdp, 9.0_fbdp/)
+	array_4x3_in(:,4,1) = (/10.0_fbdp, 11.0_fbdp, 12.0_fbdp/)
+	array_4x3_out(:,1,1) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp/)
+	array_4x3_out(:,2,1) = (/4.0_fbdp, 5.0_fbdp, 6.0_fbdp/)
+	array_4x3_out(:,3,1) = (/7.0_fbdp, 8.0_fbdp, 9.0_fbdp/)
+	array_4x3_out(:,4,1) = (/10.0_fbdp, 11.0_fbdp, 12.0_fbdp/)
+	CALL set_obs_values(array_4x3_in,1,4,3,FV_real)
+	okay = test_arrays(array_4x3_in,array_4x3_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 32 failed"
+		WRITE(*,*) array_4x3_in
+		WRITE(*,*)
+		WRITE(*,*) array_4x3_out
+		all_okay = .FALSE.
+	END IF
+
+	! A single profile should be replicated at all lat/lons
+	array_4x3_in(:,1,1) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp/)
+	array_4x3_in(:,2,1) = (/FV_real, FV_real, FV_real/)
+	array_4x3_in(:,3,1) = (/FV_real, FV_real, FV_real/)
+	array_4x3_in(:,4,1) = (/FV_real, FV_real, FV_real/)
+	array_4x3_out(:,1,1) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp/)
+	array_4x3_out(:,2,1) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp/)
+	array_4x3_out(:,3,1) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp/)
+	array_4x3_out(:,4,1) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp/)
+	CALL set_obs_values(array_4x3_in,1,4,3,FV_real)
+	okay = test_arrays(array_4x3_in,array_4x3_out)
+	IF (okay .EQV. .FALSE.) THEN
+	   WRITE(*,*) "Test 33 failed"
+		WRITE(*,*) array_4x3_in
+		WRITE(*,*)
+		WRITE(*,*) array_4x3_out
+		all_okay = .FALSE.
+	END IF
+
+	! A single profile position should only be given where nobs=1
+	ALLOCATE(lat_array_in(1),	&
+				lon_array_in(1),	&
+				lat_array_out(1), &
+				lon_array_out(1)	)
+	lat_array_in(:) = (/1.0_fbdp/)
+	lon_array_in(:) = (/1.0_fbdp/)
+	lat_array_out(:) = (/1.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,1,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 34 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+	! A single lat and list of lons should give nobs observations
+	ALLOCATE(lat_array_in(4),	&
+				lon_array_in(4),	&
+				lat_array_out(4), &
+				lon_array_out(4)	)
+	lat_array_in(:) = (/1.0_fbdp, FV_real, FV_real, FV_real/)
+	lon_array_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp/)
+	lat_array_out(:) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,4,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 35 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+	! A single lat and bounded lons should give nobs = no elements in expanded bounds
+	ALLOCATE(lat_array_in(3),	&
+				lon_array_in(3),	&
+				lat_array_out(3), &
+				lon_array_out(3)	)
+	lat_array_in(:) = (/1.0_fbdp, FV_real, FV_real/)
+	lon_array_in(:) = (/1.0_fbdp, 3.0_fbdp, 1.0_fbdp/)
+	lat_array_out(:) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,3,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 36 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+	! A single lat and bounded lons should give nobs = no elements in expanded bounds
+	ALLOCATE(lat_array_in(5),	&
+				lon_array_in(5),	&
+				lat_array_out(5), &
+				lon_array_out(5)	)
+	lat_array_in(:) = (/1.0_fbdp, FV_real, FV_real, FV_real, FV_real/)
+	lon_array_in(:) = (/1.0_fbdp, 5.0_fbdp, 1.0_fbdp, FV_real, FV_real/)
+	lat_array_out(:) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,5,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 37 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+	! A single lon and bounded lats should give nobs = no elements in expanded bounds
+	ALLOCATE(lat_array_in(5),	&
+				lon_array_in(5),	&
+				lat_array_out(5), &
+				lon_array_out(5)	)
+	lat_array_in(:) = (/1.0_fbdp, 5.0_fbdp, 1.0_fbdp, FV_real, FV_real/)
+	lon_array_in(:) = (/1.0_fbdp, FV_real, FV_real, FV_real, FV_real/)
+	lat_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,5,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 38 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+	! A list of lats and lons with same number of elements as nobs should be unaltered
+	ALLOCATE(lat_array_in(5),	&
+				lon_array_in(5),	&
+				lat_array_out(5), &
+				lon_array_out(5)	)
+	lat_array_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	lon_array_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	lat_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,5,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 39 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+	! A list of lats and lons with fewer elements as nobs should be gridded 
+	! to produce nobs observations - list all lons at same lat, before stepping in lat.
+	ALLOCATE(lat_array_in(25),	&
+				lon_array_in(25),	&
+				lat_array_out(25), &
+				lon_array_out(25)	)
+	lat_array_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp,&
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real/)
+	lon_array_in(:) = (/10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real/)
+	lat_array_out(:) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp, & 
+								2.0_fbdp, 2.0_fbdp, 2.0_fbdp, 2.0_fbdp, 2.0_fbdp, &
+								3.0_fbdp, 3.0_fbdp, 3.0_fbdp, 3.0_fbdp, 3.0_fbdp, &
+								4.0_fbdp, 4.0_fbdp, 4.0_fbdp, 4.0_fbdp, 4.0_fbdp, &
+								5.0_fbdp, 5.0_fbdp, 5.0_fbdp, 5.0_fbdp, 5.0_fbdp/)
+	lon_array_out(:) = (/10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,25,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 40 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+	! A list of lats and lon bounds with fewer elements as nobs should be gridded 
+	! to produce nobs observations - list all lons at same lat, before stepping in lat.
+	ALLOCATE(lat_array_in(25),	&
+				lon_array_in(25),	&
+				lat_array_out(25), &
+				lon_array_out(25)	)
+	lat_array_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp,&
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real/)
+	lon_array_in(:) = (/10.0_fbdp, 50.0_fbdp, 10.0_fbdp, FV_real, FV_real,&
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real/)
+	lat_array_out(:) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp, & 
+								2.0_fbdp, 2.0_fbdp, 2.0_fbdp, 2.0_fbdp, 2.0_fbdp, &
+								3.0_fbdp, 3.0_fbdp, 3.0_fbdp, 3.0_fbdp, 3.0_fbdp, &
+								4.0_fbdp, 4.0_fbdp, 4.0_fbdp, 4.0_fbdp, 4.0_fbdp, &
+								5.0_fbdp, 5.0_fbdp, 5.0_fbdp, 5.0_fbdp, 5.0_fbdp/)
+	lon_array_out(:) = (/10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,25,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 41 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+
+	! A list of lats and lon bounds with the same number of elements as nobs should be 
+	! unaltered expect for bounds expansion
+	ALLOCATE(lat_array_in(5),	&
+				lon_array_in(5),	&
+				lat_array_out(5), &
+				lon_array_out(5)	)
+	lat_array_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	lon_array_in(:) = (/10.0_fbdp, 50.0_fbdp, 10.0_fbdp, FV_real, FV_real/)
+	lat_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	lon_array_out(:) = (/10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,5,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 42 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+	
+
+	! A list of lons and lat bounds with the same number of elements as nobs should be 
+	! unaltered expect for bounds expansion
+	ALLOCATE(lat_array_in(5),	&
+				lon_array_in(5),	&
+				lat_array_out(5), &
+				lon_array_out(5)	)
+	lat_array_in(:) = (/10.0_fbdp, 50.0_fbdp, 10.0_fbdp, FV_real, FV_real/)
+	lon_array_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	lat_array_out(:) = (/10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp, 50.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,5,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 43 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+	
+
+	! A list of lons and lat bounds with fewer elements as nobs should be gridded 
+	! to produce nobs observations - list all lons at same lat, before stepping in lat.
+	ALLOCATE(lat_array_in(25),	&
+				lon_array_in(25),	&
+				lat_array_out(25), &
+				lon_array_out(25)	)
+	lat_array_in(:) = (/10.0_fbdp, 50.0_fbdp, 10.0_fbdp, FV_real, FV_real,&
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real/)
+	lon_array_in(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp,&
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real/)
+	lat_array_out(:) = (/10.0_fbdp, 10.0_fbdp, 10.0_fbdp, 10.0_fbdp, 10.0_fbdp, & 
+								20.0_fbdp, 20.0_fbdp, 20.0_fbdp, 20.0_fbdp, 20.0_fbdp, &
+								30.0_fbdp, 30.0_fbdp, 30.0_fbdp, 30.0_fbdp, 30.0_fbdp, &
+								40.0_fbdp, 40.0_fbdp, 40.0_fbdp, 40.0_fbdp, 40.0_fbdp, &
+								50.0_fbdp, 50.0_fbdp, 50.0_fbdp, 50.0_fbdp, 50.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp,&
+								1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp,&
+								1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp,&
+								1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp,&
+								1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,25,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 44 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+
+	! A single lat and bounded lons should give nobs = no elements in expanded bounds
+	ALLOCATE(lat_array_in(5),	&
+				lon_array_in(5),	&
+				lat_array_out(5), &
+				lon_array_out(5)	)
+	lat_array_in(:) = (/1.0_fbdp, FV_real, FV_real, FV_real, FV_real/)
+	lon_array_in(:) = (/1.0_fbdp, 5.0_fbdp, 1.0_fbdp, FV_real, FV_real/)
+	lat_array_out(:) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp/)
+	lon_array_out(:) = (/1.0_fbdp, 2.0_fbdp, 3.0_fbdp, 4.0_fbdp, 5.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,5,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 45 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+
+	! Bounded lat and bounded lons - list all lons at same lat, before stepping in lat.
+	ALLOCATE(lat_array_in(20),	&
+				lon_array_in(20),	&
+				lat_array_out(20), &
+				lon_array_out(20)	)
+	lat_array_in(:) = (/1.0_fbdp, 5.0_fbdp, 1.0_fbdp, FV_real, FV_real,&
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real/)
+	lon_array_in(:) = (/10.0_fbdp, 40.0_fbdp, 10.0_fbdp, FV_real, FV_real,&
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real, &
+	                    FV_real, FV_real, FV_real, FV_real, FV_real/)
+	lat_array_out(:) = (/1.0_fbdp, 1.0_fbdp, 1.0_fbdp, 1.0_fbdp, & 
+								2.0_fbdp, 2.0_fbdp, 2.0_fbdp, 2.0_fbdp, &
+								3.0_fbdp, 3.0_fbdp, 3.0_fbdp, 3.0_fbdp, &
+								4.0_fbdp, 4.0_fbdp, 4.0_fbdp, 4.0_fbdp, &
+								5.0_fbdp, 5.0_fbdp, 5.0_fbdp, 5.0_fbdp/)
+	lon_array_out(:) = (/10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp,&
+								10.0_fbdp, 20.0_fbdp, 30.0_fbdp, 40.0_fbdp/)
+	CALL set_spatial_coords(lat_array_in,lon_array_in,20,FV_real)
+	okay = test_arrays(lat_array_in,lat_array_out)
+	okay_too = test_arrays(lon_array_in,lon_array_out)
+	IF ((okay .EQV. .FALSE.) .OR. (okay_too .EQV. .FALSE.)) THEN
+	   WRITE(*,*) "Test 46 failed"
+		WRITE(*,*) lat_array_in
+		WRITE(*,*) lon_array_in
+		WRITE(*,*) lat_array_out
+		WRITE(*,*) lon_array_out
+		all_okay = .FALSE.
+	END IF
+	DEALLOCATE(lat_array_in,	&
+				  lon_array_in,	&
+				  lat_array_out,	&
+				  lon_array_out	)
+
+
+	IF (all_okay) WRITE(*,*) "All tests passed"
+	
+	END SUBROUTINE tester
+
+END MODULE test_fbgenerate	
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/README
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/README	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/README	(revision 5075)
@@ -1,10 +1,14 @@
- This is a first draft of the CONFIGURATION MANAGER demonstrator.
- Unfortunately, there are still bugs in those tools.
- I will continue to work on it next year, to fix those bugs and add some
- improvement as handle north fold...
+This is a first release of SIREN.
 
- '''WARNING : there are still bugs to fix in those tools!! '''
+To create SIREN documentation, go to ./src and run doxygen 
+(http://www.stack.nl/~dimitri/doxygen/index.html version 1.8.3.1 or upper)
+then
+   open ../doc/index.html 
+or 
+   run ../doc/latex/gmake and open refman.pdf 
 
-   ''''''
+
+templates of namelists could be find in templates directory.
+read documentation for more information.
 
  1- program to create coordinate file :
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/cfg/variable.cfg	(revision 5075)
@@ -1,37 +1,73 @@
-# name       | units          | axis | point | standard name               | long name          | interpolation
-X            | 1              | X    |   | projection_x_coordinate         |                    |                      
-Y            | 1              | Y    |   | projection_y_coordinate         |                    |                      
-Z            | 1              | Z    |   | projection_z_coordinate         |                    |                      
-T            | 1              | T    |   | projection_t_coordinate         |                    |                      
-nav_lon      | degrees_east   | XY   | T | longitude                       | Longitude          | cubic                      
-nav_lat      | degrees_north  | XY   | T | latitude                        | Latitude           | cubic         
-nav_lev      | model_levels   | Z    | T |                                 | Model levels       | cubic        
-deptht       | m              | Z    | T | depth                           | Vertical T levels  |
-time_counter |                | T    |   | time                            | Time axis          | 
-Bathymetry   | m              | XY   | T | bathymetry                      | Bathymetry         | cubic         
-votemper     | degree_Celsius | XYZT | T | sea_water_potential_temperature | Temperature        | cubic         
-vozocrtx     | m s-1          | XYZT | U |                                 | Zonal velocity     | cubic         
-vomecrty     | m s-1          | XYZT | V |                                 | Meridional velocity| cubic         
-vosaline     | PSU            | XYZT | T | sea_water_salinity              | Salinity           | cubic         
-sossheig     | m              | XYT  | T | sea_surface_height              | Sea Surface Height | cubic         
-glamt        | degrees_east   | XY   | T |                                 | Longitude_T        | cubic
-glamu        | degrees_east   | XY   | U |                                 | Longitude_U        | cubic            
-glamv        | degrees_east   | XY   | V |                                 | Longitude_V        | cubic          
-glamf        | degrees_east   | XY   | F |                                 | Longitude_F        | cubic         
-gphit        | degrees_north  | XY   | T |                                 | Latitude_T         | cubic         
-gphiu        | degrees_north  | XY   | U |                                 | Latitude_U         | cubic        
-gphiv        | degrees_north  | XY   | V |                                 | Latitude_V         | cubic        
-gphif        | degrees_north  | XY   | F |                                 | Latitude_F         | cubic        
-e1t          | m              | XY   | T |                                 |                    | cubic/rhoi    
-e1u          | m              | XY   | U |                                 |                    | cubic/rhoi     
-e1v          | m              | XY   | V |                                 |                    | cubic/rhoi      
-e1f          | m              | XY   | F |                                 |                    | cubic/rhoi    
-e2t          | m              | XY   | T |                                 |                    | cubic/rhoj      
-e2u          | m              | XY   | U |                                 |                    | cubic/rhoj      
-e2v          | m              | XY   | V |                                 |                    | cubic/rhoj     
-e2f          | m              | XY   | F |                                 |                    | cubic/rhoj      
-tmask        |                | XYZ  | T |                                 |                    | nearest       
-umask        |                | XYZ  | U |                                 |                    | nearest       
-vmask        |                | XYZ  | V |                                 |                    | nearest       
-fmask        |                | XYZ  | F |                                 |                    | nearest       
-weight       |                | XY   | T |                                 |                    |               
+# name       | units          | axis | point | standard name                | long name          | interpolation
+X            | 1              | X    |   | projection_x_coordinate          |                    |                      
+Y            | 1              | Y    |   | projection_y_coordinate          |                    |                      
+Z            | 1              | Z    |   | projection_z_coordinate          |                    |                      
+T            | 1              | T    |   | projection_t_coordinate          |                    |                      
+nav_lon      | degrees_east   | XY   | T | longitude                        | Longitude          | cubic                      
+nav_lat      | degrees_north  | XY   | T | latitude                         | Latitude           | cubic         
+nav_lev      | model_levels   | Z    | T |                                  | Model levels       | cubic        
+deptht       | m              | Z    | T | depth                            | Vertical T levels  |
+time_counter |                | T    |   | time                             | Time axis          | 
+Bathymetry   | m              | XY   | T | bathymetry                       | Bathymetry         | cubic         
+votemper     | degree_Celsius | XYZT | T | sea_water_potential_temperature  | Temperature        | cubic         
+vozocrtx     | m s-1          | XYZT | U |                                  | Zonal velocity     | cubic         
+vomecrty     | m s-1          | XYZT | V |                                  | Meridional velocity| cubic         
+vosaline     | PSU            | XYZT | T | sea_water_salinity               | Salinity           | cubic         
+sossheig     | m              | XYT  | T | sea_surface_height               | Sea Surface Height | cubic         
+glamt        | degrees_east   | XY   | T |                                  | Longitude_T        | cubic
+glamu        | degrees_east   | XY   | U |                                  | Longitude_U        | cubic            
+glamv        | degrees_east   | XY   | V |                                  | Longitude_V        | cubic          
+glamf        | degrees_east   | XY   | F |                                  | Longitude_F        | cubic         
+gphit        | degrees_north  | XY   | T |                                  | Latitude_T         | cubic         
+gphiu        | degrees_north  | XY   | U |                                  | Latitude_U         | cubic        
+gphiv        | degrees_north  | XY   | V |                                  | Latitude_V         | cubic        
+gphif        | degrees_north  | XY   | F |                                  | Latitude_F         | cubic        
+e1t          | m              | XY   | T |                                  |                    | cubic/rhoi    
+e1u          | m              | XY   | U |                                  |                    | cubic/rhoi     
+e1v          | m              | XY   | V |                                  |                    | cubic/rhoi      
+e1f          | m              | XY   | F |                                  |                    | cubic/rhoi    
+e2t          | m              | XY   | T |                                  |                    | cubic/rhoj      
+e2u          | m              | XY   | U |                                  |                    | cubic/rhoj      
+e2v          | m              | XY   | V |                                  |                    | cubic/rhoj     
+e2f          | m              | XY   | F |                                  |                    | cubic/rhoj      
+tmask        |                | XYZ  | T |                                  |                    | nearest       
+umask        |                | XYZ  | U |                                  |                    | nearest       
+vmask        |                | XYZ  | V |                                  |                    | nearest       
+fmask        |                | XYZ  | F |                                  |                    | nearest       
+weight       |                | XY   | T |                                  |                    |               
+kt           |                |      |   |                                  |                    |               
+ndastp       |                |      |   |                                  |                    |               
+adatrj       |                |      |   |                                  |                    |               
+kt           |                |      |   |                                  |                    |               
+rdt          |                |      |   |                                  |                    |               
+rdttra1      |                |      |   |                                  |                    |               
+utau_b       |                | XYT  | U |surface_downward_eastward_stress  |                    |               
+vtau_b       |                | XYT  | V |surface_downward_northward_stress |                    |               
+qns_b        |                | XYT  | T |                                  |                    |               
+emp_b        |                | XYT  | T |                                  |                    |               
+sfx_b        |                | XYT  | T |                                  |                    |               
+en           |                | XYZT | T |                                  |                    |               
+avt          |                | XYZT | T |                                  |                    |               
+avm          |                | XYZT | T |                                  |                    |               
+avmu         |                | XYZT | T |                                  |                    |               
+avmv         |                | XYZT | T |                                  |                    |               
+dissl        |                | XYZT | T |                                  |                    |               
+sbc_hc_b     |                | XYT  | T |                                  |                    |               
+sbc_sc_b     |                | XYT  | T |                                  |                    |               
+gcx          |                | XYT  | T |                                  |                    |               
+gcxb         |                | XYT  | T |                                  |                    |               
+ub           |                | XYZT | U |                                  |                    |               
+vb           |                | XYZT | V |                                  |                    |               
+tb           |                | XYZT | T |                                  |                    |               
+sb           |                | XYZT | T |                                  |                    |               
+rotb         |                | XYZT | T |                                  |                    |               
+hdivb        |                | XYZT | T |                                  |                    |               
+sshb         |                | XYT  | T |                                  |                    |               
+un           |                | XYZT | U |                                  |                    |               
+vn           |                | XYZT | V |                                  |                    |               
+tn           |                | XYZT | T |                                  |                    |               
+sn           |                | XYZT | T |                                  |                    |               
+rotn         |                | XYZT | T |                                  |                    |               
+hdivn        |                | XYZT | T |                                  |                    |               
+sshn         |                | XYT  | T |                                  |                    |               
+rhop         |                | XYZT | T |                                  |                    |               
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/Doxyfile
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/Doxyfile	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/Doxyfile	(revision 5075)
@@ -1,13 +1,16 @@
-# Doxyfile 1.6.1
+# Doxyfile 1.8.8
 
 # This file describes the settings to be used by the documentation system
-# doxygen (www.doxygen.org) for a project
-#
-# All text after a hash (#) is considered a comment and will be ignored
+# doxygen (www.doxygen.org) for a project.
+#
+# All text after a double hash (##) is considered a comment and is placed in
+# front of the TAG it is preceding.
+#
+# All text after a single hash (#) is considered a comment and will be ignored.
 # The format is:
-#       TAG = value [value, ...]
-# For lists items can also be appended using:
-#       TAG += value [value, ...]
-# Values that contain spaces should be placed between quotes (" ")
+# TAG = value [value, ...]
+# For lists, items can also be appended using:
+# TAG += value [value, ...]
+# Values that contain spaces should be placed between quotes (\" \").
 
 #---------------------------------------------------------------------------
@@ -16,80 +19,110 @@
 
 # This tag specifies the encoding used for all characters in the config file
-# that follow. The default is UTF-8 which is also the encoding used for all
-# text before the first occurrence of this tag. Doxygen uses libiconv (or the
-# iconv built into libc) for the transcoding. See
-# http://www.gnu.org/software/libiconv for the list of possible encodings.
+# that follow. The default is UTF-8 which is also the encoding used for all text
+# before the first occurrence of this tag. Doxygen uses libiconv (or the iconv
+# built into libc) for the transcoding. See http://www.gnu.org/software/libiconv
+# for the list of possible encodings.
+# The default value is: UTF-8.
 
 DOXYFILE_ENCODING      = UTF-8
 
-# The PROJECT_NAME tag is a single word (or a sequence of words surrounded
-# by quotes) that should identify the project.
-
-PROJECT_NAME           = Doxygen Fortran Example
-
-# The PROJECT_NUMBER tag can be used to enter a project or revision number.
-# This could be handy for archiving the generated documentation or
-# if some version control system is used.
-
-PROJECT_NUMBER         =
-
-# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute)
-# base path where the generated documentation will be put.
-# If a relative path is entered, it will be relative to the location
-# where doxygen was started. If left blank the current directory will be used.
-
-OUTPUT_DIRECTORY       = 
-
-# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create
-# 4096 sub-directories (in 2 levels) under the output directory of each output
-# format and will distribute the generated files over these directories.
-# Enabling this option can be useful when feeding doxygen a huge amount of
-# source files, where putting all generated files in the same directory would
-# otherwise cause performance problems for the file system.
+# The PROJECT_NAME tag is a single word (or a sequence of words surrounded by
+# double-quotes, unless you are using Doxywizard) that should identify the
+# project for which the documentation is generated. This name is used in the
+# title of most generated pages and in a few other places.
+# The default value is: My Project.
+
+PROJECT_NAME           = "SIREN"
+
+# The PROJECT_NUMBER tag can be used to enter a project or revision number. This
+# could be handy for archiving the generated documentation or if some version
+# control system is used.
+
+PROJECT_NUMBER         = "NEMO 3.6"
+
+# Using the PROJECT_BRIEF tag one can provide an optional one line description
+# for a project that appears at the top of each page and should give viewer a
+# quick idea about the purpose of the project. Keep the description short.
+
+PROJECT_BRIEF          = "System and Interface for oceanic RElocable Nesting"
+
+# With the PROJECT_LOGO tag one can specify an logo or icon that is included in
+# the documentation. The maximum height of the logo should not exceed 55 pixels
+# and the maximum width should not exceed 200 pixels. Doxygen will copy the logo
+# to the output directory.
+
+PROJECT_LOGO           = ./docsrc/Image/logoSirenNemo.png
+
+# The OUTPUT_DIRECTORY tag is used to specify the (relative or absolute) path
+# into which the generated documentation will be written. If a relative path is
+# entered, it will be relative to the location where doxygen was started. If
+# left blank the current directory will be used.
+
+OUTPUT_DIRECTORY       = ../doc
+
+# If the CREATE_SUBDIRS tag is set to YES, then doxygen will create 4096 sub-
+# directories (in 2 levels) under the output directory of each output format and
+# will distribute the generated files over these directories. Enabling this
+# option can be useful when feeding doxygen a huge amount of source files, where
+# putting all generated files in the same directory would otherwise causes
+# performance problems for the file system.
+# The default value is: NO.
 
 CREATE_SUBDIRS         = NO
+
+# If the ALLOW_UNICODE_NAMES tag is set to YES, doxygen will allow non-ASCII
+# characters to appear in the names of generated files. If set to NO, non-ASCII
+# characters will be escaped, for example _xE3_x81_x84 will be used for Unicode
+# U+3044.
+# The default value is: NO.
+
+ALLOW_UNICODE_NAMES    = NO
 
 # The OUTPUT_LANGUAGE tag is used to specify the language in which all
 # documentation generated by doxygen is written. Doxygen will use this
 # information to generate all constant output in the proper language.
-# The default language is English, other supported languages are:
-# Afrikaans, Arabic, Brazilian, Catalan, Chinese, Chinese-Traditional,
-# Croatian, Czech, Danish, Dutch, Esperanto, Farsi, Finnish, French, German,
-# Greek, Hungarian, Italian, Japanese, Japanese-en (Japanese with English
-# messages), Korean, Korean-en, Lithuanian, Norwegian, Macedonian, Persian,
-# Polish, Portuguese, Romanian, Russian, Serbian, Serbian-Cyrilic, Slovak,
-# Slovene, Spanish, Swedish, Ukrainian, and Vietnamese.
+# Possible values are: Afrikaans, Arabic, Armenian, Brazilian, Catalan, Chinese,
+# Chinese-Traditional, Croatian, Czech, Danish, Dutch, English (United States),
+# Esperanto, Farsi (Persian), Finnish, French, German, Greek, Hungarian,
+# Indonesian, Italian, Japanese, Japanese-en (Japanese with English messages),
+# Korean, Korean-en (Korean with English messages), Latvian, Lithuanian,
+# Macedonian, Norwegian, Persian (Farsi), Polish, Portuguese, Romanian, Russian,
+# Serbian, Serbian-Cyrillic, Slovak, Slovene, Spanish, Swedish, Turkish,
+# Ukrainian and Vietnamese.
+# The default value is: English.
 
 OUTPUT_LANGUAGE        = English
 
-# If the BRIEF_MEMBER_DESC tag is set to YES (the default) Doxygen will
-# include brief member descriptions after the members that are listed in
-# the file and class documentation (similar to JavaDoc).
-# Set to NO to disable this.
+# If the BRIEF_MEMBER_DESC tag is set to YES doxygen will include brief member
+# descriptions after the members that are listed in the file and class
+# documentation (similar to Javadoc). Set to NO to disable this.
+# The default value is: YES.
 
 BRIEF_MEMBER_DESC      = YES
 
-# If the REPEAT_BRIEF tag is set to YES (the default) Doxygen will prepend
-# the brief description of a member or function before the detailed description.
-# Note: if both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
+# If the REPEAT_BRIEF tag is set to YES doxygen will prepend the brief
+# description of a member or function before the detailed description
+#
+# Note: If both HIDE_UNDOC_MEMBERS and BRIEF_MEMBER_DESC are set to NO, the
 # brief descriptions will be completely suppressed.
+# The default value is: YES.
 
 REPEAT_BRIEF           = YES
 
-# This tag implements a quasi-intelligent brief description abbreviator
-# that is used to form the text in various listings. Each string
-# in this list, if found as the leading text of the brief description, will be
-# stripped from the text and the result after processing the whole list, is
-# used as the annotated text. Otherwise, the brief description is used as-is.
-# If left blank, the following values are used ("$name" is automatically
-# replaced with the name of the entity): "The $name class" "The $name widget"
-# "The $name file" "is" "provides" "specifies" "contains"
-# "represents" "a" "an" "the"
+# This tag implements a quasi-intelligent brief description abbreviator that is
+# used to form the text in various listings. Each string in this list, if found
+# as the leading text of the brief description, will be stripped from the text
+# and the result, after processing the whole list, is used as the annotated
+# text. Otherwise, the brief description is used as-is. If left blank, the
+# following values are used ($name is automatically replaced with the name of
+# the entity):The $name class, The $name widget, The $name file, is, provides,
+# specifies, contains, represents, a, an and the.
 
 ABBREVIATE_BRIEF       =
 
 # If the ALWAYS_DETAILED_SEC and REPEAT_BRIEF tags are both set to YES then
-# Doxygen will generate a detailed section even if there is only a brief
+# doxygen will generate a detailed section even if there is only a brief
 # description.
+# The default value is: NO.
 
 ALWAYS_DETAILED_SEC    = NO
@@ -99,130 +132,181 @@
 # members were ordinary class members. Constructors, destructors and assignment
 # operators of the base classes will not be shown.
+# The default value is: NO.
 
 INLINE_INHERITED_MEMB  = NO
 
-# If the FULL_PATH_NAMES tag is set to YES then Doxygen will prepend the full
-# path before files name in the file list and in the header files. If set
-# to NO the shortest path that makes the file name unique will be used.
+# If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path
+# before files name in the file list and in the header files. If set to NO the
+# shortest path that makes the file name unique will be used
+# The default value is: YES.
 
 FULL_PATH_NAMES        = YES
 
-# If the FULL_PATH_NAMES tag is set to YES then the STRIP_FROM_PATH tag
-# can be used to strip a user-defined part of the path. Stripping is
-# only done if one of the specified strings matches the left-hand part of
-# the path. The tag can be used to show relative paths in the file list.
-# If left blank the directory from which doxygen is run is used as the
-# path to strip.
+# The STRIP_FROM_PATH tag can be used to strip a user-defined part of the path.
+# Stripping is only done if one of the specified strings matches the left-hand
+# part of the path. The tag can be used to show relative paths in the file list.
+# If left blank the directory from which doxygen is run is used as the path to
+# strip.
+#
+# Note that you can specify absolute paths here, but also relative paths, which
+# will be relative from the directory where doxygen is started.
+# This tag requires that the tag FULL_PATH_NAMES is set to YES.
 
 STRIP_FROM_PATH        =
 
-# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of
-# the path mentioned in the documentation of a class, which tells
-# the reader which header file to include in order to use a class.
-# If left blank only the name of the header file containing the class
-# definition is used. Otherwise one should specify the include paths that
-# are normally passed to the compiler using the -I flag.
+# The STRIP_FROM_INC_PATH tag can be used to strip a user-defined part of the
+# path mentioned in the documentation of a class, which tells the reader which
+# header file to include in order to use a class. If left blank only the name of
+# the header file containing the class definition is used. Otherwise one should
+# specify the list of include paths that are normally passed to the compiler
+# using the -I flag.
 
 STRIP_FROM_INC_PATH    =
 
-# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter
-# (but less readable) file names. This can be useful is your file systems
-# doesn't support long names like on DOS, Mac, or CD-ROM.
+# If the SHORT_NAMES tag is set to YES, doxygen will generate much shorter (but
+# less readable) file names. This can be useful is your file systems doesn't
+# support long names like on DOS, Mac, or CD-ROM.
+# The default value is: NO.
 
 SHORT_NAMES            = NO
 
-# If the JAVADOC_AUTOBRIEF tag is set to YES then Doxygen
-# will interpret the first line (until the first dot) of a JavaDoc-style
-# comment as the brief description. If set to NO, the JavaDoc
-# comments will behave just like regular Qt-style comments
-# (thus requiring an explicit @brief command for a brief description.)
+# If the JAVADOC_AUTOBRIEF tag is set to YES then doxygen will interpret the
+# first line (until the first dot) of a Javadoc-style comment as the brief
+# description. If set to NO, the Javadoc-style will behave just like regular Qt-
+# style comments (thus requiring an explicit @brief command for a brief
+# description.)
+# The default value is: NO.
 
 JAVADOC_AUTOBRIEF      = NO
 
-# If the QT_AUTOBRIEF tag is set to YES then Doxygen will
-# interpret the first line (until the first dot) of a Qt-style
-# comment as the brief description. If set to NO, the comments
-# will behave just like regular Qt-style comments (thus requiring
-# an explicit \brief command for a brief description.)
+# If the QT_AUTOBRIEF tag is set to YES then doxygen will interpret the first
+# line (until the first dot) of a Qt-style comment as the brief description. If
+# set to NO, the Qt-style will behave just like regular Qt-style comments (thus
+# requiring an explicit \brief command for a brief description.)
+# The default value is: NO.
 
 QT_AUTOBRIEF           = NO
 
-# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make Doxygen
-# treat a multi-line C++ special comment block (i.e. a block of //! or ///
-# comments) as a brief description. This used to be the default behaviour.
-# The new default is to treat a multi-line C++ comment block as a detailed
-# description. Set this tag to YES if you prefer the old behaviour instead.
+# The MULTILINE_CPP_IS_BRIEF tag can be set to YES to make doxygen treat a
+# multi-line C++ special comment block (i.e. a block of //! or /// comments) as
+# a brief description. This used to be the default behavior. The new default is
+# to treat a multi-line C++ comment block as a detailed description. Set this
+# tag to YES if you prefer the old behavior instead.
+#
+# Note that setting this tag to YES also means that rational rose comments are
+# not recognized any more.
+# The default value is: NO.
 
 MULTILINE_CPP_IS_BRIEF = NO
 
-# If the INHERIT_DOCS tag is set to YES (the default) then an undocumented
-# member inherits the documentation from any documented member that it
-# re-implements.
+# If the INHERIT_DOCS tag is set to YES then an undocumented member inherits the
+# documentation from any documented member that it re-implements.
+# The default value is: YES.
 
 INHERIT_DOCS           = YES
 
-# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce
-# a new page for each member. If set to NO, the documentation of a member will
-# be part of the file/class/namespace that contains it.
+# If the SEPARATE_MEMBER_PAGES tag is set to YES, then doxygen will produce a
+# new page for each member. If set to NO, the documentation of a member will be
+# part of the file/class/namespace that contains it.
+# The default value is: NO.
 
 SEPARATE_MEMBER_PAGES  = NO
 
-# The TAB_SIZE tag can be used to set the number of spaces in a tab.
-# Doxygen uses this value to replace tabs by spaces in code fragments.
-
-TAB_SIZE               = 8
-
-# This tag can be used to specify a number of aliases that acts
-# as commands in the documentation. An alias has the form "name=value".
-# For example adding "sideeffect=\par Side Effects:\n" will allow you to
-# put the command \sideeffect (or @sideeffect) in the documentation, which
-# will result in a user-defined paragraph with heading "Side Effects:".
-# You can put \n's in the value part of an alias to insert newlines.
+# The TAB_SIZE tag can be used to set the number of spaces in a tab. Doxygen
+# uses this value to replace tabs by spaces in code fragments.
+# Minimum value: 1, maximum value: 16, default value: 4.
+
+TAB_SIZE               = 3
+
+# This tag can be used to specify a number of aliases that act as commands in
+# the documentation. An alias has the form:
+# name=value
+# For example adding
+# "sideeffect=@par Side Effects:\n"
+# will allow you to put the command \sideeffect (or @sideeffect) in the
+# documentation, which will result in a user-defined paragraph with heading
+# "Side Effects:". You can put \n's in the value part of an alias to insert
+# newlines.
 
 ALIASES                =
 
-# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C
-# sources only. Doxygen will then generate output that is more tailored for C.
-# For instance, some of the names that are used will be different. The list
-# of all members will be omitted, etc.
+# This tag can be used to specify a number of word-keyword mappings (TCL only).
+# A mapping has the form "name=value". For example adding "class=itcl::class"
+# will allow you to use the command class in the itcl::class meaning.
+
+TCL_SUBST              =
+
+# Set the OPTIMIZE_OUTPUT_FOR_C tag to YES if your project consists of C sources
+# only. Doxygen will then generate output that is more tailored for C. For
+# instance, some of the names that are used will be different. The list of all
+# members will be omitted, etc.
+# The default value is: NO.
 
 OPTIMIZE_OUTPUT_FOR_C  = NO
 
-# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java
-# sources only. Doxygen will then generate output that is more tailored for
-# Java. For instance, namespaces will be presented as packages, qualified
-# scopes will look different, etc.
+# Set the OPTIMIZE_OUTPUT_JAVA tag to YES if your project consists of Java or
+# Python sources only. Doxygen will then generate output that is more tailored
+# for that language. For instance, namespaces will be presented as packages,
+# qualified scopes will look different, etc.
+# The default value is: NO.
 
 OPTIMIZE_OUTPUT_JAVA   = NO
 
 # Set the OPTIMIZE_FOR_FORTRAN tag to YES if your project consists of Fortran
-# sources only. Doxygen will then generate output that is more tailored for
-# Fortran.
-
-OPTIMIZE_FOR_FORTRAN   = YES 
+# sources. Doxygen will then generate output that is tailored for Fortran.
+# The default value is: NO.
+
+OPTIMIZE_FOR_FORTRAN   = NO
 
 # Set the OPTIMIZE_OUTPUT_VHDL tag to YES if your project consists of VHDL
-# sources. Doxygen will then generate output that is tailored for
-# VHDL.
+# sources. Doxygen will then generate output that is tailored for VHDL.
+# The default value is: NO.
 
 OPTIMIZE_OUTPUT_VHDL   = NO
 
-# Doxygen selects the parser to use depending on the extension of the files it parses.
-# With this tag you can assign which parser to use for a given extension.
-# Doxygen has a built-in mapping, but you can override or extend it using this tag.
-# The format is ext=language, where ext is a file extension, and language is one of
-# the parsers supported by doxygen: IDL, Java, Javascript, C#, C, C++, D, PHP,
-# Objective-C, Python, Fortran, VHDL, C, C++. For instance to make doxygen treat
-# .inc files as Fortran files (default is PHP), and .f files as C (default is Fortran),
-# use: inc=Fortran f=C. Note that for custom extensions you also need to set FILE_PATTERNS otherwise the files are not read by doxygen.
-
-EXTENSION_MAPPING      =
+# Doxygen selects the parser to use depending on the extension of the files it
+# parses. With this tag you can assign which parser to use for a given
+# extension. Doxygen has a built-in mapping, but you can override or extend it
+# using this tag. The format is ext=language, where ext is a file extension, and
+# language is one of the parsers supported by doxygen: IDL, Java, Javascript,
+# C#, C, C++, D, PHP, Objective-C, Python, Fortran (fixed format Fortran:
+# FortranFixed, free formatted Fortran: FortranFree, unknown formatted Fortran:
+# Fortran. In the later case the parser tries to guess whether the code is fixed
+# or free formatted code, this is the default for Fortran type files), VHDL. For
+# instance to make doxygen treat .inc files as Fortran files (default is PHP),
+# and .f files as C (default is Fortran), use: inc=Fortran f=C.
+#
+# Note For files without extension you can use no_extension as a placeholder.
+#
+# Note that for custom extensions you also need to set FILE_PATTERNS otherwise
+# the files are not read by doxygen.
+
+EXTENSION_MAPPING      = 
+
+# If the MARKDOWN_SUPPORT tag is enabled then doxygen pre-processes all comments
+# according to the Markdown format, which allows for more readable
+# documentation. See http://daringfireball.net/projects/markdown/ for details.
+# The output of markdown processing is further processed by doxygen, so you can
+# mix doxygen, HTML, and XML commands with Markdown formatting. Disable only in
+# case of backward compatibilities issues.
+# The default value is: YES.
+
+MARKDOWN_SUPPORT       = YES
+
+# When enabled doxygen tries to link words that correspond to documented
+# classes, or namespaces to their corresponding documentation. Such a link can
+# be prevented in individual cases by by putting a % sign in front of the word
+# or globally by setting AUTOLINK_SUPPORT to NO.
+# The default value is: YES.
+
+AUTOLINK_SUPPORT       = YES
 
 # If you use STL classes (i.e. std::string, std::vector, etc.) but do not want
-# to include (a tag file for) the STL sources as input, then you should
-# set this tag to YES in order to let doxygen match functions declarations and
-# definitions whose arguments contain STL classes (e.g. func(std::string); v.s.
-# func(std::string) {}). This also make the inheritance and collaboration
+# to include (a tag file for) the STL sources as input, then you should set this
+# tag to YES in order to let doxygen match functions declarations and
+# definitions whose arguments contain STL classes (e.g. func(std::string);
+# versus func(std::string) {}). This also make the inheritance and collaboration
 # diagrams that involve STL classes more complete and accurate.
+# The default value is: NO.
 
 BUILTIN_STL_SUPPORT    = NO
@@ -230,19 +314,23 @@
 # If you use Microsoft's C++/CLI language, you should set this option to YES to
 # enable parsing support.
+# The default value is: NO.
 
 CPP_CLI_SUPPORT        = NO
 
-# Set the SIP_SUPPORT tag to YES if your project consists of sip sources only.
-# Doxygen will parse them like normal C++ but will assume all classes use public
-# instead of private inheritance when no explicit protection keyword is present.
+# Set the SIP_SUPPORT tag to YES if your project consists of sip (see:
+# http://www.riverbankcomputing.co.uk/software/sip/intro) sources only. Doxygen
+# will parse them like normal C++ but will assume all classes use public instead
+# of private inheritance when no explicit protection keyword is present.
+# The default value is: NO.
 
 SIP_SUPPORT            = NO
 
-# For Microsoft's IDL there are propget and propput attributes to indicate getter
-# and setter methods for a property. Setting this option to YES (the default)
-# will make doxygen to replace the get and set methods by a property in the
-# documentation. This will only work if the methods are indeed getting or
-# setting a simple type. If this is not the case, or you want to show the
-# methods anyway, you should set this option to NO.
+# For Microsoft's IDL there are propget and propput attributes to indicate
+# getter and setter methods for a property. Setting this option to YES will make
+# doxygen to replace the get and set methods by a property in the documentation.
+# This will only work if the methods are indeed getting or setting a simple
+# type. If this is not the case, or you want to show the methods anyway, you
+# should set this option to NO.
+# The default value is: YES.
 
 IDL_PROPERTY_SUPPORT   = YES
@@ -252,40 +340,61 @@
 # member in the group (if any) for the other members of the group. By default
 # all members of a group must be documented explicitly.
+# The default value is: NO.
 
 DISTRIBUTE_GROUP_DOC   = NO
 
-# Set the SUBGROUPING tag to YES (the default) to allow class member groups of
-# the same type (for instance a group of public functions) to be put as a
-# subgroup of that type (e.g. under the Public Functions section). Set it to
-# NO to prevent subgrouping. Alternatively, this can be done per class using
-# the \nosubgrouping command.
+# Set the SUBGROUPING tag to YES to allow class member groups of the same type
+# (for instance a group of public functions) to be put as a subgroup of that
+# type (e.g. under the Public Functions section). Set it to NO to prevent
+# subgrouping. Alternatively, this can be done per class using the
+# \nosubgrouping command.
+# The default value is: YES.
 
 SUBGROUPING            = YES
 
-# When TYPEDEF_HIDES_STRUCT is enabled, a typedef of a struct, union, or enum
-# is documented as struct, union, or enum with the name of the typedef. So
+# When the INLINE_GROUPED_CLASSES tag is set to YES, classes, structs and unions
+# are shown inside the group in which they are included (e.g. using \ingroup)
+# instead of on a separate page (for HTML and Man pages) or section (for LaTeX
+# and RTF).
+#
+# Note that this feature does not work in combination with
+# SEPARATE_MEMBER_PAGES.
+# The default value is: NO.
+
+INLINE_GROUPED_CLASSES = NO
+
+# When the INLINE_SIMPLE_STRUCTS tag is set to YES, structs, classes, and unions
+# with only public data fields or simple typedef fields will be shown inline in
+# the documentation of the scope in which they are defined (i.e. file,
+# namespace, or group documentation), provided this scope is documented. If set
+# to NO, structs, classes, and unions are shown on a separate page (for HTML and
+# Man pages) or section (for LaTeX and RTF).
+# The default value is: NO.
+
+INLINE_SIMPLE_STRUCTS  = NO
+
+# When TYPEDEF_HIDES_STRUCT tag is enabled, a typedef of a struct, union, or
+# enum is documented as struct, union, or enum with the name of the typedef. So
 # typedef struct TypeS {} TypeT, will appear in the documentation as a struct
 # with name TypeT. When disabled the typedef will appear as a member of a file,
-# namespace, or class. And the struct will be named TypeS. This can typically
-# be useful for C code in case the coding convention dictates that all compound
+# namespace, or class. And the struct will be named TypeS. This can typically be
+# useful for C code in case the coding convention dictates that all compound
 # types are typedef'ed and only the typedef is referenced, never the tag name.
+# The default value is: NO.
 
 TYPEDEF_HIDES_STRUCT   = NO
 
-# The SYMBOL_CACHE_SIZE determines the size of the internal cache use to
-# determine which symbols to keep in memory and which to flush to disk.
-# When the cache is full, less often used symbols will be written to disk.
-# For small to medium size projects (<1000 input files) the default value is
-# probably good enough. For larger projects a too small cache size can cause
-# doxygen to be busy swapping symbols to and from disk most of the time
-# causing a significant performance penality.
-# If the system has enough physical memory increasing the cache will improve the
-# performance by keeping more symbols in memory. Note that the value works on
-# a logarithmic scale so increasing the size by one will rougly double the
-# memory usage. The cache size is given by this formula:
-# 2^(16+SYMBOL_CACHE_SIZE). The valid range is 0..9, the default is 0,
-# corresponding to a cache size of 2^16 = 65536 symbols
-
-SYMBOL_CACHE_SIZE      = 0
+# The size of the symbol lookup cache can be set using LOOKUP_CACHE_SIZE. This
+# cache is used to resolve symbols given their name and scope. Since this can be
+# an expensive process and often the same symbol appears multiple times in the
+# code, doxygen keeps a cache of pre-resolved symbols. If the cache is too small
+# doxygen will become slower. If the cache is too large, memory is wasted. The
+# cache size is given by this formula: 2^(16+LOOKUP_CACHE_SIZE). The valid range
+# is 0..9, the default is 0, corresponding to a cache size of 2^16=65536
+# symbols. At the end of a run doxygen will report the cache usage and suggest
+# the optimal cache size from a speed point of view.
+# Minimum value: 0, maximum value: 9, default value: 0.
+
+LOOKUP_CACHE_SIZE      = 0
 
 #---------------------------------------------------------------------------
@@ -294,30 +403,44 @@
 
 # If the EXTRACT_ALL tag is set to YES doxygen will assume all entities in
-# documentation are documented, even if no documentation was available.
-# Private class members and static file members will be hidden unless
-# the EXTRACT_PRIVATE and EXTRACT_STATIC tags are set to YES
-
-EXTRACT_ALL            = YES 
-
-# If the EXTRACT_PRIVATE tag is set to YES all private members of a class
-# will be included in the documentation.
+# documentation are documented, even if no documentation was available. Private
+# class members and static file members will be hidden unless the
+# EXTRACT_PRIVATE respectively EXTRACT_STATIC tags are set to YES.
+# Note: This will also disable the warnings about undocumented members that are
+# normally produced when WARNINGS is set to YES.
+# The default value is: NO.
+
+EXTRACT_ALL            = NO
+
+# If the EXTRACT_PRIVATE tag is set to YES all private members of a class will
+# be included in the documentation.
+# The default value is: NO.
 
 EXTRACT_PRIVATE        = NO
 
-# If the EXTRACT_STATIC tag is set to YES all static members of a file
-# will be included in the documentation.
+# If the EXTRACT_PACKAGE tag is set to YES all members with package or internal
+# scope will be included in the documentation.
+# The default value is: NO.
+
+EXTRACT_PACKAGE        = NO
+
+# If the EXTRACT_STATIC tag is set to YES all static members of a file will be
+# included in the documentation.
+# The default value is: NO.
 
 EXTRACT_STATIC         = NO
 
-# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs)
-# defined locally in source files will be included in the documentation.
-# If set to NO only classes defined in header files are included.
+# If the EXTRACT_LOCAL_CLASSES tag is set to YES classes (and structs) defined
+# locally in source files will be included in the documentation. If set to NO
+# only classes defined in header files are included. Does not have any effect
+# for Java sources.
+# The default value is: YES.
 
 EXTRACT_LOCAL_CLASSES  = YES
 
-# This flag is only useful for Objective-C code. When set to YES local
-# methods, which are defined in the implementation section but not in
-# the interface are included in the documentation.
-# If set to NO (the default) only methods in the interface are included.
+# This flag is only useful for Objective-C code. When set to YES local methods,
+# which are defined in the implementation section but not in the interface are
+# included in the documentation. If set to NO only methods in the interface are
+# included.
+# The default value is: NO.
 
 EXTRACT_LOCAL_METHODS  = NO
@@ -325,166 +448,205 @@
 # If this flag is set to YES, the members of anonymous namespaces will be
 # extracted and appear in the documentation as a namespace called
-# 'anonymous_namespace{file}', where file will be replaced with the base
-# name of the file that contains the anonymous namespace. By default
-# anonymous namespace are hidden.
+# 'anonymous_namespace{file}', where file will be replaced with the base name of
+# the file that contains the anonymous namespace. By default anonymous namespace
+# are hidden.
+# The default value is: NO.
 
 EXTRACT_ANON_NSPACES   = NO
 
-# If the HIDE_UNDOC_MEMBERS tag is set to YES, Doxygen will hide all
-# undocumented members of documented classes, files or namespaces.
-# If set to NO (the default) these members will be included in the
-# various overviews, but no documentation section is generated.
-# This option has no effect if EXTRACT_ALL is enabled.
+# If the HIDE_UNDOC_MEMBERS tag is set to YES, doxygen will hide all
+# undocumented members inside documented classes or files. If set to NO these
+# members will be included in the various overviews, but no documentation
+# section is generated. This option has no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
 
 HIDE_UNDOC_MEMBERS     = NO
 
-# If the HIDE_UNDOC_CLASSES tag is set to YES, Doxygen will hide all
-# undocumented classes that are normally visible in the class hierarchy.
-# If set to NO (the default) these classes will be included in the various
-# overviews. This option has no effect if EXTRACT_ALL is enabled.
+# If the HIDE_UNDOC_CLASSES tag is set to YES, doxygen will hide all
+# undocumented classes that are normally visible in the class hierarchy. If set
+# to NO these classes will be included in the various overviews. This option has
+# no effect if EXTRACT_ALL is enabled.
+# The default value is: NO.
 
 HIDE_UNDOC_CLASSES     = NO
 
-# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, Doxygen will hide all
-# friend (class|struct|union) declarations.
-# If set to NO (the default) these declarations will be included in the
-# documentation.
+# If the HIDE_FRIEND_COMPOUNDS tag is set to YES, doxygen will hide all friend
+# (class|struct|union) declarations. If set to NO these declarations will be
+# included in the documentation.
+# The default value is: NO.
 
 HIDE_FRIEND_COMPOUNDS  = NO
 
-# If the HIDE_IN_BODY_DOCS tag is set to YES, Doxygen will hide any
-# documentation blocks found inside the body of a function.
-# If set to NO (the default) these blocks will be appended to the
-# function's detailed documentation block.
+# If the HIDE_IN_BODY_DOCS tag is set to YES, doxygen will hide any
+# documentation blocks found inside the body of a function. If set to NO these
+# blocks will be appended to the function's detailed documentation block.
+# The default value is: NO.
 
 HIDE_IN_BODY_DOCS      = NO
 
-# The INTERNAL_DOCS tag determines if documentation
-# that is typed after a \internal command is included. If the tag is set
-# to NO (the default) then the documentation will be excluded.
-# Set it to YES to include the internal documentation.
+# The INTERNAL_DOCS tag determines if documentation that is typed after a
+# \internal command is included. If the tag is set to NO then the documentation
+# will be excluded. Set it to YES to include the internal documentation.
+# The default value is: NO.
 
 INTERNAL_DOCS          = NO
 
-# If the CASE_SENSE_NAMES tag is set to NO then Doxygen will only generate
-# file names in lower-case letters. If set to YES upper-case letters are also
+# If the CASE_SENSE_NAMES tag is set to NO then doxygen will only generate file
+# names in lower-case letters. If set to YES upper-case letters are also
 # allowed. This is useful if you have classes or files whose names only differ
 # in case and if your file system supports case sensitive file names. Windows
 # and Mac users are advised to set this option to NO.
+# The default value is: system dependent.
 
 CASE_SENSE_NAMES       = YES
 
-# If the HIDE_SCOPE_NAMES tag is set to NO (the default) then Doxygen
-# will show members with their full class and namespace scopes in the
-# documentation. If set to YES the scope will be hidden.
+# If the HIDE_SCOPE_NAMES tag is set to NO then doxygen will show members with
+# their full class and namespace scopes in the documentation. If set to YES the
+# scope will be hidden.
+# The default value is: NO.
 
 HIDE_SCOPE_NAMES       = NO
 
-# If the SHOW_INCLUDE_FILES tag is set to YES (the default) then Doxygen
-# will put a list of the files that are included by a file in the documentation
-# of that file.
+# If the SHOW_INCLUDE_FILES tag is set to YES then doxygen will put a list of
+# the files that are included by a file in the documentation of that file.
+# The default value is: YES.
 
 SHOW_INCLUDE_FILES     = YES
 
-# If the INLINE_INFO tag is set to YES (the default) then a tag [inline]
-# is inserted in the documentation for inline members.
+# If the SHOW_GROUPED_MEMB_INC tag is set to YES then Doxygen will add for each
+# grouped member an include statement to the documentation, telling the reader
+# which file to include in order to use the member.
+# The default value is: NO.
+
+SHOW_GROUPED_MEMB_INC  = NO
+
+# If the FORCE_LOCAL_INCLUDES tag is set to YES then doxygen will list include
+# files with double quotes in the documentation rather than with sharp brackets.
+# The default value is: NO.
+
+FORCE_LOCAL_INCLUDES   = NO
+
+# If the INLINE_INFO tag is set to YES then a tag [inline] is inserted in the
+# documentation for inline members.
+# The default value is: YES.
 
 INLINE_INFO            = YES
 
-# If the SORT_MEMBER_DOCS tag is set to YES (the default) then doxygen
-# will sort the (detailed) documentation of file and class members
-# alphabetically by member name. If set to NO the members will appear in
-# declaration order.
+# If the SORT_MEMBER_DOCS tag is set to YES then doxygen will sort the
+# (detailed) documentation of file and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order.
+# The default value is: YES.
 
 SORT_MEMBER_DOCS       = YES
 
-# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the
-# brief documentation of file, namespace and class members alphabetically
-# by member name. If set to NO (the default) the members will appear in
-# declaration order.
+# If the SORT_BRIEF_DOCS tag is set to YES then doxygen will sort the brief
+# descriptions of file, namespace and class members alphabetically by member
+# name. If set to NO the members will appear in declaration order. Note that
+# this will also influence the order of the classes in the class list.
+# The default value is: NO.
 
 SORT_BRIEF_DOCS        = NO
 
-# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the (brief and detailed) documentation of class members so that constructors and destructors are listed first. If set to NO (the default) the constructors will appear in the respective orders defined by SORT_MEMBER_DOCS and SORT_BRIEF_DOCS. This tag will be ignored for brief docs if SORT_BRIEF_DOCS is set to NO and ignored for detailed docs if SORT_MEMBER_DOCS is set to NO.
+# If the SORT_MEMBERS_CTORS_1ST tag is set to YES then doxygen will sort the
+# (brief and detailed) documentation of class members so that constructors and
+# destructors are listed first. If set to NO the constructors will appear in the
+# respective orders defined by SORT_BRIEF_DOCS and SORT_MEMBER_DOCS.
+# Note: If SORT_BRIEF_DOCS is set to NO this option is ignored for sorting brief
+# member documentation.
+# Note: If SORT_MEMBER_DOCS is set to NO this option is ignored for sorting
+# detailed member documentation.
+# The default value is: NO.
 
 SORT_MEMBERS_CTORS_1ST = NO
 
-# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the
-# hierarchy of group names into alphabetical order. If set to NO (the default)
-# the group names will appear in their defined order.
+# If the SORT_GROUP_NAMES tag is set to YES then doxygen will sort the hierarchy
+# of group names into alphabetical order. If set to NO the group names will
+# appear in their defined order.
+# The default value is: NO.
 
 SORT_GROUP_NAMES       = NO
 
-# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be
-# sorted by fully-qualified names, including namespaces. If set to
-# NO (the default), the class list will be sorted only by class name,
-# not including the namespace part.
+# If the SORT_BY_SCOPE_NAME tag is set to YES, the class list will be sorted by
+# fully-qualified names, including namespaces. If set to NO, the class list will
+# be sorted only by class name, not including the namespace part.
 # Note: This option is not very useful if HIDE_SCOPE_NAMES is set to YES.
-# Note: This option applies only to the class list, not to the
-# alphabetical list.
+# Note: This option applies only to the class list, not to the alphabetical
+# list.
+# The default value is: NO.
 
 SORT_BY_SCOPE_NAME     = NO
 
-# The GENERATE_TODOLIST tag can be used to enable (YES) or
-# disable (NO) the todo list. This list is created by putting \todo
-# commands in the documentation.
+# If the STRICT_PROTO_MATCHING option is enabled and doxygen fails to do proper
+# type resolution of all parameters of a function it will reject a match between
+# the prototype and the implementation of a member function even if there is
+# only one candidate or it is obvious which candidate to choose by doing a
+# simple string match. By disabling STRICT_PROTO_MATCHING doxygen will still
+# accept a match between prototype and implementation in such cases.
+# The default value is: NO.
+
+STRICT_PROTO_MATCHING  = NO
+
+# The GENERATE_TODOLIST tag can be used to enable ( YES) or disable ( NO) the
+# todo list. This list is created by putting \todo commands in the
+# documentation.
+# The default value is: YES.
 
 GENERATE_TODOLIST      = YES
 
-# The GENERATE_TESTLIST tag can be used to enable (YES) or
-# disable (NO) the test list. This list is created by putting \test
-# commands in the documentation.
+# The GENERATE_TESTLIST tag can be used to enable ( YES) or disable ( NO) the
+# test list. This list is created by putting \test commands in the
+# documentation.
+# The default value is: YES.
 
 GENERATE_TESTLIST      = YES
 
-# The GENERATE_BUGLIST tag can be used to enable (YES) or
-# disable (NO) the bug list. This list is created by putting \bug
-# commands in the documentation.
+# The GENERATE_BUGLIST tag can be used to enable ( YES) or disable ( NO) the bug
+# list. This list is created by putting \bug commands in the documentation.
+# The default value is: YES.
 
 GENERATE_BUGLIST       = YES
 
-# The GENERATE_DEPRECATEDLIST tag can be used to enable (YES) or
-# disable (NO) the deprecated list. This list is created by putting
-# \deprecated commands in the documentation.
+# The GENERATE_DEPRECATEDLIST tag can be used to enable ( YES) or disable ( NO)
+# the deprecated list. This list is created by putting \deprecated commands in
+# the documentation.
+# The default value is: YES.
 
 GENERATE_DEPRECATEDLIST= YES
 
-# The ENABLED_SECTIONS tag can be used to enable conditional
-# documentation sections, marked by \if sectionname ... \endif.
+# The ENABLED_SECTIONS tag can be used to enable conditional documentation
+# sections, marked by \if <section_label> ... \endif and \cond <section_label>
+# ... \endcond blocks.
 
 ENABLED_SECTIONS       =
 
-# The MAX_INITIALIZER_LINES tag determines the maximum number of lines
-# the initial value of a variable or define consists of for it to appear in
-# the documentation. If the initializer consists of more lines than specified
-# here it will be hidden. Use a value of 0 to hide initializers completely.
-# The appearance of the initializer of individual variables and defines in the
-# documentation can be controlled using \showinitializer or \hideinitializer
-# command in the documentation regardless of this setting.
+# The MAX_INITIALIZER_LINES tag determines the maximum number of lines that the
+# initial value of a variable or macro / define can have for it to appear in the
+# documentation. If the initializer consists of more lines than specified here
+# it will be hidden. Use a value of 0 to hide initializers completely. The
+# appearance of the value of individual variables and macros / defines can be
+# controlled using \showinitializer or \hideinitializer command in the
+# documentation regardless of this setting.
+# Minimum value: 0, maximum value: 10000, default value: 30.
 
 MAX_INITIALIZER_LINES  = 30
 
-# Set the SHOW_USED_FILES tag to NO to disable the list of files generated
-# at the bottom of the documentation of classes and structs. If set to YES the
-# list will mention the files that were used to generate the documentation.
+# Set the SHOW_USED_FILES tag to NO to disable the list of files generated at
+# the bottom of the documentation of classes and structs. If set to YES the list
+# will mention the files that were used to generate the documentation.
+# The default value is: YES.
 
 SHOW_USED_FILES        = YES
 
-# If the sources in your project are distributed over multiple directories
-# then setting the SHOW_DIRECTORIES tag to YES will show the directory hierarchy
-# in the documentation. The default is NO.
-
-SHOW_DIRECTORIES       = NO
-
-# Set the SHOW_FILES tag to NO to disable the generation of the Files page.
-# This will remove the Files entry from the Quick Index and from the
-# Folder Tree View (if specified). The default is YES.
+# Set the SHOW_FILES tag to NO to disable the generation of the Files page. This
+# will remove the Files entry from the Quick Index and from the Folder Tree View
+# (if specified).
+# The default value is: YES.
 
 SHOW_FILES             = YES
 
-# Set the SHOW_NAMESPACES tag to NO to disable the generation of the
-# Namespaces page.
-# This will remove the Namespaces entry from the Quick Index
-# and from the Folder Tree View (if specified). The default is YES.
+# Set the SHOW_NAMESPACES tag to NO to disable the generation of the Namespaces
+# page. This will remove the Namespaces entry from the Quick Index and from the
+# Folder Tree View (if specified).
+# The default value is: YES.
 
 SHOW_NAMESPACES        = YES
@@ -493,114 +655,144 @@
 # doxygen should invoke to get the current version for each file (typically from
 # the version control system). Doxygen will invoke the program by executing (via
-# popen()) the command <command> <input-file>, where <command> is the value of
-# the FILE_VERSION_FILTER tag, and <input-file> is the name of an input file
-# provided by doxygen. Whatever the program writes to standard output
-# is used as the file version. See the manual for examples.
+# popen()) the command command input-file, where command is the value of the
+# FILE_VERSION_FILTER tag, and input-file is the name of an input file provided
+# by doxygen. Whatever the program writes to standard output is used as the file
+# version. For an example see the documentation.
 
 FILE_VERSION_FILTER    =
 
-# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed by
-# doxygen. The layout file controls the global structure of the generated output files
-# in an output format independent way. The create the layout file that represents
-# doxygen's defaults, run doxygen with the -l option. You can optionally specify a
-# file name after the option, if omitted DoxygenLayout.xml will be used as the name
-# of the layout file.
+# The LAYOUT_FILE tag can be used to specify a layout file which will be parsed
+# by doxygen. The layout file controls the global structure of the generated
+# output files in an output format independent way. To create the layout file
+# that represents doxygen's defaults, run doxygen with the -l option. You can
+# optionally specify a file name after the option, if omitted DoxygenLayout.xml
+# will be used as the name of the layout file.
+#
+# Note that if you run doxygen from a directory containing a file called
+# DoxygenLayout.xml, doxygen will parse it automatically even if the LAYOUT_FILE
+# tag is left empty.
 
 LAYOUT_FILE            =
 
-#---------------------------------------------------------------------------
-# configuration options related to warning and progress messages
-#---------------------------------------------------------------------------
-
-# The QUIET tag can be used to turn on/off the messages that are generated
-# by doxygen. Possible values are YES and NO. If left blank NO is used.
+# The CITE_BIB_FILES tag can be used to specify one or more bib files containing
+# the reference definitions. This must be a list of .bib files. The .bib
+# extension is automatically appended if omitted. This requires the bibtex tool
+# to be installed. See also http://en.wikipedia.org/wiki/BibTeX for more info.
+# For LaTeX the style of the bibliography can be controlled using
+# LATEX_BIB_STYLE. To use this feature you need bibtex and perl available in the
+# search path. See also \cite for info how to create references.
+
+CITE_BIB_FILES         =
+
+#---------------------------------------------------------------------------
+# Configuration options related to warning and progress messages
+#---------------------------------------------------------------------------
+
+# The QUIET tag can be used to turn on/off the messages that are generated to
+# standard output by doxygen. If QUIET is set to YES this implies that the
+# messages are off.
+# The default value is: NO.
 
 QUIET                  = NO
 
 # The WARNINGS tag can be used to turn on/off the warning messages that are
-# generated by doxygen. Possible values are YES and NO. If left blank
-# NO is used.
+# generated to standard error ( stderr) by doxygen. If WARNINGS is set to YES
+# this implies that the warnings are on.
+#
+# Tip: Turn warnings on while writing the documentation.
+# The default value is: YES.
 
 WARNINGS               = YES
 
-# If WARN_IF_UNDOCUMENTED is set to YES, then doxygen will generate warnings
-# for undocumented members. If EXTRACT_ALL is set to YES then this flag will
-# automatically be disabled.
+# If the WARN_IF_UNDOCUMENTED tag is set to YES, then doxygen will generate
+# warnings for undocumented members. If EXTRACT_ALL is set to YES then this flag
+# will automatically be disabled.
+# The default value is: YES.
 
 WARN_IF_UNDOCUMENTED   = YES
 
-# If WARN_IF_DOC_ERROR is set to YES, doxygen will generate warnings for
-# potential errors in the documentation, such as not documenting some
-# parameters in a documented function, or documenting parameters that
-# don't exist or using markup commands wrongly.
+# If the WARN_IF_DOC_ERROR tag is set to YES, doxygen will generate warnings for
+# potential errors in the documentation, such as not documenting some parameters
+# in a documented function, or documenting parameters that don't exist or using
+# markup commands wrongly.
+# The default value is: YES.
 
 WARN_IF_DOC_ERROR      = YES
 
-# This WARN_NO_PARAMDOC option can be abled to get warnings for
-# functions that are documented, but have no documentation for their parameters
-# or return value. If set to NO (the default) doxygen will only warn about
-# wrong or incomplete parameter documentation, but not about the absence of
-# documentation.
+# This WARN_NO_PARAMDOC option can be enabled to get warnings for functions that
+# are documented, but have no documentation for their parameters or return
+# value. If set to NO doxygen will only warn about wrong or incomplete parameter
+# documentation, but not about the absence of documentation.
+# The default value is: NO.
 
 WARN_NO_PARAMDOC       = NO
 
-# The WARN_FORMAT tag determines the format of the warning messages that
-# doxygen can produce. The string should contain the $file, $line, and $text
-# tags, which will be replaced by the file and line number from which the
-# warning originated and the warning text. Optionally the format may contain
-# $version, which will be replaced by the version of the file (if it could
-# be obtained via FILE_VERSION_FILTER)
+# The WARN_FORMAT tag determines the format of the warning messages that doxygen
+# can produce. The string should contain the $file, $line, and $text tags, which
+# will be replaced by the file and line number from which the warning originated
+# and the warning text. Optionally the format may contain $version, which will
+# be replaced by the version of the file (if it could be obtained via
+# FILE_VERSION_FILTER)
+# The default value is: $file:$line: $text.
 
 WARN_FORMAT            = "$file:$line: $text"
 
-# The WARN_LOGFILE tag can be used to specify a file to which warning
-# and error messages should be written. If left blank the output is written
-# to stderr.
+# The WARN_LOGFILE tag can be used to specify a file to which warning and error
+# messages should be written. If left blank the output is written to standard
+# error (stderr).
 
 WARN_LOGFILE           =
 
 #---------------------------------------------------------------------------
-# configuration options related to the input files
-#---------------------------------------------------------------------------
-
-# The INPUT tag can be used to specify the files and/or directories that contain
-# documented source files. You may enter file names like "myfile.cpp" or
-# directories like "/usr/src/myproject". Separate the files or directories
-# with spaces.
-
-INPUT                  =
+# Configuration options related to the input files
+#---------------------------------------------------------------------------
+
+# The INPUT tag is used to specify the files and/or directories that contain
+# documented source files. You may enter file names like myfile.cpp or
+# directories like /usr/src/myproject. Separate the files or directories with
+# spaces.
+# Note: If this tag is empty the current directory is searched.
+
+INPUT                  = . ./docsrc
 
 # This tag can be used to specify the character encoding of the source files
-# that doxygen parses. Internally doxygen uses the UTF-8 encoding, which is
-# also the default input encoding. Doxygen uses libiconv (or the iconv built
-# into libc) for the transcoding. See http://www.gnu.org/software/libiconv for
-# the list of possible encodings.
+# that doxygen parses. Internally doxygen uses the UTF-8 encoding. Doxygen uses
+# libiconv (or the iconv built into libc) for the transcoding. See the libiconv
+# documentation (see: http://www.gnu.org/software/libiconv) for the list of
+# possible encodings.
+# The default value is: UTF-8.
 
 INPUT_ENCODING         = UTF-8
 
 # If the value of the INPUT tag contains directories, you can use the
-# FILE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
-# and *.h) to filter out the source-files in the directories. If left
-# blank the following patterns are tested:
-# *.c *.cc *.cxx *.cpp *.c++ *.java *.ii *.ixx *.ipp *.i++ *.inl *.h *.hh *.hxx
-# *.hpp *.h++ *.idl *.odl *.cs *.php *.php3 *.inc *.m *.mm *.py *.f90
-
-FILE_PATTERNS          = *.f90 
-
-# The RECURSIVE tag can be used to turn specify whether or not subdirectories
-# should be searched for input files as well. Possible values are YES and NO.
-# If left blank NO is used.
+# FILE_PATTERNS tag to specify one or more wildcard patterns (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank the
+# following patterns are tested:*.c, *.cc, *.cxx, *.cpp, *.c++, *.java, *.ii,
+# *.ixx, *.ipp, *.i++, *.inl, *.idl, *.ddl, *.odl, *.h, *.hh, *.hxx, *.hpp,
+# *.h++, *.cs, *.d, *.php, *.php4, *.php5, *.phtml, *.inc, *.m, *.markdown,
+# *.md, *.mm, *.dox, *.py, *.f90, *.f, *.for, *.tcl, *.vhd, *.vhdl, *.ucf,
+# *.qsf, *.as and *.js.
+
+FILE_PATTERNS          = 
+
+# The RECURSIVE tag can be used to specify whether or not subdirectories should
+# be searched for input files as well.
+# The default value is: NO.
 
 RECURSIVE              = NO
 
-# The EXCLUDE tag can be used to specify files and/or directories that should
+# The EXCLUDE tag can be used to specify files and/or directories that should be
 # excluded from the INPUT source files. This way you can easily exclude a
 # subdirectory from a directory tree whose root is specified with the INPUT tag.
+#
+# Note that relative paths are relative to the directory from which doxygen is
+# run.
 
 EXCLUDE                =
 
-# The EXCLUDE_SYMLINKS tag can be used select whether or not files or
-# directories that are symbolic links (a Unix filesystem feature) are excluded
+# The EXCLUDE_SYMLINKS tag can be used to select whether or not files or
+# directories that are symbolic links (a Unix file system feature) are excluded
 # from the input.
+# The default value is: NO.
 
 EXCLUDE_SYMLINKS       = NO
@@ -608,7 +800,8 @@
 # If the value of the INPUT tag contains directories, you can use the
 # EXCLUDE_PATTERNS tag to specify one or more wildcard patterns to exclude
-# certain files from those directories. Note that the wildcards are matched
-# against the file with absolute path, so to exclude all test directories
-# for example use the pattern */test/*
+# certain files from those directories.
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories for example use the pattern */test/*
 
 EXCLUDE_PATTERNS       =
@@ -619,596 +812,1087 @@
 # wildcard * is used, a substring. Examples: ANamespace, AClass,
 # AClass::ANamespace, ANamespace::*Test
+#
+# Note that the wildcards are matched against the file with absolute path, so to
+# exclude all test directories use the pattern */test/*
 
 EXCLUDE_SYMBOLS        =
 
-# The EXAMPLE_PATH tag can be used to specify one or more files or
-# directories that contain example code fragments that are included (see
-# the \include command).
+# The EXAMPLE_PATH tag can be used to specify one or more files or directories
+# that contain example code fragments that are included (see the \include
+# command).
 
 EXAMPLE_PATH           =
 
 # If the value of the EXAMPLE_PATH tag contains directories, you can use the
-# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp
-# and *.h) to filter out the source-files in the directories. If left
-# blank all files are included.
+# EXAMPLE_PATTERNS tag to specify one or more wildcard pattern (like *.cpp and
+# *.h) to filter out the source-files in the directories. If left blank all
+# files are included.
 
 EXAMPLE_PATTERNS       =
 
 # If the EXAMPLE_RECURSIVE tag is set to YES then subdirectories will be
-# searched for input files to be used with the \include or \dontinclude
-# commands irrespective of the value of the RECURSIVE tag.
-# Possible values are YES and NO. If left blank NO is used.
+# searched for input files to be used with the \include or \dontinclude commands
+# irrespective of the value of the RECURSIVE tag.
+# The default value is: NO.
 
 EXAMPLE_RECURSIVE      = NO
 
-# The IMAGE_PATH tag can be used to specify one or more files or
-# directories that contain image that are included in the documentation (see
-# the \image command).
-
-IMAGE_PATH             = 
+# The IMAGE_PATH tag can be used to specify one or more files or directories
+# that contain images that are to be included in the documentation (see the
+# \image command).
+
+IMAGE_PATH             = ./docsrc/Image
 
 # The INPUT_FILTER tag can be used to specify a program that doxygen should
 # invoke to filter for each input file. Doxygen will invoke the filter program
-# by executing (via popen()) the command <filter> <input-file>, where <filter>
-# is the value of the INPUT_FILTER tag, and <input-file> is the name of an
-# input file. Doxygen will then use the output that the filter program writes
-# to standard output.
-# If FILTER_PATTERNS is specified, this tag will be
-# ignored.
+# by executing (via popen()) the command:
+#
+# <filter> <input-file>
+#
+# where <filter> is the value of the INPUT_FILTER tag, and <input-file> is the
+# name of an input file. Doxygen will then use the output that the filter
+# program writes to standard output. If FILTER_PATTERNS is specified, this tag
+# will be ignored.
+#
+# Note that the filter must not add or remove lines; it is applied before the
+# code is scanned, but not when the output code is generated. If lines are added
+# or removed, the anchors will not be placed correctly.
 
 INPUT_FILTER           =
 
 # The FILTER_PATTERNS tag can be used to specify filters on a per file pattern
-# basis.
-# Doxygen will compare the file name with each pattern and apply the
-# filter if there is a match.
-# The filters are a list of the form:
-# pattern=filter (like *.cpp=my_cpp_filter). See INPUT_FILTER for further
-# info on how filters are used. If FILTER_PATTERNS is empty, INPUT_FILTER
-# is applied to all files.
+# basis. Doxygen will compare the file name with each pattern and apply the
+# filter if there is a match. The filters are a list of the form: pattern=filter
+# (like *.cpp=my_cpp_filter). See INPUT_FILTER for further information on how
+# filters are used. If the FILTER_PATTERNS tag is empty or if none of the
+# patterns match the file name, INPUT_FILTER is applied.
 
 FILTER_PATTERNS        =
 
 # If the FILTER_SOURCE_FILES tag is set to YES, the input filter (if set using
-# INPUT_FILTER) will be used to filter the input files when producing source
-# files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# INPUT_FILTER ) will also be used to filter the input files that are used for
+# producing the source files to browse (i.e. when SOURCE_BROWSER is set to YES).
+# The default value is: NO.
 
 FILTER_SOURCE_FILES    = NO
 
-#---------------------------------------------------------------------------
-# configuration options related to source browsing
-#---------------------------------------------------------------------------
-
-# If the SOURCE_BROWSER tag is set to YES then a list of source files will
-# be generated. Documented entities will be cross-referenced with these sources.
-# Note: To get rid of all source code in the generated output, make sure also
-# VERBATIM_HEADERS is set to NO.
+# The FILTER_SOURCE_PATTERNS tag can be used to specify source filters per file
+# pattern. A pattern will override the setting for FILTER_PATTERN (if any) and
+# it is also possible to disable source filtering for a specific pattern using
+# *.ext= (so without naming a filter).
+# This tag requires that the tag FILTER_SOURCE_FILES is set to YES.
+
+FILTER_SOURCE_PATTERNS =
+
+# If the USE_MDFILE_AS_MAINPAGE tag refers to the name of a markdown file that
+# is part of the input, its contents will be placed on the main page
+# (index.html). This can be useful if you have a project on for instance GitHub
+# and want to reuse the introduction page also for the doxygen output.
+
+USE_MDFILE_AS_MAINPAGE =
+
+#---------------------------------------------------------------------------
+# Configuration options related to source browsing
+#---------------------------------------------------------------------------
+
+# If the SOURCE_BROWSER tag is set to YES then a list of source files will be
+# generated. Documented entities will be cross-referenced with these sources.
+#
+# Note: To get rid of all source code in the generated output, make sure that
+# also VERBATIM_HEADERS is set to NO.
+# The default value is: NO.
 
 SOURCE_BROWSER         = NO
 
-# Setting the INLINE_SOURCES tag to YES will include the body
-# of functions and classes directly in the documentation.
+# Setting the INLINE_SOURCES tag to YES will include the body of functions,
+# classes and enums directly into the documentation.
+# The default value is: NO.
 
 INLINE_SOURCES         = NO
 
-# Setting the STRIP_CODE_COMMENTS tag to YES (the default) will instruct
-# doxygen to hide any special comment blocks from generated source code
-# fragments. Normal C and C++ comments will always remain visible.
+# Setting the STRIP_CODE_COMMENTS tag to YES will instruct doxygen to hide any
+# special comment blocks from generated source code fragments. Normal C, C++ and
+# Fortran comments will always remain visible.
+# The default value is: YES.
 
 STRIP_CODE_COMMENTS    = YES
 
-# If the REFERENCED_BY_RELATION tag is set to YES
-# then for each documented function all documented
-# functions referencing it will be listed.
+# If the REFERENCED_BY_RELATION tag is set to YES then for each documented
+# function all documented functions referencing it will be listed.
+# The default value is: NO.
 
 REFERENCED_BY_RELATION = NO
 
-# If the REFERENCES_RELATION tag is set to YES
-# then for each documented function all documented entities
-# called/used by that function will be listed.
+# If the REFERENCES_RELATION tag is set to YES then for each documented function
+# all documented entities called/used by that function will be listed.
+# The default value is: NO.
 
 REFERENCES_RELATION    = NO
 
-# If the REFERENCES_LINK_SOURCE tag is set to YES (the default)
-# and SOURCE_BROWSER tag is set to YES, then the hyperlinks from
-# functions in REFERENCES_RELATION and REFERENCED_BY_RELATION lists will
-# link to the source code.
-# Otherwise they will link to the documentation.
+# If the REFERENCES_LINK_SOURCE tag is set to YES and SOURCE_BROWSER tag is set
+# to YES, then the hyperlinks from functions in REFERENCES_RELATION and
+# REFERENCED_BY_RELATION lists will link to the source code. Otherwise they will
+# link to the documentation.
+# The default value is: YES.
 
 REFERENCES_LINK_SOURCE = YES
 
-# If the USE_HTAGS tag is set to YES then the references to source code
-# will point to the HTML generated by the htags(1) tool instead of doxygen
-# built-in source browser. The htags tool is part of GNU's global source
-# tagging system (see http://www.gnu.org/software/global/global.html). You
-# will need version 4.8.6 or higher.
+# If SOURCE_TOOLTIPS is enabled (the default) then hovering a hyperlink in the
+# source code will show a tooltip with additional information such as prototype,
+# brief description and links to the definition and documentation. Since this
+# will make the HTML file larger and loading of large files a bit slower, you
+# can opt to disable this feature.
+# The default value is: YES.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
+
+SOURCE_TOOLTIPS        = YES
+
+# If the USE_HTAGS tag is set to YES then the references to source code will
+# point to the HTML generated by the htags(1) tool instead of doxygen built-in
+# source browser. The htags tool is part of GNU's global source tagging system
+# (see http://www.gnu.org/software/global/global.html). You will need version
+# 4.8.6 or higher.
+#
+# To use it do the following:
+# - Install the latest version of global
+# - Enable SOURCE_BROWSER and USE_HTAGS in the config file
+# - Make sure the INPUT points to the root of the source tree
+# - Run doxygen as normal
+#
+# Doxygen will invoke htags (and that will in turn invoke gtags), so these
+# tools must be available from the command line (i.e. in the search path).
+#
+# The result: instead of the source browser generated by doxygen, the links to
+# source code will now point to the output of htags.
+# The default value is: NO.
+# This tag requires that the tag SOURCE_BROWSER is set to YES.
 
 USE_HTAGS              = NO
 
-# If the VERBATIM_HEADERS tag is set to YES (the default) then Doxygen
-# will generate a verbatim copy of the header file for each class for
-# which an include is specified. Set to NO to disable this.
+# If the VERBATIM_HEADERS tag is set the YES then doxygen will generate a
+# verbatim copy of the header file for each class for which an include is
+# specified. Set to NO to disable this.
+# See also: Section \class.
+# The default value is: YES.
 
 VERBATIM_HEADERS       = YES
 
 #---------------------------------------------------------------------------
-# configuration options related to the alphabetical class index
-#---------------------------------------------------------------------------
-
-# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index
-# of all compounds will be generated. Enable this if the project
-# contains a lot of classes, structs, unions or interfaces.
+# Configuration options related to the alphabetical class index
+#---------------------------------------------------------------------------
+
+# If the ALPHABETICAL_INDEX tag is set to YES, an alphabetical index of all
+# compounds will be generated. Enable this if the project contains a lot of
+# classes, structs, unions or interfaces.
+# The default value is: YES.
 
 ALPHABETICAL_INDEX     = NO
 
-# If the alphabetical index is enabled (see ALPHABETICAL_INDEX) then
-# the COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns
-# in which this list will be split (can be a number in the range [1..20])
+# The COLS_IN_ALPHA_INDEX tag can be used to specify the number of columns in
+# which the alphabetical index list will be split.
+# Minimum value: 1, maximum value: 20, default value: 5.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
 
 COLS_IN_ALPHA_INDEX    = 5
 
-# In case all classes in a project start with a common prefix, all
-# classes will be put under the same header in the alphabetical index.
-# The IGNORE_PREFIX tag can be used to specify one or more prefixes that
-# should be ignored while generating the index headers.
+# In case all classes in a project start with a common prefix, all classes will
+# be put under the same header in the alphabetical index. The IGNORE_PREFIX tag
+# can be used to specify a prefix (or a list of prefixes) that should be ignored
+# while generating the index headers.
+# This tag requires that the tag ALPHABETICAL_INDEX is set to YES.
 
 IGNORE_PREFIX          =
 
 #---------------------------------------------------------------------------
-# configuration options related to the HTML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_HTML tag is set to YES (the default) Doxygen will
-# generate HTML output.
+# Configuration options related to the HTML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_HTML tag is set to YES doxygen will generate HTML output
+# The default value is: YES.
 
 GENERATE_HTML          = YES
 
-# The HTML_OUTPUT tag is used to specify where the HTML docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `html' will be used as the default path.
+# The HTML_OUTPUT tag is used to specify where the HTML docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_OUTPUT            = html
 
-# The HTML_FILE_EXTENSION tag can be used to specify the file extension for
-# each generated HTML page (for example: .htm,.php,.asp). If it is left blank
-# doxygen will generate files with .html extension.
+# The HTML_FILE_EXTENSION tag can be used to specify the file extension for each
+# generated HTML page (for example: .htm, .php, .asp).
+# The default value is: .html.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_FILE_EXTENSION    = .html
 
-# The HTML_HEADER tag can be used to specify a personal HTML header for
-# each generated HTML page. If it is left blank doxygen will generate a
+# The HTML_HEADER tag can be used to specify a user-defined HTML header file for
+# each generated HTML page. If the tag is left blank doxygen will generate a
 # standard header.
+#
+# To get valid HTML the header file that includes any scripts and style sheets
+# that doxygen needs, which is dependent on the configuration options used (e.g.
+# the setting GENERATE_TREEVIEW). It is highly recommended to start with a
+# default header using
+# doxygen -w html new_header.html new_footer.html new_stylesheet.css
+# YourConfigFile
+# and then modify the file new_header.html. See also section "Doxygen usage"
+# for information on how to generate the default header that doxygen normally
+# uses.
+# Note: The header is subject to change so you typically have to regenerate the
+# default header when upgrading to a newer version of doxygen. For a description
+# of the possible markers and block names see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_HEADER            =
 
-# The HTML_FOOTER tag can be used to specify a personal HTML footer for
-# each generated HTML page. If it is left blank doxygen will generate a
-# standard footer.
+# The HTML_FOOTER tag can be used to specify a user-defined HTML footer for each
+# generated HTML page. If the tag is left blank doxygen will generate a standard
+# footer. See HTML_HEADER for more information on how to generate a default
+# footer and what special commands can be used inside the footer. See also
+# section "Doxygen usage" for information on how to generate the default footer
+# that doxygen normally uses.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_FOOTER            =
 
-# If the HTML_TIMESTAMP tag is set to YES then the generated HTML
-# documentation will contain the timesstamp.
-
-HTML_TIMESTAMP         = NO
-
-# The HTML_STYLESHEET tag can be used to specify a user-defined cascading
-# style sheet that is used by each HTML page. It can be used to
-# fine-tune the look of the HTML output. If the tag is left blank doxygen
-# will generate a default style sheet. Note that doxygen will try to copy
-# the style sheet file to the HTML output directory, so don't put your own
-# stylesheet in the HTML output directory as well, or it will be erased!
+# The HTML_STYLESHEET tag can be used to specify a user-defined cascading style
+# sheet that is used by each HTML page. It can be used to fine-tune the look of
+# the HTML output. If left blank doxygen will generate a default style sheet.
+# See also section "Doxygen usage" for information on how to generate the style
+# sheet that doxygen normally uses.
+# Note: It is recommended to use HTML_EXTRA_STYLESHEET instead of this tag, as
+# it is more robust and this tag (HTML_STYLESHEET) will in the future become
+# obsolete.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_STYLESHEET        =
 
-# If the HTML_ALIGN_MEMBERS tag is set to YES, the members of classes,
-# files or namespaces will be aligned in HTML using tables. If set to
-# NO a bullet list will be used.
-
-HTML_ALIGN_MEMBERS     = YES
+# The HTML_EXTRA_STYLESHEET tag can be used to specify additional user-defined
+# cascading style sheets that are included after the standard style sheets
+# created by doxygen. Using this option one can overrule certain style aspects.
+# This is preferred over using HTML_STYLESHEET since it does not replace the
+# standard style sheet and is therefor more robust against future updates.
+# Doxygen will copy the style sheet files to the output directory.
+# Note: The order of the extra stylesheet files is of importance (e.g. the last
+# stylesheet in the list overrules the setting of the previous ones in the
+# list). For an example see the documentation.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_STYLESHEET  =
+
+# The HTML_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the HTML output directory. Note
+# that these files will be copied to the base HTML output directory. Use the
+# $relpath^ marker in the HTML_HEADER and/or HTML_FOOTER files to load these
+# files. In the HTML_STYLESHEET file, use the file name only. Also note that the
+# files will be copied as-is; there are no commands or markers available.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_EXTRA_FILES       =
+
+# The HTML_COLORSTYLE_HUE tag controls the color of the HTML output. Doxygen
+# will adjust the colors in the stylesheet and background images according to
+# this color. Hue is specified as an angle on a colorwheel, see
+# http://en.wikipedia.org/wiki/Hue for more information. For instance the value
+# 0 represents red, 60 is yellow, 120 is green, 180 is cyan, 240 is blue, 300
+# purple, and 360 is red again.
+# Minimum value: 0, maximum value: 359, default value: 220.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_HUE    = 220
+
+# The HTML_COLORSTYLE_SAT tag controls the purity (or saturation) of the colors
+# in the HTML output. For a value of 0 the output will use grayscales only. A
+# value of 255 will produce the most vivid colors.
+# Minimum value: 0, maximum value: 255, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_SAT    = 100
+
+# The HTML_COLORSTYLE_GAMMA tag controls the gamma correction applied to the
+# luminance component of the colors in the HTML output. Values below 100
+# gradually make the output lighter, whereas values above 100 make the output
+# darker. The value divided by 100 is the actual gamma applied, so 80 represents
+# a gamma of 0.8, The value 220 represents a gamma of 2.2, and 100 does not
+# change the gamma.
+# Minimum value: 40, maximum value: 240, default value: 80.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_COLORSTYLE_GAMMA  = 80
+
+# If the HTML_TIMESTAMP tag is set to YES then the footer of each generated HTML
+# page will contain the date and time when the page was generated. Setting this
+# to NO can help when comparing the output of multiple runs.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_TIMESTAMP         = YES
 
 # If the HTML_DYNAMIC_SECTIONS tag is set to YES then the generated HTML
 # documentation will contain sections that can be hidden and shown after the
-# page has loaded. For this to work a browser that supports
-# JavaScript and DHTML is required (for instance Mozilla 1.0+, Firefox
-# Netscape 6.0+, Internet explorer 5.0+, Konqueror, or Safari).
+# page has loaded.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 HTML_DYNAMIC_SECTIONS  = NO
 
-# If the GENERATE_DOCSET tag is set to YES, additional index files
-# will be generated that can be used as input for Apple's Xcode 3
-# integrated development environment, introduced with OSX 10.5 (Leopard).
-# To create a documentation set, doxygen will generate a Makefile in the
-# HTML output directory. Running make will produce the docset in that
-# directory and running "make install" will install the docset in
-# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find
-# it at startup.
-# See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html for more information.
+# With HTML_INDEX_NUM_ENTRIES one can control the preferred number of entries
+# shown in the various tree structured indices initially; the user can expand
+# and collapse entries dynamically later on. Doxygen will expand the tree to
+# such a level that at most the specified number of entries are visible (unless
+# a fully collapsed tree already exceeds this amount). So setting the number of
+# entries 1 will produce a full collapsed tree by default. 0 is a special value
+# representing an infinite number of entries and will result in a full expanded
+# tree by default.
+# Minimum value: 0, maximum value: 9999, default value: 100.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+HTML_INDEX_NUM_ENTRIES = 100
+
+# If the GENERATE_DOCSET tag is set to YES, additional index files will be
+# generated that can be used as input for Apple's Xcode 3 integrated development
+# environment (see: http://developer.apple.com/tools/xcode/), introduced with
+# OSX 10.5 (Leopard). To create a documentation set, doxygen will generate a
+# Makefile in the HTML output directory. Running make will produce the docset in
+# that directory and running make install will install the docset in
+# ~/Library/Developer/Shared/Documentation/DocSets so that Xcode will find it at
+# startup. See http://developer.apple.com/tools/creatingdocsetswithdoxygen.html
+# for more information.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 GENERATE_DOCSET        = NO
 
-# When GENERATE_DOCSET tag is set to YES, this tag determines the name of the
-# feed. A documentation feed provides an umbrella under which multiple
-# documentation sets from a single provider (such as a company or product suite)
-# can be grouped.
+# This tag determines the name of the docset feed. A documentation feed provides
+# an umbrella under which multiple documentation sets from a single provider
+# (such as a company or product suite) can be grouped.
+# The default value is: Doxygen generated docs.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
 
 DOCSET_FEEDNAME        = "Doxygen generated docs"
 
-# When GENERATE_DOCSET tag is set to YES, this tag specifies a string that
-# should uniquely identify the documentation set bundle. This should be a
-# reverse domain-name style string, e.g. com.mycompany.MyDocSet. Doxygen
-# will append .docset to the name.
+# This tag specifies a string that should uniquely identify the documentation
+# set bundle. This should be a reverse domain-name style string, e.g.
+# com.mycompany.MyDocSet. Doxygen will append .docset to the name.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
 
 DOCSET_BUNDLE_ID       = org.doxygen.Project
 
-# If the GENERATE_HTMLHELP tag is set to YES, additional index files
-# will be generated that can be used as input for tools like the
-# Microsoft HTML help workshop to generate a compiled HTML help file (.chm)
-# of the generated HTML documentation.
+# The DOCSET_PUBLISHER_ID tag specifies a string that should uniquely identify
+# the documentation publisher. This should be a reverse domain-name style
+# string, e.g. com.mycompany.MyDocSet.documentation.
+# The default value is: org.doxygen.Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_ID    = org.doxygen.Publisher
+
+# The DOCSET_PUBLISHER_NAME tag identifies the documentation publisher.
+# The default value is: Publisher.
+# This tag requires that the tag GENERATE_DOCSET is set to YES.
+
+DOCSET_PUBLISHER_NAME  = Publisher
+
+# If the GENERATE_HTMLHELP tag is set to YES then doxygen generates three
+# additional HTML index files: index.hhp, index.hhc, and index.hhk. The
+# index.hhp is a project file that can be read by Microsoft's HTML Help Workshop
+# (see: http://www.microsoft.com/en-us/download/details.aspx?id=21138) on
+# Windows.
+#
+# The HTML Help Workshop contains a compiler that can convert all HTML output
+# generated by doxygen into a single compiled HTML file (.chm). Compiled HTML
+# files are now used as the Windows 98 help format, and will replace the old
+# Windows help format (.hlp) on all Windows platforms in the future. Compressed
+# HTML files also contain an index, a table of contents, and you can search for
+# words in the documentation. The HTML workshop also contains a viewer for
+# compressed HTML files.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 GENERATE_HTMLHELP      = NO
 
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_FILE tag can
-# be used to specify the file name of the resulting .chm file. You
-# can add a path in front of the file if the result should not be
+# The CHM_FILE tag can be used to specify the file name of the resulting .chm
+# file. You can add a path in front of the file if the result should not be
 # written to the html output directory.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 CHM_FILE               =
 
-# If the GENERATE_HTMLHELP tag is set to YES, the HHC_LOCATION tag can
-# be used to specify the location (absolute path including file name) of
-# the HTML help compiler (hhc.exe). If non-empty doxygen will try to run
-# the HTML help compiler on the generated index.hhp.
+# The HHC_LOCATION tag can be used to specify the location (absolute path
+# including file name) of the HTML help compiler ( hhc.exe). If non-empty
+# doxygen will try to run the HTML help compiler on the generated index.hhp.
+# The file has to be specified with full path.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 HHC_LOCATION           =
 
-# If the GENERATE_HTMLHELP tag is set to YES, the GENERATE_CHI flag
-# controls if a separate .chi index file is generated (YES) or that
-# it should be included in the master .chm file (NO).
+# The GENERATE_CHI flag controls if a separate .chi index file is generated (
+# YES) or that it should be included in the master .chm file ( NO).
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 GENERATE_CHI           = NO
 
-# If the GENERATE_HTMLHELP tag is set to YES, the CHM_INDEX_ENCODING
-# is used to encode HtmlHelp index (hhk), content (hhc) and project file
-# content.
+# The CHM_INDEX_ENCODING is used to encode HtmlHelp index ( hhk), content ( hhc)
+# and project file content.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 CHM_INDEX_ENCODING     =
 
-# If the GENERATE_HTMLHELP tag is set to YES, the BINARY_TOC flag
-# controls whether a binary table of contents is generated (YES) or a
-# normal table of contents (NO) in the .chm file.
+# The BINARY_TOC flag controls whether a binary table of contents is generated (
+# YES) or a normal table of contents ( NO) in the .chm file. Furthermore it
+# enables the Previous and Next buttons.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 BINARY_TOC             = NO
 
-# The TOC_EXPAND flag can be set to YES to add extra items for group members
-# to the contents of the HTML help documentation and to the tree view.
+# The TOC_EXPAND flag can be set to YES to add extra items for group members to
+# the table of contents of the HTML help documentation and to the tree view.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTMLHELP is set to YES.
 
 TOC_EXPAND             = NO
 
-# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and QHP_VIRTUAL_FOLDER
-# are set, an additional index file will be generated that can be used as input for
-# Qt's qhelpgenerator to generate a Qt Compressed Help (.qch) of the generated
-# HTML documentation.
+# If the GENERATE_QHP tag is set to YES and both QHP_NAMESPACE and
+# QHP_VIRTUAL_FOLDER are set, an additional index file will be generated that
+# can be used as input for Qt's qhelpgenerator to generate a Qt Compressed Help
+# (.qch) of the generated HTML documentation.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 GENERATE_QHP           = NO
 
-# If the QHG_LOCATION tag is specified, the QCH_FILE tag can
-# be used to specify the file name of the resulting .qch file.
-# The path specified is relative to the HTML output folder.
+# If the QHG_LOCATION tag is specified, the QCH_FILE tag can be used to specify
+# the file name of the resulting .qch file. The path specified is relative to
+# the HTML output folder.
+# This tag requires that the tag GENERATE_QHP is set to YES.
 
 QCH_FILE               =
 
-# The QHP_NAMESPACE tag specifies the namespace to use when generating
-# Qt Help Project output. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#namespace
-
-QHP_NAMESPACE          =
-
-# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating
-# Qt Help Project output. For more information please see
-# http://doc.trolltech.com/qthelpproject.html#virtual-folders
+# The QHP_NAMESPACE tag specifies the namespace to use when generating Qt Help
+# Project output. For more information please see Qt Help Project / Namespace
+# (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#namespace).
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_QHP is set to YES.
+
+QHP_NAMESPACE          = org.doxygen.Project
+
+# The QHP_VIRTUAL_FOLDER tag specifies the namespace to use when generating Qt
+# Help Project output. For more information please see Qt Help Project / Virtual
+# Folders (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#virtual-
+# folders).
+# The default value is: doc.
+# This tag requires that the tag GENERATE_QHP is set to YES.
 
 QHP_VIRTUAL_FOLDER     = doc
 
-# If QHP_CUST_FILTER_NAME is set, it specifies the name of a custom filter to add.
-# For more information please see
-# http://doc.trolltech.com/qthelpproject.html#custom-filters
+# If the QHP_CUST_FILTER_NAME tag is set, it specifies the name of a custom
+# filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
 
 QHP_CUST_FILTER_NAME   =
 
-# The QHP_CUST_FILT_ATTRS tag specifies the list of the attributes of the custom filter to add.For more information please see
-# <a href="http://doc.trolltech.com/qthelpproject.html#custom-filters">Qt Help Project / Custom Filters</a>.
+# The QHP_CUST_FILTER_ATTRS tag specifies the list of the attributes of the
+# custom filter to add. For more information please see Qt Help Project / Custom
+# Filters (see: http://qt-project.org/doc/qt-4.8/qthelpproject.html#custom-
+# filters).
+# This tag requires that the tag GENERATE_QHP is set to YES.
 
 QHP_CUST_FILTER_ATTRS  =
 
-# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this project's
-# filter section matches.
-# <a href="http://doc.trolltech.com/qthelpproject.html#filter-attributes">Qt Help Project / Filter Attributes</a>.
+# The QHP_SECT_FILTER_ATTRS tag specifies the list of the attributes this
+# project's filter section matches. Qt Help Project / Filter Attributes (see:
+# http://qt-project.org/doc/qt-4.8/qthelpproject.html#filter-attributes).
+# This tag requires that the tag GENERATE_QHP is set to YES.
 
 QHP_SECT_FILTER_ATTRS  =
 
-# If the GENERATE_QHP tag is set to YES, the QHG_LOCATION tag can
-# be used to specify the location of Qt's qhelpgenerator.
-# If non-empty doxygen will try to run qhelpgenerator on the generated
-# .qhp file.
+# The QHG_LOCATION tag can be used to specify the location of Qt's
+# qhelpgenerator. If non-empty doxygen will try to run qhelpgenerator on the
+# generated .qhp file.
+# This tag requires that the tag GENERATE_QHP is set to YES.
 
 QHG_LOCATION           =
 
-# The DISABLE_INDEX tag can be used to turn on/off the condensed index at
-# top of each HTML page. The value NO (the default) enables the index and
-# the value YES disables it.
+# If the GENERATE_ECLIPSEHELP tag is set to YES, additional index files will be
+# generated, together with the HTML files, they form an Eclipse help plugin. To
+# install this plugin and make it available under the help contents menu in
+# Eclipse, the contents of the directory containing the HTML and XML files needs
+# to be copied into the plugins directory of eclipse. The name of the directory
+# within the plugins directory should be the same as the ECLIPSE_DOC_ID value.
+# After copying Eclipse needs to be restarted before the help appears.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_ECLIPSEHELP   = NO
+
+# A unique identifier for the Eclipse help plugin. When installing the plugin
+# the directory name containing the HTML and XML files should also have this
+# name. Each documentation set should have its own identifier.
+# The default value is: org.doxygen.Project.
+# This tag requires that the tag GENERATE_ECLIPSEHELP is set to YES.
+
+ECLIPSE_DOC_ID         = org.doxygen.Project
+
+# If you want full control over the layout of the generated HTML pages it might
+# be necessary to disable the index and replace it with your own. The
+# DISABLE_INDEX tag can be used to turn on/off the condensed index (tabs) at top
+# of each HTML page. A value of NO enables the index and the value YES disables
+# it. Since the tabs in the index contain the same information as the navigation
+# tree, you can set this option to YES if you also set GENERATE_TREEVIEW to YES.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 DISABLE_INDEX          = NO
 
-# This tag can be used to set the number of enum values (range [1..20])
-# that doxygen will group on one line in the generated HTML documentation.
+# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
+# structure should be generated to display hierarchical information. If the tag
+# value is set to YES, a side panel will be generated containing a tree-like
+# index structure (just like the one that is generated for HTML Help). For this
+# to work a browser that supports JavaScript, DHTML, CSS and frames is required
+# (i.e. any modern browser). Windows users are probably better off using the
+# HTML help feature. Via custom stylesheets (see HTML_EXTRA_STYLESHEET) one can
+# further fine-tune the look of the index. As an example, the default style
+# sheet generated by doxygen has an example that shows how to put an image at
+# the root of the tree instead of the PROJECT_NAME. Since the tree basically has
+# the same information as the tab index, you could consider setting
+# DISABLE_INDEX to YES when enabling this option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+GENERATE_TREEVIEW      = NO
+
+# The ENUM_VALUES_PER_LINE tag can be used to set the number of enum values that
+# doxygen will group on one line in the generated HTML documentation.
+#
+# Note that a value of 0 will completely suppress the enum values from appearing
+# in the overview section.
+# Minimum value: 0, maximum value: 20, default value: 4.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 ENUM_VALUES_PER_LINE   = 4
 
-# The GENERATE_TREEVIEW tag is used to specify whether a tree-like index
-# structure should be generated to display hierarchical information.
-# If the tag value is set to YES, a side panel will be generated
-# containing a tree-like index structure (just like the one that
-# is generated for HTML Help). For this to work a browser that supports
-# JavaScript, DHTML, CSS and frames is required (i.e. any modern browser).
-# Windows users are probably better off using the HTML help feature.
-
-GENERATE_TREEVIEW      = NO
-
-# By enabling USE_INLINE_TREES, doxygen will generate the Groups, Directories,
-# and Class Hierarchy pages using a tree view instead of an ordered list.
-
-USE_INLINE_TREES       = NO
-
-# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be
-# used to set the initial width (in pixels) of the frame in which the tree
-# is shown.
+# If the treeview is enabled (see GENERATE_TREEVIEW) then this tag can be used
+# to set the initial width (in pixels) of the frame in which the tree is shown.
+# Minimum value: 0, maximum value: 1500, default value: 250.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 TREEVIEW_WIDTH         = 250
 
-# Use this tag to change the font size of Latex formulas included
-# as images in the HTML documentation. The default is 10. Note that
-# when you change the font size after a successful doxygen run you need
-# to manually remove any form_*.png images from the HTML output directory
-# to force them to be regenerated.
+# When the EXT_LINKS_IN_WINDOW option is set to YES doxygen will open links to
+# external symbols imported via tag files in a separate window.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+EXT_LINKS_IN_WINDOW    = NO
+
+# Use this tag to change the font size of LaTeX formulas included as images in
+# the HTML documentation. When you change the font size after a successful
+# doxygen run you need to manually remove any form_*.png images from the HTML
+# output directory to force them to be regenerated.
+# Minimum value: 8, maximum value: 50, default value: 10.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 FORMULA_FONTSIZE       = 10
 
-# When the SEARCHENGINE tag is enable doxygen will generate a search box for the HTML output. The underlying search engine uses javascript
-# and DHTML and should work on any modern browser. Note that when using HTML help (GENERATE_HTMLHELP) or Qt help (GENERATE_QHP)
-# there is already a search function so this one should typically
-# be disabled.
+# Use the FORMULA_TRANPARENT tag to determine whether or not the images
+# generated for formulas are transparent PNGs. Transparent PNGs are not
+# supported properly for IE 6.0, but are supported on all modern browsers.
+#
+# Note that when changing this option you need to delete any form_*.png files in
+# the HTML output directory before the changes have effect.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+FORMULA_TRANSPARENT    = YES
+
+# Enable the USE_MATHJAX option to render LaTeX formulas using MathJax (see
+# http://www.mathjax.org) which uses client side Javascript for the rendering
+# instead of using prerendered bitmaps. Use this if you do not have LaTeX
+# installed or if you want to formulas look prettier in the HTML output. When
+# enabled you may also need to install MathJax separately and configure the path
+# to it using the MATHJAX_RELPATH option.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_HTML is set to YES.
+
+USE_MATHJAX            = NO
+
+# When MathJax is enabled you can set the default output format to be used for
+# the MathJax output. See the MathJax site (see:
+# http://docs.mathjax.org/en/latest/output.html) for more details.
+# Possible values are: HTML-CSS (which is slower, but has the best
+# compatibility), NativeMML (i.e. MathML) and SVG.
+# The default value is: HTML-CSS.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_FORMAT         = HTML-CSS
+
+# When MathJax is enabled you need to specify the location relative to the HTML
+# output directory using the MATHJAX_RELPATH option. The destination directory
+# should contain the MathJax.js script. For instance, if the mathjax directory
+# is located at the same level as the HTML output directory, then
+# MATHJAX_RELPATH should be ../mathjax. The default value points to the MathJax
+# Content Delivery Network so you can quickly see the result without installing
+# MathJax. However, it is strongly recommended to install a local copy of
+# MathJax from http://www.mathjax.org before deployment.
+# The default value is: http://cdn.mathjax.org/mathjax/latest.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_RELPATH        = http://cdn.mathjax.org/mathjax/latest
+
+# The MATHJAX_EXTENSIONS tag can be used to specify one or more MathJax
+# extension names that should be enabled during MathJax rendering. For example
+# MATHJAX_EXTENSIONS = TeX/AMSmath TeX/AMSsymbols
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_EXTENSIONS     =
+
+# The MATHJAX_CODEFILE tag can be used to specify a file with javascript pieces
+# of code that will be used on startup of the MathJax code. See the MathJax site
+# (see: http://docs.mathjax.org/en/latest/output.html) for more details. For an
+# example see the documentation.
+# This tag requires that the tag USE_MATHJAX is set to YES.
+
+MATHJAX_CODEFILE       =
+
+# When the SEARCHENGINE tag is enabled doxygen will generate a search box for
+# the HTML output. The underlying search engine uses javascript and DHTML and
+# should work on any modern browser. Note that when using HTML help
+# (GENERATE_HTMLHELP), Qt help (GENERATE_QHP), or docsets (GENERATE_DOCSET)
+# there is already a search function so this one should typically be disabled.
+# For large projects the javascript based search engine can be slow, then
+# enabling SERVER_BASED_SEARCH may provide a better solution. It is possible to
+# search using the keyboard; to jump to the search box use <access key> + S
+# (what the <access key> is depends on the OS and browser, but it is typically
+# <CTRL>, <ALT>/<option>, or both). Inside the search box use the <cursor down
+# key> to jump into the search results window, the results can be navigated
+# using the <cursor keys>. Press <Enter> to select an item or <escape> to cancel
+# the search. The filter options can be selected when the cursor is inside the
+# search box by pressing <Shift>+<cursor down>. Also here use the <cursor keys>
+# to select a filter and <Enter> or <escape> to activate or cancel the filter
+# option.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_HTML is set to YES.
 
 SEARCHENGINE           = YES
 
-#---------------------------------------------------------------------------
-# configuration options related to the LaTeX output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_LATEX tag is set to YES (the default) Doxygen will
-# generate Latex output.
+# When the SERVER_BASED_SEARCH tag is enabled the search engine will be
+# implemented using a web server instead of a web client using Javascript. There
+# are two flavors of web server based searching depending on the EXTERNAL_SEARCH
+# setting. When disabled, doxygen will generate a PHP script for searching and
+# an index file used by the script. When EXTERNAL_SEARCH is enabled the indexing
+# and searching needs to be provided by external tools. See the section
+# "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SERVER_BASED_SEARCH    = NO
+
+# When EXTERNAL_SEARCH tag is enabled doxygen will no longer generate the PHP
+# script for searching. Instead the search results are written to an XML file
+# which needs to be processed by an external indexer. Doxygen will invoke an
+# external search engine pointed to by the SEARCHENGINE_URL option to obtain the
+# search results.
+#
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/).
+#
+# See the section "External Indexing and Searching" for details.
+# The default value is: NO.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH        = NO
+
+# The SEARCHENGINE_URL should point to a search engine hosted by a web server
+# which will return the search results when EXTERNAL_SEARCH is enabled.
+#
+# Doxygen ships with an example indexer ( doxyindexer) and search engine
+# (doxysearch.cgi) which are based on the open source search engine library
+# Xapian (see: http://xapian.org/). See the section "External Indexing and
+# Searching" for details.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHENGINE_URL       =
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the unindexed
+# search data is written to a file for indexing by an external tool. With the
+# SEARCHDATA_FILE tag the name of this file can be specified.
+# The default file is: searchdata.xml.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+SEARCHDATA_FILE        = searchdata.xml
+
+# When SERVER_BASED_SEARCH and EXTERNAL_SEARCH are both enabled the
+# EXTERNAL_SEARCH_ID tag can be used as an identifier for the project. This is
+# useful in combination with EXTRA_SEARCH_MAPPINGS to search through multiple
+# projects and redirect the results back to the right project.
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTERNAL_SEARCH_ID     =
+
+# The EXTRA_SEARCH_MAPPINGS tag can be used to enable searching through doxygen
+# projects other than the one defined by this configuration file, but that are
+# all added to the same external search index. Each project needs to have a
+# unique id set via EXTERNAL_SEARCH_ID. The search mapping then maps the id of
+# to a relative location where the documentation can be found. The format is:
+# EXTRA_SEARCH_MAPPINGS = tagname1=loc1 tagname2=loc2 ...
+# This tag requires that the tag SEARCHENGINE is set to YES.
+
+EXTRA_SEARCH_MAPPINGS  =
+
+#---------------------------------------------------------------------------
+# Configuration options related to the LaTeX output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_LATEX tag is set to YES doxygen will generate LaTeX output.
+# The default value is: YES.
 
 GENERATE_LATEX         = YES
 
-# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `latex' will be used as the default path.
+# The LATEX_OUTPUT tag is used to specify where the LaTeX docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_OUTPUT           = latex
 
 # The LATEX_CMD_NAME tag can be used to specify the LaTeX command name to be
-# invoked. If left blank `latex' will be used as the default command name.
+# invoked.
+#
+# Note that when enabling USE_PDFLATEX this option is only used for generating
+# bitmaps for formulas in the HTML output, but not in the Makefile that is
+# written to the output directory.
+# The default file is: latex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_CMD_NAME         = latex
 
-# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to
-# generate index for LaTeX. If left blank `makeindex' will be used as the
-# default command name.
+# The MAKEINDEX_CMD_NAME tag can be used to specify the command name to generate
+# index for LaTeX.
+# The default file is: makeindex.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 MAKEINDEX_CMD_NAME     = makeindex
 
-# If the COMPACT_LATEX tag is set to YES Doxygen generates more compact
-# LaTeX documents. This may be useful for small projects and may help to
-# save some trees in general.
+# If the COMPACT_LATEX tag is set to YES doxygen generates more compact LaTeX
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 COMPACT_LATEX          = NO
 
-# The PAPER_TYPE tag can be used to set the paper type that is used
-# by the printer. Possible values are: a4, a4wide, letter, legal and
-# executive. If left blank a4wide will be used.
-
-PAPER_TYPE             = a4wide
-
-# The EXTRA_PACKAGES tag can be to specify one or more names of LaTeX
-# packages that should be included in the LaTeX output.
+# The PAPER_TYPE tag can be used to set the paper type that is used by the
+# printer.
+# Possible values are: a4 (210 x 297 mm), letter (8.5 x 11 inches), legal (8.5 x
+# 14 inches) and executive (7.25 x 10.5 inches).
+# The default value is: a4.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+PAPER_TYPE             = a4
+
+# The EXTRA_PACKAGES tag can be used to specify one or more LaTeX package names
+# that should be included in the LaTeX output. To get the times font for
+# instance you can specify
+# EXTRA_PACKAGES=times
+# If left blank no extra packages will be included.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 EXTRA_PACKAGES         =
 
-# The LATEX_HEADER tag can be used to specify a personal LaTeX header for
-# the generated latex document. The header should contain everything until
-# the first chapter. If it is left blank doxygen will generate a
-# standard header. Notice: only use this tag if you know what you are doing!
+# The LATEX_HEADER tag can be used to specify a personal LaTeX header for the
+# generated LaTeX document. The header should contain everything until the first
+# chapter. If it is left blank doxygen will generate a standard header. See
+# section "Doxygen usage" for information on how to let doxygen write the
+# default header to a separate file.
+#
+# Note: Only use a user-defined header if you know what you are doing! The
+# following commands have a special meaning inside the header: $title,
+# $datetime, $date, $doxygenversion, $projectname, $projectnumber,
+# $projectbrief, $projectlogo. Doxygen will replace $title with the empy string,
+# for the replacement values of the other commands the user is refered to
+# HTML_HEADER.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_HEADER           =
 
-# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated
-# is prepared for conversion to pdf (using ps2pdf). The pdf file will
-# contain links (just like the HTML output) instead of page references
-# This makes the output suitable for online browsing using a pdf viewer.
+# The LATEX_FOOTER tag can be used to specify a personal LaTeX footer for the
+# generated LaTeX document. The footer should contain everything after the last
+# chapter. If it is left blank doxygen will generate a standard footer. See
+# LATEX_HEADER for more information on how to generate a default footer and what
+# special commands can be used inside the footer.
+#
+# Note: Only use a user-defined footer if you know what you are doing!
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_FOOTER           =
+
+# The LATEX_EXTRA_FILES tag can be used to specify one or more extra images or
+# other source files which should be copied to the LATEX_OUTPUT output
+# directory. Note that the files will be copied as-is; there are no commands or
+# markers available.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_EXTRA_FILES      =
+
+# If the PDF_HYPERLINKS tag is set to YES, the LaTeX that is generated is
+# prepared for conversion to PDF (using ps2pdf or pdflatex). The PDF file will
+# contain links (just like the HTML output) instead of page references. This
+# makes the output suitable for online browsing using a PDF viewer.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 PDF_HYPERLINKS         = YES
 
-# If the USE_PDFLATEX tag is set to YES, pdflatex will be used instead of
-# plain latex in the generated Makefile. Set this option to YES to get a
+# If the USE_PDFLATEX tag is set to YES, doxygen will use pdflatex to generate
+# the PDF file directly from the LaTeX files. Set this option to YES to get a
 # higher quality PDF documentation.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 USE_PDFLATEX           = YES
 
-# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \\batchmode.
-# command to the generated LaTeX files. This will instruct LaTeX to keep
-# running if errors occur, instead of asking the user for help.
-# This option is also used when generating formulas in HTML.
+# If the LATEX_BATCHMODE tag is set to YES, doxygen will add the \batchmode
+# command to the generated LaTeX files. This will instruct LaTeX to keep running
+# if errors occur, instead of asking the user for help. This option is also used
+# when generating formulas in HTML.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_BATCHMODE        = NO
 
-# If LATEX_HIDE_INDICES is set to YES then doxygen will not
-# include the index chapters (such as File Index, Compound Index, etc.)
-# in the output.
+# If the LATEX_HIDE_INDICES tag is set to YES then doxygen will not include the
+# index chapters (such as File Index, Compound Index, etc.) in the output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_HIDE_INDICES     = NO
 
-# If LATEX_SOURCE_CODE is set to YES then doxygen will include source code with syntax highlighting in the LaTeX output. Note that which sources are shown also depends on other settings such as SOURCE_BROWSER.
+# If the LATEX_SOURCE_CODE tag is set to YES then doxygen will include source
+# code with syntax highlighting in the LaTeX output.
+#
+# Note that which sources are shown also depends on other settings such as
+# SOURCE_BROWSER.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
 
 LATEX_SOURCE_CODE      = NO
 
-#---------------------------------------------------------------------------
-# configuration options related to the RTF output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_RTF tag is set to YES Doxygen will generate RTF output
-# The RTF output is optimized for Word 97 and may not look very pretty with
-# other RTF readers or editors.
+# The LATEX_BIB_STYLE tag can be used to specify the style to use for the
+# bibliography, e.g. plainnat, or ieeetr. See
+# http://en.wikipedia.org/wiki/BibTeX and \cite for more info.
+# The default value is: plain.
+# This tag requires that the tag GENERATE_LATEX is set to YES.
+
+LATEX_BIB_STYLE        = plain
+
+#---------------------------------------------------------------------------
+# Configuration options related to the RTF output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_RTF tag is set to YES doxygen will generate RTF output. The
+# RTF output is optimized for Word 97 and may not look too pretty with other RTF
+# readers/editors.
+# The default value is: NO.
 
 GENERATE_RTF           = NO
 
-# The RTF_OUTPUT tag is used to specify where the RTF docs will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `rtf' will be used as the default path.
+# The RTF_OUTPUT tag is used to specify where the RTF docs will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: rtf.
+# This tag requires that the tag GENERATE_RTF is set to YES.
 
 RTF_OUTPUT             = rtf
 
-# If the COMPACT_RTF tag is set to YES Doxygen generates more compact
-# RTF documents. This may be useful for small projects and may help to
-# save some trees in general.
+# If the COMPACT_RTF tag is set to YES doxygen generates more compact RTF
+# documents. This may be useful for small projects and may help to save some
+# trees in general.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
 
 COMPACT_RTF            = NO
 
-# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated
-# will contain hyperlink fields. The RTF file will
-# contain links (just like the HTML output) instead of page references.
-# This makes the output suitable for online browsing using WORD or other
-# programs which support those fields.
-# Note: wordpad (write) and others do not support links.
+# If the RTF_HYPERLINKS tag is set to YES, the RTF that is generated will
+# contain hyperlink fields. The RTF file will contain links (just like the HTML
+# output) instead of page references. This makes the output suitable for online
+# browsing using Word or some other Word compatible readers that support those
+# fields.
+#
+# Note: WordPad (write) and others do not support links.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_RTF is set to YES.
 
 RTF_HYPERLINKS         = NO
 
-# Load stylesheet definitions from file. Syntax is similar to doxygen's
-# config file, i.e. a series of assignments. You only have to provide
-# replacements, missing definitions are set to their default value.
+# Load stylesheet definitions from file. Syntax is similar to doxygen's config
+# file, i.e. a series of assignments. You only have to provide replacements,
+# missing definitions are set to their default value.
+#
+# See also section "Doxygen usage" for information on how to generate the
+# default style sheet that doxygen normally uses.
+# This tag requires that the tag GENERATE_RTF is set to YES.
 
 RTF_STYLESHEET_FILE    =
 
-# Set optional variables used in the generation of an rtf document.
-# Syntax is similar to doxygen's config file.
+# Set optional variables used in the generation of an RTF document. Syntax is
+# similar to doxygen's config file. A template extensions file can be generated
+# using doxygen -e rtf extensionFile.
+# This tag requires that the tag GENERATE_RTF is set to YES.
 
 RTF_EXTENSIONS_FILE    =
 
 #---------------------------------------------------------------------------
-# configuration options related to the man page output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_MAN tag is set to YES (the default) Doxygen will
-# generate man pages
+# Configuration options related to the man page output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_MAN tag is set to YES doxygen will generate man pages for
+# classes and files.
+# The default value is: NO.
 
 GENERATE_MAN           = NO
 
-# The MAN_OUTPUT tag is used to specify where the man pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `man' will be used as the default path.
+# The MAN_OUTPUT tag is used to specify where the man pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it. A directory man3 will be created inside the directory specified by
+# MAN_OUTPUT.
+# The default directory is: man.
+# This tag requires that the tag GENERATE_MAN is set to YES.
 
 MAN_OUTPUT             = man
 
-# The MAN_EXTENSION tag determines the extension that is added to
-# the generated man pages (default is the subroutine's section .3)
+# The MAN_EXTENSION tag determines the extension that is added to the generated
+# man pages. In case the manual section does not start with a number, the number
+# 3 is prepended. The dot (.) at the beginning of the MAN_EXTENSION tag is
+# optional.
+# The default value is: .3.
+# This tag requires that the tag GENERATE_MAN is set to YES.
 
 MAN_EXTENSION          = .3
 
-# If the MAN_LINKS tag is set to YES and Doxygen generates man output,
-# then it will generate one additional man file for each entity
-# documented in the real man page(s). These additional files
-# only source the real man page, but without them the man command
-# would be unable to find the correct page. The default is NO.
+# The MAN_SUBDIR tag determines the name of the directory created within
+# MAN_OUTPUT in which the man pages are placed. If defaults to man followed by
+# MAN_EXTENSION with the initial . removed.
+# This tag requires that the tag GENERATE_MAN is set to YES.
+
+MAN_SUBDIR             =
+
+# If the MAN_LINKS tag is set to YES and doxygen generates man output, then it
+# will generate one additional man file for each entity documented in the real
+# man page(s). These additional files only source the real man page, but without
+# them the man command would be unable to find the correct page.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_MAN is set to YES.
 
 MAN_LINKS              = NO
 
 #---------------------------------------------------------------------------
-# configuration options related to the XML output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_XML tag is set to YES Doxygen will
-# generate an XML file that captures the structure of
-# the code including all documentation.
+# Configuration options related to the XML output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_XML tag is set to YES doxygen will generate an XML file that
+# captures the structure of the code including all documentation.
+# The default value is: NO.
 
 GENERATE_XML           = NO
 
-# The XML_OUTPUT tag is used to specify where the XML pages will be put.
-# If a relative path is entered the value of OUTPUT_DIRECTORY will be
-# put in front of it. If left blank `xml' will be used as the default path.
+# The XML_OUTPUT tag is used to specify where the XML pages will be put. If a
+# relative path is entered the value of OUTPUT_DIRECTORY will be put in front of
+# it.
+# The default directory is: xml.
+# This tag requires that the tag GENERATE_XML is set to YES.
 
 XML_OUTPUT             = xml
 
-# The XML_SCHEMA tag can be used to specify an XML schema,
-# which can be used by a validating XML parser to check the
-# syntax of the XML files.
-
-XML_SCHEMA             =
-
-# The XML_DTD tag can be used to specify an XML DTD,
-# which can be used by a validating XML parser to check the
-# syntax of the XML files.
-
-XML_DTD                =
-
-# If the XML_PROGRAMLISTING tag is set to YES Doxygen will
-# dump the program listings (including syntax highlighting
-# and cross-referencing information) to the XML output. Note that
-# enabling this will significantly increase the size of the XML output.
+# If the XML_PROGRAMLISTING tag is set to YES doxygen will dump the program
+# listings (including syntax highlighting and cross-referencing information) to
+# the XML output. Note that enabling this will significantly increase the size
+# of the XML output.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_XML is set to YES.
 
 XML_PROGRAMLISTING     = YES
 
 #---------------------------------------------------------------------------
-# configuration options for the AutoGen Definitions output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_AUTOGEN_DEF tag is set to YES Doxygen will
-# generate an AutoGen Definitions (see autogen.sf.net) file
-# that captures the structure of the code including all
-# documentation. Note that this feature is still experimental
-# and incomplete at the moment.
+# Configuration options related to the DOCBOOK output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_DOCBOOK tag is set to YES doxygen will generate Docbook files
+# that can be used to generate PDF.
+# The default value is: NO.
+
+GENERATE_DOCBOOK       = NO
+
+# The DOCBOOK_OUTPUT tag is used to specify where the Docbook pages will be put.
+# If a relative path is entered the value of OUTPUT_DIRECTORY will be put in
+# front of it.
+# The default directory is: docbook.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_OUTPUT         = docbook
+
+# If the DOCBOOK_PROGRAMLISTING tag is set to YES doxygen will include the
+# program listings (including syntax highlighting and cross-referencing
+# information) to the DOCBOOK output. Note that enabling this will significantly
+# increase the size of the DOCBOOK output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_DOCBOOK is set to YES.
+
+DOCBOOK_PROGRAMLISTING = NO
+
+#---------------------------------------------------------------------------
+# Configuration options for the AutoGen Definitions output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_AUTOGEN_DEF tag is set to YES doxygen will generate an AutoGen
+# Definitions (see http://autogen.sf.net) file that captures the structure of
+# the code including all documentation. Note that this feature is still
+# experimental and incomplete at the moment.
+# The default value is: NO.
 
 GENERATE_AUTOGEN_DEF   = NO
 
 #---------------------------------------------------------------------------
-# configuration options related to the Perl module output
-#---------------------------------------------------------------------------
-
-# If the GENERATE_PERLMOD tag is set to YES Doxygen will
-# generate a Perl module file that captures the structure of
-# the code including all documentation. Note that this
-# feature is still experimental and incomplete at the
-# moment.
+# Configuration options related to the Perl module output
+#---------------------------------------------------------------------------
+
+# If the GENERATE_PERLMOD tag is set to YES doxygen will generate a Perl module
+# file that captures the structure of the code including all documentation.
+#
+# Note that this feature is still experimental and incomplete at the moment.
+# The default value is: NO.
 
 GENERATE_PERLMOD       = NO
 
-# If the PERLMOD_LATEX tag is set to YES Doxygen will generate
-# the necessary Makefile rules, Perl scripts and LaTeX code to be able
-# to generate PDF and DVI output from the Perl module output.
+# If the PERLMOD_LATEX tag is set to YES doxygen will generate the necessary
+# Makefile rules, Perl scripts and LaTeX code to be able to generate PDF and DVI
+# output from the Perl module output.
+# The default value is: NO.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
 
 PERLMOD_LATEX          = NO
 
-# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be
-# nicely formatted so it can be parsed by a human reader.
-# This is useful
-# if you want to understand what is going on.
-# On the other hand, if this
-# tag is set to NO the size of the Perl module output will be much smaller
-# and Perl will parse it just the same.
+# If the PERLMOD_PRETTY tag is set to YES the Perl module output will be nicely
+# formatted so it can be parsed by a human reader. This is useful if you want to
+# understand what is going on. On the other hand, if this tag is set to NO the
+# size of the Perl module output will be much smaller and Perl will parse it
+# just the same.
+# The default value is: YES.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
 
 PERLMOD_PRETTY         = YES
 
-# The names of the make variables in the generated doxyrules.make file
-# are prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX.
-# This is useful so different doxyrules.make files included by the same
-# Makefile don't overwrite each other's variables.
+# The names of the make variables in the generated doxyrules.make file are
+# prefixed with the string contained in PERLMOD_MAKEVAR_PREFIX. This is useful
+# so different doxyrules.make files included by the same Makefile don't
+# overwrite each other's variables.
+# This tag requires that the tag GENERATE_PERLMOD is set to YES.
 
 PERLMOD_MAKEVAR_PREFIX =
@@ -1218,31 +1902,38 @@
 #---------------------------------------------------------------------------
 
-# If the ENABLE_PREPROCESSING tag is set to YES (the default) Doxygen will
-# evaluate all C-preprocessor directives found in the sources and include
-# files.
+# If the ENABLE_PREPROCESSING tag is set to YES doxygen will evaluate all
+# C-preprocessor directives found in the sources and include files.
+# The default value is: YES.
 
 ENABLE_PREPROCESSING   = YES
 
-# If the MACRO_EXPANSION tag is set to YES Doxygen will expand all macro
-# names in the source code. If set to NO (the default) only conditional
-# compilation will be performed. Macro expansion can be done in a controlled
-# way by setting EXPAND_ONLY_PREDEF to YES.
+# If the MACRO_EXPANSION tag is set to YES doxygen will expand all macro names
+# in the source code. If set to NO only conditional compilation will be
+# performed. Macro expansion can be done in a controlled way by setting
+# EXPAND_ONLY_PREDEF to YES.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
 
 MACRO_EXPANSION        = NO
 
-# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES
-# then the macro expansion is limited to the macros specified with the
-# PREDEFINED and EXPAND_AS_DEFINED tags.
+# If the EXPAND_ONLY_PREDEF and MACRO_EXPANSION tags are both set to YES then
+# the macro expansion is limited to the macros specified with the PREDEFINED and
+# EXPAND_AS_DEFINED tags.
+# The default value is: NO.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
 
 EXPAND_ONLY_PREDEF     = NO
 
-# If the SEARCH_INCLUDES tag is set to YES (the default) the includes files
-# in the INCLUDE_PATH (see below) will be search if a #include is found.
+# If the SEARCH_INCLUDES tag is set to YES the includes files in the
+# INCLUDE_PATH will be searched if a #include is found.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
 
 SEARCH_INCLUDES        = YES
 
 # The INCLUDE_PATH tag can be used to specify one or more directories that
-# contain include files that are not input files but should be processed by
-# the preprocessor.
+# contain include files that are not input files but should be processed by the
+# preprocessor.
+# This tag requires that the tag SEARCH_INCLUDES is set to YES.
 
 INCLUDE_PATH           =
@@ -1250,76 +1941,87 @@
 # You can use the INCLUDE_FILE_PATTERNS tag to specify one or more wildcard
 # patterns (like *.h and *.hpp) to filter out the header-files in the
-# directories. If left blank, the patterns specified with FILE_PATTERNS will
-# be used.
+# directories. If left blank, the patterns specified with FILE_PATTERNS will be
+# used.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
 
 INCLUDE_FILE_PATTERNS  =
 
-# The PREDEFINED tag can be used to specify one or more macro names that
-# are defined before the preprocessor is started (similar to the -D option of
-# gcc). The argument of the tag is a list of macros of the form: name
-# or name=definition (no spaces). If the definition and the = are
-# omitted =1 is assumed. To prevent a macro definition from being
-# undefined via #undef or recursively expanded use the := operator
-# instead of the = operator.
+# The PREDEFINED tag can be used to specify one or more macro names that are
+# defined before the preprocessor is started (similar to the -D option of e.g.
+# gcc). The argument of the tag is a list of macros of the form: name or
+# name=definition (no spaces). If the definition and the "=" are omitted, "=1"
+# is assumed. To prevent a macro definition from being undefined via #undef or
+# recursively expanded use the := operator instead of the = operator.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
 
 PREDEFINED             =
 
-# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then
-# this tag can be used to specify a list of macro names that should be expanded.
-# The macro definition that is found in the sources will be used.
-# Use the PREDEFINED tag if you want to use a different macro definition.
+# If the MACRO_EXPANSION and EXPAND_ONLY_PREDEF tags are set to YES then this
+# tag can be used to specify a list of macro names that should be expanded. The
+# macro definition that is found in the sources will be used. Use the PREDEFINED
+# tag if you want to use a different macro definition that overrules the
+# definition found in the source code.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
 
 EXPAND_AS_DEFINED      =
 
-# If the SKIP_FUNCTION_MACROS tag is set to YES (the default) then
-# doxygen's preprocessor will remove all function-like macros that are alone
-# on a line, have an all uppercase name, and do not end with a semicolon. Such
-# function macros are typically used for boiler-plate code, and will confuse
-# the parser if not removed.
+# If the SKIP_FUNCTION_MACROS tag is set to YES then doxygen's preprocessor will
+# remove all references to function-like macros that are alone on a line, have
+# an all uppercase name, and do not end with a semicolon. Such function macros
+# are typically used for boiler-plate code, and will confuse the parser if not
+# removed.
+# The default value is: YES.
+# This tag requires that the tag ENABLE_PREPROCESSING is set to YES.
 
 SKIP_FUNCTION_MACROS   = YES
 
 #---------------------------------------------------------------------------
-# Configuration::additions related to external references
-#---------------------------------------------------------------------------
-
-# The TAGFILES option can be used to specify one or more tagfiles.
-# Optionally an initial location of the external documentation
-# can be added for each tagfile. The format of a tag file without
-# this location is as follows:
-#
+# Configuration options related to external references
+#---------------------------------------------------------------------------
+
+# The TAGFILES tag can be used to specify one or more tag files. For each tag
+# file the location of the external documentation should be added. The format of
+# a tag file without this location is as follows:
 # TAGFILES = file1 file2 ...
 # Adding location for the tag files is done as follows:
-#
 # TAGFILES = file1=loc1 "file2 = loc2" ...
-# where "loc1" and "loc2" can be relative or absolute paths or
-# URLs. If a location is present for each tag, the installdox tool
-# does not have to be run to correct the links.
-# Note that each tag file must have a unique name
-# (where the name does NOT include the path)
-# If a tag file is not located in the directory in which doxygen
-# is run, you must also specify the path to the tagfile here.
+# where loc1 and loc2 can be relative or absolute paths or URLs. See the
+# section "Linking to external documentation" for more information about the use
+# of tag files.
+# Note: Each tag file must have a unique name (where the name does NOT include
+# the path). If a tag file is not located in the directory in which doxygen is
+# run, you must also specify the path to the tagfile here.
 
 TAGFILES               =
 
-# When a file name is specified after GENERATE_TAGFILE, doxygen will create
-# a tag file that is based on the input files it reads.
+# When a file name is specified after GENERATE_TAGFILE, doxygen will create a
+# tag file that is based on the input files it reads. See section "Linking to
+# external documentation" for more information about the usage of tag files.
 
 GENERATE_TAGFILE       =
 
-# If the ALLEXTERNALS tag is set to YES all external classes will be listed
-# in the class index. If set to NO only the inherited external classes
-# will be listed.
+# If the ALLEXTERNALS tag is set to YES all external class will be listed in the
+# class index. If set to NO only the inherited external classes will be listed.
+# The default value is: NO.
 
 ALLEXTERNALS           = NO
 
-# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed
-# in the modules index. If set to NO, only the current project's groups will
+# If the EXTERNAL_GROUPS tag is set to YES all external groups will be listed in
+# the modules index. If set to NO, only the current project's groups will be
+# listed.
+# The default value is: YES.
+
+EXTERNAL_GROUPS        = YES
+
+# If the EXTERNAL_PAGES tag is set to YES all external pages will be listed in
+# the related pages index. If set to NO, only the current project's pages will
 # be listed.
-
-EXTERNAL_GROUPS        = YES
+# The default value is: YES.
+
+EXTERNAL_PAGES         = YES
 
 # The PERL_PATH should be the absolute path and name of the perl script
-# interpreter (i.e. the result of `which perl').
+# interpreter (i.e. the result of 'which perl').
+# The default file (with absolute path) is: /usr/bin/perl.
 
 PERL_PATH              = /usr/bin/perl
@@ -1329,16 +2031,16 @@
 #---------------------------------------------------------------------------
 
-# If the CLASS_DIAGRAMS tag is set to YES (the default) Doxygen will
-# generate a inheritance diagram (in HTML, RTF and LaTeX) for classes with base
-# or super classes. Setting the tag to NO turns the diagrams off. Note that
-# this option is superseded by the HAVE_DOT option below. This is only a
-# fallback. It is recommended to install and use dot, since it yields more
+# If the CLASS_DIAGRAMS tag is set to YES doxygen will generate a class diagram
+# (in HTML and LaTeX) for classes with base or super classes. Setting the tag to
+# NO turns the diagrams off. Note that this option also works with HAVE_DOT
+# disabled, but it is recommended to install and use dot, since it yields more
 # powerful graphs.
+# The default value is: YES.
 
 CLASS_DIAGRAMS         = YES
 
 # You can define message sequence charts within doxygen comments using the \msc
-# command. Doxygen will then run the mscgen tool (see
-# http://www.mcternan.me.uk/mscgen/) to produce the chart and insert it in the
+# command. Doxygen will then run the mscgen tool (see:
+# http://www.mcternan.me.uk/mscgen/)) to produce the chart and insert it in the
 # documentation. The MSCGEN_PATH tag allows you to specify the directory where
 # the mscgen tool resides. If left empty the tool is assumed to be found in the
@@ -1347,56 +2049,81 @@
 MSCGEN_PATH            =
 
-# If set to YES, the inheritance and collaboration graphs will hide
-# inheritance and usage relations if the target is undocumented
-# or is not a class.
+# You can include diagrams made with dia in doxygen documentation. Doxygen will
+# then run dia to produce the diagram and insert it in the documentation. The
+# DIA_PATH tag allows you to specify the directory where the dia binary resides.
+# If left empty dia is assumed to be found in the default search path.
+
+DIA_PATH               =
+
+# If set to YES, the inheritance and collaboration graphs will hide inheritance
+# and usage relations if the target is undocumented or is not a class.
+# The default value is: YES.
 
 HIDE_UNDOC_RELATIONS   = YES
 
 # If you set the HAVE_DOT tag to YES then doxygen will assume the dot tool is
-# available from the path. This tool is part of Graphviz, a graph visualization
-# toolkit from AT&T and Lucent Bell Labs. The other options in this section
-# have no effect if this option is set to NO (the default)
-
-HAVE_DOT               = YES 
-
-# By default doxygen will write a font called FreeSans.ttf to the output
-# directory and reference it in all dot files that doxygen generates. This
-# font does not include all possible unicode characters however, so when you need
-# these (or just want a differently looking font) you can specify the font name
-# using DOT_FONTNAME. You need need to make sure dot is able to find the font,
-# which can be done by putting it in a standard location or by setting the
-# DOTFONTPATH environment variable or by setting DOT_FONTPATH to the directory
-# containing the font.
-
-DOT_FONTNAME           = FreeSans
-
-# The DOT_FONTSIZE tag can be used to set the size of the font of dot graphs.
-# The default size is 10pt.
+# available from the path. This tool is part of Graphviz (see:
+# http://www.graphviz.org/), a graph visualization toolkit from AT&T and Lucent
+# Bell Labs. The other options in this section have no effect if this option is
+# set to NO
+# The default value is: NO.
+
+HAVE_DOT               = YES
+
+# The DOT_NUM_THREADS specifies the number of dot invocations doxygen is allowed
+# to run in parallel. When set to 0 doxygen will base this on the number of
+# processors available in the system. You can set it explicitly to a value
+# larger than 0 to get control over the balance between CPU load and processing
+# speed.
+# Minimum value: 0, maximum value: 32, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_NUM_THREADS        = 0
+
+# When you want a differently looking font in the dot files that doxygen
+# generates you can specify the font name using DOT_FONTNAME. You need to make
+# sure dot is able to find the font, which can be done by putting it in a
+# standard location or by setting the DOTFONTPATH environment variable or by
+# setting DOT_FONTPATH to the directory containing the font.
+# The default value is: Helvetica.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+DOT_FONTNAME           = Helvetica
+
+# The DOT_FONTSIZE tag can be used to set the size (in points) of the font of
+# dot graphs.
+# Minimum value: 4, maximum value: 24, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_FONTSIZE           = 10
 
-# By default doxygen will tell dot to use the output directory to look for the
-# FreeSans.ttf font (which doxygen will put there itself). If you specify a
-# different font using DOT_FONTNAME you can set the path where dot
-# can find it using this tag.
+# By default doxygen will tell dot to use the default font as specified with
+# DOT_FONTNAME. If you specify a different font using DOT_FONTNAME you can set
+# the path where dot can find it using this tag.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_FONTPATH           =
 
-# If the CLASS_GRAPH and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for each documented class showing the direct and
-# indirect inheritance relations. Setting this tag to YES will force the
-# the CLASS_DIAGRAMS tag to NO.
+# If the CLASS_GRAPH tag is set to YES then doxygen will generate a graph for
+# each documented class showing the direct and indirect inheritance relations.
+# Setting this tag to YES will force the CLASS_DIAGRAMS tag to NO.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 CLASS_GRAPH            = YES
 
-# If the COLLABORATION_GRAPH and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for each documented class showing the direct and
-# indirect implementation dependencies (inheritance, containment, and
-# class references variables) of the class with other documented classes.
+# If the COLLABORATION_GRAPH tag is set to YES then doxygen will generate a
+# graph for each documented class showing the direct and indirect implementation
+# dependencies (inheritance, containment, and class references variables) of the
+# class with other documented classes.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 COLLABORATION_GRAPH    = YES
 
-# If the GROUP_GRAPHS and HAVE_DOT tags are set to YES then doxygen
-# will generate a graph for groups, showing the direct groups dependencies
+# If the GROUP_GRAPHS tag is set to YES then doxygen will generate a graph for
+# groups, showing the direct groups dependencies.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 GROUP_GRAPHS           = YES
@@ -1405,96 +2132,176 @@
 # collaboration diagrams in a style similar to the OMG's Unified Modeling
 # Language.
-
-UML_LOOK               = NO
-
-# If set to YES, the inheritance and collaboration graphs will show the
-# relations between templates and their instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LOOK               = YES
+
+# If the UML_LOOK tag is enabled, the fields and methods are shown inside the
+# class node. If there are many fields or methods and many nodes the graph may
+# become too big to be useful. The UML_LIMIT_NUM_FIELDS threshold limits the
+# number of items for each type to make the size more manageable. Set this to 0
+# for no limit. Note that the threshold may be exceeded by 50% before the limit
+# is enforced. So when you set the threshold to 10, up to 15 fields may appear,
+# but if the number exceeds 15, the total amount of fields shown is limited to
+# 10.
+# Minimum value: 0, maximum value: 100, default value: 10.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+UML_LIMIT_NUM_FIELDS   = 10
+
+# If the TEMPLATE_RELATIONS tag is set to YES then the inheritance and
+# collaboration graphs will show the relations between templates and their
+# instances.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 TEMPLATE_RELATIONS     = NO
 
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDE_GRAPH, and HAVE_DOT
-# tags are set to YES then doxygen will generate a graph for each documented
-# file showing the direct and indirect include dependencies of the file with
-# other documented files.
+# If the INCLUDE_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are set to
+# YES then doxygen will generate a graph for each documented file showing the
+# direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 INCLUDE_GRAPH          = YES
 
-# If the ENABLE_PREPROCESSING, SEARCH_INCLUDES, INCLUDED_BY_GRAPH, and
-# HAVE_DOT tags are set to YES then doxygen will generate a graph for each
-# documented header file showing the documented files that directly or
-# indirectly include this file.
+# If the INCLUDED_BY_GRAPH, ENABLE_PREPROCESSING and SEARCH_INCLUDES tags are
+# set to YES then doxygen will generate a graph for each documented file showing
+# the direct and indirect include dependencies of the file with other documented
+# files.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 INCLUDED_BY_GRAPH      = YES
 
-# If the CALL_GRAPH and HAVE_DOT options are set to YES then
-# doxygen will generate a call dependency graph for every global function
-# or class method. Note that enabling this option will significantly increase
-# the time of a run. So in most cases it will be better to enable call graphs
-# for selected functions only using the \callgraph command.
-
-CALL_GRAPH             = YES
-
-# If the CALLER_GRAPH and HAVE_DOT tags are set to YES then
-# doxygen will generate a caller dependency graph for every global function
-# or class method. Note that enabling this option will significantly increase
-# the time of a run. So in most cases it will be better to enable caller
-# graphs for selected functions only using the \callergraph command.
-
-CALLER_GRAPH           = YES 
-
-# If the GRAPHICAL_HIERARCHY and HAVE_DOT tags are set to YES then doxygen
-# will graphical hierarchy of all classes instead of a textual one.
+# If the CALL_GRAPH tag is set to YES then doxygen will generate a call
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable call graphs for selected
+# functions only using the \callgraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALL_GRAPH             = NO
+
+# If the CALLER_GRAPH tag is set to YES then doxygen will generate a caller
+# dependency graph for every global function or class method.
+#
+# Note that enabling this option will significantly increase the time of a run.
+# So in most cases it will be better to enable caller graphs for selected
+# functions only using the \callergraph command.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+CALLER_GRAPH           = NO
+
+# If the GRAPHICAL_HIERARCHY tag is set to YES then doxygen will graphical
+# hierarchy of all classes instead of a textual one.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 GRAPHICAL_HIERARCHY    = YES
 
-# If the DIRECTORY_GRAPH, SHOW_DIRECTORIES and HAVE_DOT tags are set to YES
-# then doxygen will show the dependencies a directory has on other directories
-# in a graphical way. The dependency relations are determined by the #include
-# relations between the files in the directories.
+# If the DIRECTORY_GRAPH tag is set to YES then doxygen will show the
+# dependencies a directory has on other directories in a graphical way. The
+# dependency relations are determined by the #include relations between the
+# files in the directories.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DIRECTORY_GRAPH        = YES
 
 # The DOT_IMAGE_FORMAT tag can be used to set the image format of the images
-# generated by dot. Possible values are png, jpg, or gif
-# If left blank png will be used.
+# generated by dot.
+# Note: If you choose svg you need to set HTML_FILE_EXTENSION to xhtml in order
+# to make the SVG files visible in IE 9+ (other browsers do not have this
+# requirement).
+# Possible values are: png, jpg, gif and svg.
+# The default value is: png.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_IMAGE_FORMAT       = png
 
-# The tag DOT_PATH can be used to specify the path where the dot tool can be
+# If DOT_IMAGE_FORMAT is set to svg, then this option can be set to YES to
+# enable generation of interactive SVG images that allow zooming and panning.
+#
+# Note that this requires a modern browser other than Internet Explorer. Tested
+# and working are Firefox, Chrome, Safari, and Opera.
+# Note: For IE 9+ you need to set HTML_FILE_EXTENSION to xhtml in order to make
+# the SVG files visible. Older versions of IE do not have SVG support.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+INTERACTIVE_SVG        = NO
+
+# The DOT_PATH tag can be used to specify the path where the dot tool can be
 # found. If left blank, it is assumed the dot tool can be found in the path.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_PATH               =
 
 # The DOTFILE_DIRS tag can be used to specify one or more directories that
-# contain dot files that are included in the documentation (see the
-# \dotfile command).
+# contain dot files that are included in the documentation (see the \dotfile
+# command).
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOTFILE_DIRS           =
 
-# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of
-# nodes that will be shown in the graph. If the number of nodes in a graph
-# becomes larger than this value, doxygen will truncate the graph, which is
-# visualized by representing a node as a red box. Note that doxygen if the
-# number of direct children of the root node in a graph is already larger than
-# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note
-# that the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# The MSCFILE_DIRS tag can be used to specify one or more directories that
+# contain msc files that are included in the documentation (see the \mscfile
+# command).
+
+MSCFILE_DIRS           =
+
+# The DIAFILE_DIRS tag can be used to specify one or more directories that
+# contain dia files that are included in the documentation (see the \diafile
+# command).
+
+DIAFILE_DIRS           =
+
+# When using plantuml, the PLANTUML_JAR_PATH tag should be used to specify the
+# path where java can find the plantuml.jar file. If left blank, it is assumed
+# PlantUML is not used or called during a preprocessing step. Doxygen will
+# generate a warning when it encounters a \startuml command in this case and
+# will not generate output for the diagram.
+# This tag requires that the tag HAVE_DOT is set to YES.
+
+PLANTUML_JAR_PATH      =
+
+# The DOT_GRAPH_MAX_NODES tag can be used to set the maximum number of nodes
+# that will be shown in the graph. If the number of nodes in a graph becomes
+# larger than this value, doxygen will truncate the graph, which is visualized
+# by representing a node as a red box. Note that doxygen if the number of direct
+# children of the root node in a graph is already larger than
+# DOT_GRAPH_MAX_NODES then the graph will not be shown at all. Also note that
+# the size of a graph can be further restricted by MAX_DOT_GRAPH_DEPTH.
+# Minimum value: 0, maximum value: 10000, default value: 50.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_GRAPH_MAX_NODES    = 50
 
-# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the
-# graphs generated by dot. A depth value of 3 means that only nodes reachable
-# from the root by following a path via at most 3 edges will be shown. Nodes
-# that lay further from the root node will be omitted. Note that setting this
-# option to 1 or 2 may greatly reduce the computation time needed for large
-# code bases. Also note that the size of a graph can be further restricted by
+# The MAX_DOT_GRAPH_DEPTH tag can be used to set the maximum depth of the graphs
+# generated by dot. A depth value of 3 means that only nodes reachable from the
+# root by following a path via at most 3 edges will be shown. Nodes that lay
+# further from the root node will be omitted. Note that setting this option to 1
+# or 2 may greatly reduce the computation time needed for large code bases. Also
+# note that the size of a graph can be further restricted by
 # DOT_GRAPH_MAX_NODES. Using a depth of 0 means no depth restriction.
+# Minimum value: 0, maximum value: 1000, default value: 0.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 MAX_DOT_GRAPH_DEPTH    = 0
 
 # Set the DOT_TRANSPARENT tag to YES to generate images with a transparent
-# background. This is disabled by default, because dot on Windows does not
-# seem to support this out of the box. Warning: Depending on the platform used,
-# enabling this option may lead to badly anti-aliased labels on the edges of
-# a graph (i.e. they become hard to read).
+# background. This is disabled by default, because dot on Windows does not seem
+# to support this out of the box.
+#
+# Warning: Depending on the platform used, enabling this option may lead to
+# badly anti-aliased labels on the edges of a graph (i.e. they become hard to
+# read).
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_TRANSPARENT        = NO
@@ -1502,18 +2309,23 @@
 # Set the DOT_MULTI_TARGETS tag to YES allow dot to generate multiple output
 # files in one run (i.e. multiple -o and -T options on the command line). This
-# makes dot run faster, but since only newer versions of dot (>1.8.10)
-# support this, this feature is disabled by default.
+# makes dot run faster, but since only newer versions of dot (>1.8.10) support
+# this, this feature is disabled by default.
+# The default value is: NO.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_MULTI_TARGETS      = NO
 
-# If the GENERATE_LEGEND tag is set to YES (the default) Doxygen will
-# generate a legend page explaining the meaning of the various boxes and
-# arrows in the dot generated graphs.
+# If the GENERATE_LEGEND tag is set to YES doxygen will generate a legend page
+# explaining the meaning of the various boxes and arrows in the dot generated
+# graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 GENERATE_LEGEND        = YES
 
-# If the DOT_CLEANUP tag is set to YES (the default) Doxygen will
-# remove the intermediate dot files that are used to generate
-# the various graphs.
+# If the DOT_CLEANUP tag is set to YES doxygen will remove the intermediate dot
+# files that are used to generate the various graphs.
+# The default value is: YES.
+# This tag requires that the tag HAVE_DOT is set to YES.
 
 DOT_CLEANUP            = YES
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/attribute.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/attribute.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/attribute.f90	(revision 5075)
@@ -8,23 +8,60 @@
 !> @brief 
 !> This module manage attribute of variable or file.
-!
+!>
 !> @details
 !>    define type TATT:<br/>
-!>    TYPE(TATT) :: tl_att<br/>
+!> @code
+!>    TYPE(TATT) :: tl_att
+!> @endcode
 !>
 !>    the attribute value inside attribute structure will be
-!>    character or real(8) 1D table.<br/>
-!>    However the attribute value could be initialised with:<br/>
+!>    character or real(8) 1D array.<br/>
+!>    However the attribute value could be initialized with:<br/>
 !>    - character
 !>    - scalar (real(4), real(8), integer(4) or integer(8))
-!>    - table 1D (real(4), real(8), integer(4) or integer(8))
+!>    - array 1D (real(4), real(8), integer(4) or integer(8))
 !>
-!>    to initialise an attribute structure :<br/>
-!>    tl_att=att_init('attname',value)<br/>
-!>    tl_att=att_init('attname',tab_value)<br/>
+!>    to initialize an attribute structure :<br/>
+!> @code
+!>    tl_att=att_init('attname',value)
+!> @endcode
+!>    - value is a character, scalar value or table of value
 !>
-!>    to print attribute information of one attribute structure:<br/>
+!>    to print attribute information of one or array of attribute structure:<br/>
+!> @code
 !>    CALL att_print(td_att) 
+!> @endcode
 !>
+!>    to clean attribute structure:<br/>
+!> @code
+!>    CALL att_clean(td_att) 
+!> @endcode
+!>
+!>    to copy attribute structure in another one (using different memory cell):<br/>
+!> @code
+!>    tl_att2=att_copy(tl_att1) 
+!> @endcode
+!>    @note as we use pointer for the value array of the attribute structure,
+!>    the use of the assignment operator (=) to copy attribute structure 
+!>    create a pointer on the same array. 
+!>    This is not the case with this copy function.
+!>
+!>    to get attribute index, in an array of attribute structure:<br/>
+!> @code
+!>   il_index=att_get_index( td_att, cd_name )
+!> @endcode
+!>    - td_att array of attribute structure
+!>    - cd_name attribute name
+!> 
+!>    to get attribute id, read from a file:<br/>
+!>@code
+!>  il_id=att_get_id( td_att, cd_name )
+!>@endcode
+!>    - td_att array of attribute structure
+!>    - cd_name attribute name
+!>
+!>    to get attribute name
+!>    - tl_att\%c_name
+!> 
 !>    to get character length or the number of value store in attribute
 !>    - tl_att\%i_len
@@ -38,15 +75,13 @@
 !>    - tl_att\%i_type
 !>
-!>    to get attribute id (affected when attributes will be added to 
-!>    variable or file):<br/>
+!>    to get attribute id (read from file):<br/>
 !>    - tl_att\%i_id
 !>
-!> @author
-!> J.Paul
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
+!> @date November, 2014 - Fix memory leaks bug
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
 !----------------------------------------------------------------------
 MODULE att
@@ -54,42 +89,44 @@
    USE global                          ! global variable
    USE kind                            ! F90 kind parameter
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE fct                             ! basic useful function
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
-   PUBLIC :: TATT       ! attribute structure
+   PUBLIC :: TATT       !< attribute structure
 
    ! function and subroutine
-   PUBLIC :: ASSIGNMENT(=)  ! copy attribute structure
-   PUBLIC :: att_init     ! initialize attribute structure
-   PUBLIC :: att_print    ! print attribute structure
-   PUBLIC :: att_get_id   ! get attribute id in table of attribute structure
-   PUBLIC :: att_clean    ! clean attribute strcuture
-
-   PRIVATE :: att__init_c     ! initialise an attribute structure with character value
-   PRIVATE :: att__init_dp    ! initialise an attribute structure with table of real(8) value
-   PRIVATE :: att__init_dp_0d ! initialise an attribute structure with real(8) value
-   PRIVATE :: att__init_sp    ! initialise an attribute structure with table of real(4) value
-   PRIVATE :: att__init_sp_0d ! initialise an attribute structure with real(4) value
-   PRIVATE :: att__init_i1    ! initialise an attribute structure with table of integer(1) value
-   PRIVATE :: att__init_i1_0d ! initialise an attribute structure with integer(1) value
-   PRIVATE :: att__init_i2    ! initialise an attribute structure with table of integer(2) value
-   PRIVATE :: att__init_i2_0d ! initialise an attribute structure with integer(2) value
-   PRIVATE :: att__init_i4    ! initialise an attribute structure with table of integer(4) value
-   PRIVATE :: att__init_i4_0d ! initialise an attribute structure with integer(4) value
-   PRIVATE :: att__init_i8    ! initialise an attribute structure with table of integer(8) value
-   PRIVATE :: att__init_i8_0d ! initialise an attribute structure with integer(8) value
-   PRIVATE :: att__copy_unit   ! copy attribute structure
-   PRIVATE :: att__copy_tab    ! copy attribute structure
-
-   !> @struct TATT
-   TYPE TATT
-      !CHARACTER(LEN=lc) :: c_name = 'unknown'  !< attribute name
-      CHARACTER(LEN=lc) :: c_name = ''  !< attribute name
-      INTEGER(i4)       :: i_id = 0          !< attribute id
-      INTEGER(i4)       :: i_type  = 0       !< attribute type
+   PUBLIC :: att_init       !< initialize attribute structure
+   PUBLIC :: att_print      !< print attribute structure
+   PUBLIC :: att_clean      !< clean attribute strcuture
+   PUBLIC :: att_copy       !< copy attribute structure
+   PUBLIC :: att_get_index  !< get attribute index, in an array of attribute structure
+   PUBLIC :: att_get_id     !< get attribute id, read from file
+
+   PRIVATE :: att__clean_unit ! clean attribute strcuture
+   PRIVATE :: att__clean_arr  ! clean array of attribute strcuture
+   PRIVATE :: att__print_unit ! print information on one attribute
+   PRIVATE :: att__print_arr  ! print information on a array of attribute
+   PRIVATE :: att__init_c     ! initialize an attribute structure with character value
+   PRIVATE :: att__init_dp    ! initialize an attribute structure with array of real(8) value
+   PRIVATE :: att__init_dp_0d ! initialize an attribute structure with real(8) value
+   PRIVATE :: att__init_sp    ! initialize an attribute structure with array of real(4) value
+   PRIVATE :: att__init_sp_0d ! initialize an attribute structure with real(4) value
+   PRIVATE :: att__init_i1    ! initialize an attribute structure with array of integer(1) value
+   PRIVATE :: att__init_i1_0d ! initialize an attribute structure with integer(1) value
+   PRIVATE :: att__init_i2    ! initialize an attribute structure with array of integer(2) value
+   PRIVATE :: att__init_i2_0d ! initialize an attribute structure with integer(2) value
+   PRIVATE :: att__init_i4    ! initialize an attribute structure with array of integer(4) value
+   PRIVATE :: att__init_i4_0d ! initialize an attribute structure with integer(4) value
+   PRIVATE :: att__init_i8    ! initialize an attribute structure with array of integer(8) value
+   PRIVATE :: att__init_i8_0d ! initialize an attribute structure with integer(8) value
+   PRIVATE :: att__copy_unit  ! copy attribute structure
+   PRIVATE :: att__copy_arr   ! copy array of attribute structure
+
+   TYPE TATT !< attribute structure
+      CHARACTER(LEN=lc) :: c_name = ''       !< attribute name
+      INTEGER(i4)       :: i_id   = 0        !< attribute id
+      INTEGER(i4)       :: i_type = 0        !< attribute type
       INTEGER(i4)       :: i_len  = 0        !< number of value store in attribute
       CHARACTER(LEN=lc) :: c_value = "none"  !< attribute value if type CHAR
@@ -113,34 +150,47 @@
    END INTERFACE att_init
 
-   INTERFACE ASSIGNMENT(=)
-      MODULE PROCEDURE att__copy_unit   ! copy attribute structure
-      MODULE PROCEDURE att__copy_tab   ! copy attribute structure
+   INTERFACE att_print
+      MODULE PROCEDURE att__print_unit ! print information on one attribute
+      MODULE PROCEDURE att__print_arr  ! print information on a array of attribute
+   END INTERFACE att_print
+
+   INTERFACE att_clean
+      MODULE PROCEDURE att__clean_unit  
+      MODULE PROCEDURE att__clean_arr   
    END INTERFACE
 
+   INTERFACE att_copy
+      MODULE PROCEDURE att__copy_unit  ! copy attribute structure
+      MODULE PROCEDURE att__copy_arr   ! copy array of attribute structure
+   END INTERFACE
+
 CONTAINS
    !-------------------------------------------------------------------
    !> @brief
-   !> This function copy attribute structure in another attribute
-   !> structure
+   !> This subroutine copy a array of attribute structure in another one
    !> @details 
-   !> attribute value are copied in a temporary table, so input and output
-   !> attribute structure value do not point on the same "memory cell", and so
-   !> on are independant. 
-   !>
+   !> see att__copy_unit
+   !>
+   !> @warning do not use on the output of a function who create or read an
+   !> attribute (ex: tl_att=att_copy(att_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[out] td_att1  : attribute structure
-   !> @param[in] td_att2  : attribute structure
-   !-------------------------------------------------------------------
-   ! @code
-   SUBROUTINE att__copy_tab( td_att1, td_att2 )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TATT), DIMENSION(:)               , INTENT(IN) :: td_att2
-      TYPE(TATT), DIMENSION(SIZE(td_att2(:))),INTENT(OUT) :: td_att1
+   !> @date November, 2013 - Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak) 
+   !
+   !> @param[in] td_att   array of attribute structure
+   !> @return copy of input array of attribute structure
+   !-------------------------------------------------------------------
+   FUNCTION att__copy_arr( td_att )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TATT), DIMENSION(:), INTENT(IN) :: td_att
+      ! function
+      TYPE(TATT), DIMENSION(SIZE(td_att(:))) :: att__copy_arr
 
       ! local variable
@@ -149,34 +199,37 @@
       !----------------------------------------------------------------
 
-      DO ji=1,SIZE(td_att2(:))
-         td_att1(ji)=td_att2(ji)
+      DO ji=1,SIZE(td_att(:))
+         att__copy_arr(ji)=att_copy(td_att(ji))
       ENDDO
 
-   END SUBROUTINE att__copy_tab
-   ! @endcode
+   END FUNCTION att__copy_arr
    !-------------------------------------------------------------------
    !> @brief
-   !> This function copy attribute structure in another attribute
-   !> structure
+   !> This subroutine copy an attribute structure in another one.
    !> @details 
-   !> attribute value are copied in a temporary table, so input and output
+   !> attribute value are copied in a temporary array, so input and output
    !> attribute structure value do not point on the same "memory cell", and so
    !> on are independant. 
    !>
+   !> @warning do not use on the output of a function who create or read an
+   !> attribute (ex: tl_att=att_copy(att_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[out] td_att1  : attribute structure
-   !> @param[in] td_att2  : attribute structure
-   !-------------------------------------------------------------------
-   ! @code
-   SUBROUTINE att__copy_unit( td_att1, td_att2 )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TATT), INTENT(OUT) :: td_att1
-      TYPE(TATT), INTENT(IN)  :: td_att2
+   !> @date November, 2013 - Initial Version
+   !> @date November, 2014
+   !> - use function instead of overload assignment operator (to avoid memory leak) 
+   !>
+   !> @param[in] td_att   attribute structure
+   !> @return copy of input attribute structure
+   !-------------------------------------------------------------------
+   FUNCTION att__copy_unit( td_att )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TATT), INTENT(IN)  :: td_att
+      ! function
+      TYPE(TATT) :: att__copy_unit
 
       ! local variable
@@ -184,40 +237,38 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace("COPY: attribute "//TRIM(td_att2%c_name) )
-
       ! copy attribute variable
-      td_att1%c_name  = TRIM(td_att2%c_name)
-      td_att1%i_id    = td_att2%i_id
-      td_att1%i_type  = td_att2%i_type
-      td_att1%i_len   = td_att2%i_len
-      td_att1%c_value = TRIM(td_att2%c_value)
+      att__copy_unit%c_name  = TRIM(td_att%c_name)
+      att__copy_unit%i_id    = td_att%i_id
+      att__copy_unit%i_type  = td_att%i_type
+      att__copy_unit%i_len   = td_att%i_len
+      att__copy_unit%c_value = TRIM(td_att%c_value)
 
       ! copy attribute pointer in an independant variable
-      IF( ASSOCIATED(td_att1%d_value) ) DEALLOCATE(td_att1%d_value)
-      IF( ASSOCIATED(td_att2%d_value) )THEN
-         ALLOCATE( dl_value(td_att2%i_len) )
-         dl_value(:) = td_att2%d_value(:)
-
-         ALLOCATE( td_att1%d_value(td_att1%i_len) )
-         td_att1%d_value(:) = dl_value(:)
+      IF( ASSOCIATED(att__copy_unit%d_value) ) DEALLOCATE(att__copy_unit%d_value)
+      IF( ASSOCIATED(td_att%d_value) )THEN
+         ALLOCATE( dl_value(td_att%i_len) )
+         dl_value(:) = td_att%d_value(:)
+
+         ALLOCATE( att__copy_unit%d_value(att__copy_unit%i_len) )
+         att__copy_unit%d_value(:) = dl_value(:)
 
          DEALLOCATE( dl_value )
       ENDIF
 
-   END SUBROUTINE att__copy_unit
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function get attribute id, in a table of attribute structure,
-   !> given attribute name
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_att  : attribute structure
-   !> @param[in] cd_name : attribute name
-   !> @return attribute id
-   !-------------------------------------------------------------------
-   ! @code
-   INTEGER(i4) FUNCTION att_get_id( td_att, cd_name )
+   END FUNCTION att__copy_unit
+   !-------------------------------------------------------------------
+   !> @brief This function return attribute index, in a array of attribute structure,
+   !> given attribute name.<br/>
+   !> @details
+   !> if attribute name do not exist, return 0.
+   !>
+   !> @author J.Paul
+   !> @date Septempber, 2014 - Initial Version
+   !
+   !> @param[in] td_att    array of attribute structure
+   !> @param[in] cd_name   attribute name
+   !> @return attribute index
+   !-------------------------------------------------------------------
+   INTEGER(i4) FUNCTION att_get_index( td_att, cd_name )
       IMPLICIT NONE
       ! Argument
@@ -231,28 +282,62 @@
       INTEGER(i4) :: ji
       !----------------------------------------------------------------
-      att_get_id=0
+      att_get_index=0
 
       il_size=SIZE(td_att(:))
       DO ji=1,il_size
          IF( TRIM(td_att(ji)%c_name) == TRIM(cd_name) )THEN
-            att_get_id=ji
+            att_get_index=ji
             EXIT
          ENDIF
       ENDDO
 
+   END FUNCTION att_get_index
+   !-------------------------------------------------------------------
+   !> @brief This function return attribute id, read from a file.<br/>
+   !> @details
+   !> if attribute name do not exist, return 0.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !> @date September, 2014 - bug fix with use of id read from attribute structure
+   !
+   !> @param[in] td_att    array of attribute structure
+   !> @param[in] cd_name   attribute name
+   !> @return attribute id
+   !-------------------------------------------------------------------
+   INTEGER(i4) FUNCTION att_get_id( td_att, cd_name )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TATT),       DIMENSION(:), INTENT(IN) :: td_att
+      CHARACTER(LEN=*),               INTENT(IN) :: cd_name
+
+      ! local variable
+      INTEGER(i4) :: il_size
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      att_get_id=0
+
+      il_size=SIZE(td_att(:))
+      DO ji=1,il_size
+         IF( TRIM(td_att(ji)%c_name) == TRIM(cd_name) )THEN
+            att_get_id=td_att(ji)%i_id
+            EXIT
+         ENDIF
+      ENDDO
+
    END FUNCTION att_get_id
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with character
-   !> value 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] cd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with character
+   !> value. 
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] cd_value  attribute value
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TATT) FUNCTION att__init_c( cd_name, cd_value )
       IMPLICIT NONE
@@ -265,5 +350,5 @@
       CALL att_clean(att__init_c)
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attribute value "//TRIM(ADJUSTL(cd_value)) )
@@ -276,18 +361,19 @@
 
    END FUNCTION att__init_c
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with table 
-   !> of real(8) value
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] dd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with array 
+   !> of real(8) value.
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @dtae November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] dd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_dp( cd_name, dd_value )
+   TYPE(TATT) FUNCTION att__init_dp( cd_name, dd_value, id_type )
       IMPLICIT NONE
 
@@ -295,4 +381,5 @@
       CHARACTER(LEN=*),               INTENT(IN) :: cd_name
       REAL(dp),         DIMENSION(:), INTENT(IN) :: dd_value
+      INTEGER(i4)                   , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -307,5 +394,5 @@
       CALL att_clean(att__init_dp)
 
-      ! table size
+      ! array size
       il_len=size(dd_value(:))
 
@@ -316,5 +403,5 @@
       cl_value=TRIM(cl_value)//TRIM(fct_str(dd_value(il_len)))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attribute value "//TRIM(ADJUSTL(cl_value)) )
@@ -322,5 +409,9 @@
       att__init_dp%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_dp%i_type=NF90_DOUBLE
+      IF( PRESENT(id_type) )THEN
+         att__init_dp%i_type=id_type
+      ELSE
+         att__init_dp%i_type=NF90_DOUBLE
+      ENDIF
 
       IF( ASSOCIATED(att__init_dp%d_value) )THEN
@@ -333,22 +424,24 @@
 
    END FUNCTION att__init_dp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with 
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with 
    !> real(8) value 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] dd_value: attribute value
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] dd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_dp_0d( cd_name, dd_value )
+   TYPE(TATT) FUNCTION att__init_dp_0d( cd_name, dd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*), INTENT(IN) :: cd_name
       REAL(dp),         INTENT(IN) :: dd_value
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -361,5 +454,5 @@
       cl_value="(/"//TRIM(fct_str(dd_value))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attribute value "//TRIM(ADJUSTL(cl_value)) )
@@ -367,5 +460,9 @@
       att__init_dp_0d%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_dp_0d%i_type=NF90_DOUBLE
+      IF( PRESENT(id_type) )THEN
+         att__init_dp_0d%i_type=id_type
+      ELSE
+         att__init_dp_0d%i_type=NF90_DOUBLE
+      ENDIF
 
       IF( ASSOCIATED(att__init_dp_0d%d_value) )THEN
@@ -378,22 +475,24 @@
 
    END FUNCTION att__init_dp_0d
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with table 
-   !> of real(4) value
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] rd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with array 
+   !> of real(4) value.
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] rd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_sp( cd_name, rd_value )
+   TYPE(TATT) FUNCTION att__init_sp( cd_name, rd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*),               INTENT(IN) :: cd_name
       REAL(sp),         DIMENSION(:), INTENT(IN) :: rd_value
+      INTEGER(i4)                   , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -408,5 +507,5 @@
       CALL att_clean(att__init_sp)
       
-      ! table size
+      ! array size
       il_len=size(rd_value(:))
 
@@ -417,5 +516,5 @@
       cl_value=TRIM(cl_value)//TRIM(fct_str(rd_value(il_len)))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attribute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -423,5 +522,9 @@
       att__init_sp%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_sp%i_type=NF90_FLOAT
+      IF( PRESENT(id_type) )THEN
+         att__init_sp%i_type=id_type
+      ELSE
+         att__init_sp%i_type=NF90_FLOAT
+      ENDIF
 
       IF( ASSOCIATED(att__init_sp%d_value) )THEN
@@ -434,22 +537,24 @@
 
    END FUNCTION att__init_sp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with 
-   !> real(4) value 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] rd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with 
+   !> real(4) value. 
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] rd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_sp_0d( cd_name, rd_value )
+   TYPE(TATT) FUNCTION att__init_sp_0d( cd_name, rd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*), INTENT(IN) :: cd_name
       REAL(sp),         INTENT(IN) :: rd_value
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -462,5 +567,5 @@
       cl_value="(/"//TRIM(fct_str(rd_value))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attribute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -468,5 +573,9 @@
       att__init_sp_0d%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_sp_0d%i_type=NF90_FLOAT
+      IF( PRESENT(id_type) )THEN
+         att__init_sp_0d%i_type=id_type
+      ELSE
+         att__init_sp_0d%i_type=NF90_FLOAT
+      ENDIF
 
       IF( ASSOCIATED(att__init_sp_0d%d_value) )THEN
@@ -479,22 +588,24 @@
 
    END FUNCTION att__init_sp_0d
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with table 
-   !> of integer(1) value
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] bd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with array 
+   !> of integer(1) value.
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] bd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_i1( cd_name, bd_value )
+   TYPE(TATT) FUNCTION att__init_i1( cd_name, bd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*),               INTENT(IN) :: cd_name
       INTEGER(i1),      DIMENSION(:), INTENT(IN) :: bd_value
+      INTEGER(i4)                   , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -509,5 +620,5 @@
       CALL att_clean(att__init_i1)
       
-      ! table size
+      ! array size
       il_len=size(bd_value(:))
 
@@ -518,5 +629,5 @@
       cl_value=TRIM(cl_value)//TRIM(fct_str(bd_value(il_len)))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attribute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -524,5 +635,9 @@
       att__init_i1%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_i1%i_type=NF90_BYTE
+      IF( PRESENT(id_type) )THEN
+         att__init_i1%i_type=id_type
+      ELSE
+         att__init_i1%i_type=NF90_BYTE
+      ENDIF
 
       IF( ASSOCIATED(att__init_i1%d_value) )THEN
@@ -535,22 +650,24 @@
 
    END FUNCTION att__init_i1
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with 
-   !> integer(1) value 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] bd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with 
+   !> integer(1) value. 
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] bd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_i1_0d( cd_name, bd_value )
+   TYPE(TATT) FUNCTION att__init_i1_0d( cd_name, bd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*), INTENT(IN) :: cd_name
       INTEGER(i1),      INTENT(IN) :: bd_value
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_type
 
       !local value
@@ -563,5 +680,5 @@
       cl_value="(/"//TRIM(fct_str(bd_value))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attibute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -569,5 +686,9 @@
       att__init_i1_0d%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_i1_0d%i_type=NF90_BYTE
+      IF( PRESENT(id_type) )THEN
+         att__init_i1_0d%i_type=id_type
+      ELSE
+         att__init_i1_0d%i_type=NF90_BYTE
+      ENDIF      
 
       IF( ASSOCIATED(att__init_i1_0d%d_value) )THEN
@@ -580,22 +701,24 @@
 
    END FUNCTION att__init_i1_0d
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with table 
-   !> of integer(2) value
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] sd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with array 
+   !> of integer(2) value.
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] sd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_i2( cd_name, sd_value )
+   TYPE(TATT) FUNCTION att__init_i2( cd_name, sd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*),               INTENT(IN) :: cd_name
       INTEGER(i2),      DIMENSION(:), INTENT(IN) :: sd_value
+      INTEGER(i4)                   , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -610,5 +733,5 @@
       CALL att_clean(att__init_i2)
       
-      ! table size
+      ! array size
       il_len=size(sd_value(:))
 
@@ -619,5 +742,5 @@
       cl_value=TRIM(cl_value)//TRIM(fct_str(sd_value(il_len)))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attribute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -625,5 +748,9 @@
       att__init_i2%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_i2%i_type=NF90_SHORT
+      IF( PRESENT(id_type) )THEN
+         att__init_i2%i_type=id_type
+      ELSE
+         att__init_i2%i_type=NF90_SHORT
+      ENDIF
 
       IF( ASSOCIATED(att__init_i2%d_value) )THEN
@@ -636,22 +763,24 @@
 
    END FUNCTION att__init_i2
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with 
-   !> integer(2) value 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] sd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with 
+   !> integer(2) value. 
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] sd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_i2_0d( cd_name, sd_value )
+   TYPE(TATT) FUNCTION att__init_i2_0d( cd_name, sd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*), INTENT(IN) :: cd_name
       INTEGER(i2),      INTENT(IN) :: sd_value
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_type
 
       !local value
@@ -664,5 +793,5 @@
       cl_value="(/"//TRIM(fct_str(sd_value))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attibute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -670,5 +799,9 @@
       att__init_i2_0d%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_i2_0d%i_type=NF90_SHORT
+      IF( PRESENT(id_type) )THEN
+         att__init_i2_0d%i_type=id_type
+      ELSE
+         att__init_i2_0d%i_type=NF90_SHORT
+      ENDIF
 
       IF( ASSOCIATED(att__init_i2_0d%d_value) )THEN
@@ -681,22 +814,24 @@
 
    END FUNCTION att__init_i2_0d
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with table 
-   !> of integer(4) value
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] id_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with array 
+   !> of integer(4) value.
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] id_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_i4( cd_name, id_value )
+   TYPE(TATT) FUNCTION att__init_i4( cd_name, id_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*),               INTENT(IN) :: cd_name
       INTEGER(i4),      DIMENSION(:), INTENT(IN) :: id_value
+      INTEGER(i4)                   , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -711,5 +846,5 @@
       CALL att_clean(att__init_i4)
       
-      ! table size
+      ! array size
       il_len=size(id_value(:))
 
@@ -720,5 +855,5 @@
       cl_value=TRIM(cl_value)//TRIM(fct_str(id_value(il_len)))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attribute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -726,5 +861,9 @@
       att__init_i4%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_i4%i_type=NF90_INT
+      IF( PRESENT(id_type) )THEN
+         att__init_i4%i_type=id_type
+      ELSE
+         att__init_i4%i_type=NF90_INT
+      ENDIF
 
       IF( ASSOCIATED(att__init_i4%d_value) )THEN
@@ -737,22 +876,24 @@
 
    END FUNCTION att__init_i4
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with 
-   !> integer(4) value 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] id_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with 
+   !> integer(4) value. 
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !>
+   !> @param[in] cd_name   attribute name
+   !> @param[in] id_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_i4_0d( cd_name, id_value )
+   TYPE(TATT) FUNCTION att__init_i4_0d( cd_name, id_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*), INTENT(IN) :: cd_name
       INTEGER(i4),      INTENT(IN) :: id_value
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_type
 
       !local value
@@ -765,5 +906,5 @@
       cl_value="(/"//TRIM(fct_str(id_value))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attibute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -771,5 +912,9 @@
       att__init_i4_0d%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_i4_0d%i_type=NF90_INT
+      IF( PRESENT(id_type) )THEN
+         att__init_i4_0d%i_type=id_type
+      ELSE
+         att__init_i4_0d%i_type=NF90_INT
+      ENDIF
 
       IF( ASSOCIATED(att__init_i4_0d%d_value) )THEN
@@ -782,22 +927,24 @@
 
    END FUNCTION att__init_i4_0d
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with table 
-   !> of integer(8) value
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] kd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with array 
+   !> of integer(8) value.
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] kd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_i8( cd_name, kd_value )
+   TYPE(TATT) FUNCTION att__init_i8( cd_name, kd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*),               INTENT(IN) :: cd_name
       INTEGER(i8),      DIMENSION(:), INTENT(IN) :: kd_value
+      INTEGER(i4)                   , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -812,5 +959,5 @@
       CALL att_clean(att__init_i8)
       
-      ! table size
+      ! array size
       il_len=size(kd_value(:))
 
@@ -821,5 +968,5 @@
       cl_value=TRIM(cl_value)//TRIM(fct_str(kd_value(il_len)))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attibute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -827,5 +974,9 @@
       att__init_i8%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_i8%i_type=NF90_INT
+      IF( PRESENT(id_type) )THEN
+         att__init_i8%i_type=id_type
+      ELSE
+         att__init_i8%i_type=NF90_INT
+      ENDIF
 
       IF( ASSOCIATED(att__init_i8%d_value) )THEN
@@ -838,22 +989,24 @@
 
    END FUNCTION att__init_i8
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise an attribute structure with 
-   !> integer(8) value 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : attribute name
-   !> @param[in] kd_value: attribute value
+   !-------------------------------------------------------------------
+   !> @brief This function initialize an attribute structure with 
+   !> integer(8) value. 
+   !> @details
+   !> Optionaly you could specify the type of the variable to be saved.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   attribute name
+   !> @param[in] kd_value  attribute value
+   !> @param[in] id_type   type of the variable to be saved
    !> @return attribute structure
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION att__init_i8_0d( cd_name, kd_value )
+   TYPE(TATT) FUNCTION att__init_i8_0d( cd_name, kd_value, id_type )
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*), INTENT(IN) :: cd_name
       INTEGER(i8),      INTENT(IN) :: kd_value
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_type
 
       ! local value
@@ -866,5 +1019,5 @@
       cl_value="(/"//TRIM(fct_str(kd_value))//"/)"
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " ATT INIT: attribute name: "//TRIM(ADJUSTL(cd_name))//&
       &  " attibute value "//TRIM(ADJUSTL(cl_value)) )      
@@ -872,5 +1025,9 @@
       att__init_i8_0d%c_name=TRIM(ADJUSTL(cd_name))
 
-      att__init_i8_0d%i_type=NF90_INT
+      IF( PRESENT(id_type) )THEN
+         att__init_i8_0d%i_type=id_type
+      ELSE
+         att__init_i8_0d%i_type=NF90_INT
+      ENDIF
 
       IF( ASSOCIATED(att__init_i8_0d%d_value) )THEN
@@ -883,15 +1040,37 @@
 
    END FUNCTION att__init_i8_0d
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine print attribute information
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_att : attribute structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE att_print(td_att)
+   !-------------------------------------------------------------------
+   !> @brief This subroutine print informations of an array of attribute. 
+   !>
+   !> @author J.Paul
+   !> @date June, 2014 - Initial Version
+   !>
+   !> @param[in] td_att array of attribute structure
+   !-------------------------------------------------------------------
+   SUBROUTINE att__print_arr(td_att)
+      IMPLICIT NONE
+
+      ! Argument      
+      TYPE(TATT), DIMENSION(:), INTENT(IN) :: td_att
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      DO ji=1,SIZE(td_att(:))
+         CALL att_print(td_att(ji))
+      ENDDO
+
+   END SUBROUTINE att__print_arr
+   !-------------------------------------------------------------------
+   !> @brief This subroutine print attribute information.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !> @date September, 2014 - take into account type of attribute.
+   !
+   !> @param[in] td_att attribute structure
+   !-------------------------------------------------------------------
+   SUBROUTINE att__print_unit(td_att)
       IMPLICIT NONE
 
@@ -902,5 +1081,10 @@
       CHARACTER(LEN=lc) :: cl_type
       CHARACTER(LEN=lc) :: cl_value
-      CHARACTER(LEN=lc) :: cl_tmp
+
+      INTEGER(i8)       :: kl_tmp
+      INTEGER(i2)       :: sl_tmp
+      INTEGER(i1)       :: bl_tmp
+      REAL(sp)          :: rl_tmp
+      REAL(dp)          :: dl_tmp
 
       ! loop indices
@@ -924,5 +1108,5 @@
             CASE DEFAULT
                cl_type=''
-               !cl_type='unknown'
+
          END SELECT
 
@@ -932,21 +1116,69 @@
                cl_value=td_att%c_value
 
-            CASE(NF90_BYTE, NF90_SHORT, NF90_INT, NF90_FLOAT, NF90_DOUBLE)   
+            CASE(NF90_BYTE)   
                IF( td_att%i_len > 1 )THEN
-
-                  cl_tmp=','
                   cl_value='(/'
                   DO ji=1,td_att%i_len-1
-                     cl_value=TRIM(cl_value)//&
-                     &        TRIM(fct_str(td_att%d_value(ji)))//TRIM(cl_tmp)
+                     bl_tmp=INT(td_att%d_value(ji),i1)
+                     cl_value=TRIM(cl_value)//TRIM(fct_str(bl_tmp))//','
                   ENDDO
-                  cl_value=TRIM(cl_value)//&
-                  &        TRIM(fct_str(td_att%d_value(td_att%i_len)))//'/)'
-
+                  bl_tmp=INT(td_att%d_value(td_att%i_len),i1)
+                  cl_value=TRIM(cl_value)//TRIM(fct_str(bl_tmp))//'/)'
                ELSE
-
                   cl_value='(/'//TRIM(fct_str(td_att%d_value(1)))//'/)'
-
                ENDIF
+
+            CASE(NF90_SHORT)   
+               IF( td_att%i_len > 1 )THEN
+                  cl_value='(/'
+                  DO ji=1,td_att%i_len-1
+                     sl_tmp=INT(td_att%d_value(ji),i2)
+                     cl_value=TRIM(cl_value)//TRIM(fct_str(sl_tmp))//','
+                  ENDDO
+                  sl_tmp=INT(td_att%d_value(td_att%i_len),i2)
+                  cl_value=TRIM(cl_value)//TRIM(fct_str(sl_tmp))//'/)'
+               ELSE
+                  cl_value='(/'//TRIM(fct_str(td_att%d_value(1)))//'/)'
+               ENDIF
+
+            CASE(NF90_INT)   
+               IF( td_att%i_len > 1 )THEN
+                  cl_value='(/'
+                  DO ji=1,td_att%i_len-1
+                     kl_tmp=INT(td_att%d_value(ji),i8)
+                     cl_value=TRIM(cl_value)//TRIM(fct_str(kl_tmp))//','
+                  ENDDO
+                  kl_tmp=INT(td_att%d_value(td_att%i_len),i8)
+                  cl_value=TRIM(cl_value)//TRIM(fct_str(kl_tmp))//'/)'
+               ELSE
+                  cl_value='(/'//TRIM(fct_str(td_att%d_value(1)))//'/)'
+               ENDIF
+
+            CASE(NF90_FLOAT)   
+               IF( td_att%i_len > 1 )THEN
+                  cl_value='(/'
+                  DO ji=1,td_att%i_len-1
+                     rl_tmp=REAL(td_att%d_value(ji),sp)
+                     cl_value=TRIM(cl_value)//TRIM(fct_str(rl_tmp))//','
+                  ENDDO
+                  rl_tmp=REAL(td_att%d_value(td_att%i_len),sp)
+                  cl_value=TRIM(cl_value)//TRIM(fct_str(rl_tmp))//'/)'
+               ELSE
+                  cl_value='(/'//TRIM(fct_str(td_att%d_value(1)))//'/)'
+               ENDIF
+
+            CASE(NF90_DOUBLE)   
+               IF( td_att%i_len > 1 )THEN
+                  cl_value='(/'
+                  DO ji=1,td_att%i_len-1
+                     dl_tmp=REAL(td_att%d_value(ji),dp)
+                     cl_value=TRIM(cl_value)//TRIM(fct_str(dl_tmp))//','
+                  ENDDO
+                  dl_tmp=REAL(td_att%d_value(td_att%i_len),dp)
+                  cl_value=TRIM(cl_value)//TRIM(fct_str(dl_tmp))//'/)'
+               ELSE
+                  cl_value='(/'//TRIM(fct_str(td_att%d_value(1)))//'/)'
+               ENDIF
+
             CASE DEFAULT
                cl_value="none"
@@ -960,6 +1192,5 @@
          &        " value : ",TRIM(ADJUSTL(cl_value))
 
-   END SUBROUTINE att_print
-   !> @endcode
+   END SUBROUTINE att__print_unit
    !-------------------------------------------------------------------
    !> @brief 
@@ -967,10 +1198,9 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_att : attribute strcuture
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE att_clean( td_att )
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_att attribute strcuture
+   !-------------------------------------------------------------------
+   SUBROUTINE att__clean_unit( td_att )
       IMPLICIT NONE
       ! Argument
@@ -981,5 +1211,5 @@
       !----------------------------------------------------------------
 
-      CALL logger_info( &
+      CALL logger_trace( &
       &  " CLEAN: reset attribute "//TRIM(td_att%c_name) )
 
@@ -990,8 +1220,31 @@
 
       ! replace by empty structure
-      td_att=tl_att
-
-   END SUBROUTINE att_clean
-   !> @endcode
+      td_att=att_copy(tl_att)
+
+   END SUBROUTINE att__clean_unit
+   !-------------------------------------------------------------------
+   !> @brief 
+   !>  This subroutine clean array of attribute strcuture.
+   !
+   !> @author J.Paul
+   !> @date September, 2014 - Initial Version
+   !
+   !> @param[inout] td_att attribute strcuture
+   !-------------------------------------------------------------------
+   SUBROUTINE att__clean_arr( td_att )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TATT), DIMENSION(:), INTENT(INOUT) :: td_att
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      DO ji=SIZE(td_att(:)),1,-1
+         CALL att_clean(td_att(ji) )
+      ENDDO
+
+   END SUBROUTINE att__clean_arr
 END MODULE att
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/boundary.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/boundary.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/boundary.f90	(revision 5075)
@@ -8,17 +8,105 @@
 !> @brief
 !> This module manage boundary.
-!
+!>
 !> @details
+!>    define type TBDY:<br/>
+!> @code
+!>    TYPE(TBDY) :: tl_bdy<br/>
+!> @endcode
 !>
+!>    to initialise boundary structure:<br/>
+!> @code
+!>    tl_bdy=boundary_init(td_var, [ld_north,] [ld_south,] [ld_east,] [ld_west,]
+!>    [cd_north,] [cd_south,] [cd_east,] [cd_west,] [ld_oneseg])
+!> @endcode
+!>       - td_var is variable structure
+!>       - ld_north is logical to force used of north boundary [optional]
+!>       - ld_south is logical to force used of north boundary [optional]
+!>       - ld_east  is logical to force used of north boundary [optional]
+!>       - ld_west  is logical to force used of north boundary [optional]
+!>       - cd_north is string character description of north boundary [optional]
+!>       - cd_south is string character description of north boundary [optional]
+!>       - cd_east  is string character description of north boundary [optional]
+!>       - cd_west  is string character description of north boundary [optional]
+!>       - ld_oneseg is logical to force to use only one segment for each boundary [optional]
 !>
+!>    to get boundary cardinal:<br/>
+!>    - tl_bdy\%c_card
 !>
+!>    to know if boundary is use:<br/>
+!>    - tl_bdy\%l_use
 !>
+!>    to get the number of segment in boundary:<br/>
+!>    - tl_bdy\%i_nseg
 !>
-!> @author
-!> J.Paul
+!>    to get array of segment in boundary:<br/>
+!>    - tl_bdy\%t_seg(:)
+!>
+!>    to get orthogonal segment index of north boundary:<br/>
+!>    - tl_bdy\%t_seg(jp_north)%\i_index
+!>
+!>    to get segment width of south boundary:<br/>
+!>    - tl_bdy\%t_seg(jp_south)%\i_width
+!>
+!>    to get segment first indice of east boundary:<br/>
+!>    - tl_bdy\%t_seg(jp_east)%\i_first
+!>
+!>    to get segment last indice of west boundary:<br/>
+!>    - tl_bdy\%t_seg(jp_west)%\i_last
+!>
+!>    to print information about boundary:<br/>
+!> @code
+!>    CALL boundary_print(td_bdy)
+!> @endcode
+!>       - td_bdy is boundary structure or a array of boundary structure
+!>
+!>    to clean boundary structure:<br/>
+!> @code
+!>    CALL boundary_clean(td_bdy)
+!> @endcode
+!>
+!>    to get indices of each semgent for each boundary:<br/>
+!> @code
+!>    CALL boundary_get_indices( td_bdy, td_var, ld_oneseg)
+!> @endcode
+!>       - td_bdy is boundary structure
+!>       - td_var is variable structure
+!>       - ld_oneseg is logical to force to use only one segment for each boundary [optional]
+!>
+!>    to check boundary indices and corner:<br/>
+!> @code
+!>    CALL boundary_check(td_bdy, td_var)
+!> @endcode
+!>       - td_bdy is boundary structure
+!>       - td_var is variable structure
+!>
+!>    to check boundary corner:<br/>
+!> @code
+!>    CALL boundary_check_corner(td_bdy, td_var)
+!> @endcode
+!>       - td_bdy is boundary structure
+!>       - td_var is variable structure
+!>
+!>    to create filename with cardinal name inside:<br/>
+!> @code
+!>    cl_filename=boundary_set_filename(cd_file, cd_card)
+!> @endcode
+!>       - cd_file = original file name
+!>       - cd_card = cardinal name
+!>
+!>    to swap array for east and north boundary:<br/>
+!> @code
+!>    CALL boundary_swap( td_var, td_bdy )
+!> @endcode
+!>       - td_var is variable strucutre
+!>       - td_bdy is boundary strucutre
+!>
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!> @todo
-!> - add description generique de l'objet boundary
+!> @date November, 2013 - Initial Version
+!> @date September, 2014 - add boundary description
+!> @date November, 2014 - Fix memory leaks bug
+!> 
+!> @todo add schematic to boundary structure description
 !> 
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -29,31 +117,19 @@
    USE phycst                          ! physical constant
    USE kind                            ! F90 kind parameter
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE fct                             ! basic useful function
-!   USE date                            ! date manager
-!   USE att                             ! attribute manager
-!   USE dim                             ! dimension manager
    USE var                             ! variable manager
-!   USE file                            ! file manager
-!   USE iom                             ! I/O manager
-!   USE dom                             ! domain  manager
-!   USE grid                            ! grid manager
-!   USE extrap                          ! extrapolation manager
-!   USE interp                          ! interpolation manager
-!   USE filter                          ! filter manager
-!   USE mpp                             ! MPP manager
-!   USE iom_mpp                         ! MPP I/O manager
 
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
-   PUBLIC :: ip_ncard !< number of cardinal point
-   PUBLIC :: ip_card  !< table of cardinal point
    PUBLIC :: TBDY     !< boundary structure
    PUBLIC :: TSEG     !< segment structure
 
+   PRIVATE :: im_width !< boundary width
+
    ! function and subroutine
+   PUBLIC :: boundary_copy         !< copy boundary structure
    PUBLIC :: boundary_init         !< initialise boundary structure
    PUBLIC :: boundary_print        !< print information about boundary
@@ -63,26 +139,29 @@
    PUBLIC :: boundary_check_corner !< check boundary corner
    PUBLIC :: boundary_set_filename !< set boundary filename
-   PUBLIC :: boundary_clean_interp !< clean interpolated boundary
    PUBLIC :: boundary_swap         !< swap array for north and east boundary
 
-   PRIVATE :: boundary__init_wrapper    !< initialise a boundary structure
-   PRIVATE :: boundary__init            !< initialise basically a boundary structure
-!   PRIVATE :: boundary__copy            !< copy boundary structure in another
-   PRIVATE :: boundary__copy_unit       !< copy boundary structure in another
-   PRIVATE :: boundary__copy_tab        !< copy boundary structure in another
-   PRIVATE :: boundary__add_seg         !< add one segment structure to a boundary 
-   PRIVATE :: boundary__del_seg         !< remove all segments of a boundary
-   PRIVATE :: boundary__get_info        !< get boundary information from boundary description string character.
-   PRIVATE :: boundary__get_seg_number  !< compute the number of sea segment for one boundary
-   PRIVATE :: boundary__get_seg_indices !< get segment indices for one boundary 
-   PRIVATE :: boundary__print_unit      !< print information about one boundary
-   PRIVATE :: boundary__print_tab       !< print information about a table of boundary
+   PRIVATE :: boundary__clean_unit      ! clean boundary structure 
+   PRIVATE :: boundary__clean_arr       ! clean array of boundary structure 
+   PRIVATE :: boundary__init_wrapper    ! initialise a boundary structure
+   PRIVATE :: boundary__init            ! initialise basically a boundary structure
+   PRIVATE :: boundary__copy_unit       ! copy boundary structure in another
+   PRIVATE :: boundary__copy_arr        ! copy boundary structure in another
+   PRIVATE :: boundary__add_seg         ! add one segment structure to a boundary 
+   PRIVATE :: boundary__del_seg         ! remove all segments of a boundary
+   PRIVATE :: boundary__get_info        ! get boundary information from boundary description string character.
+   PRIVATE :: boundary__get_seg_number  ! compute the number of sea segment for one boundary
+   PRIVATE :: boundary__get_seg_indices ! get segment indices for one boundary 
+   PRIVATE :: boundary__print_unit      ! print information about one boundary
+   PRIVATE :: boundary__print_arr       ! print information about a array of boundary
    
-   PRIVATE :: seg__init    !< initialise segment structure
-   PRIVATE :: seg__clean   !< clean segment structure
-   PRIVATE :: seg__copy    !< copy segment structure in another
-
-   !> @struct
-   TYPE TSEG   
+   PRIVATE :: seg__init       ! initialise segment structure
+   PRIVATE :: seg__clean      ! clean segment structure
+   PRIVATE :: seg__clean_unit ! clean segment structure
+   PRIVATE :: seg__clean_arr  ! clean array of segment structure
+   PRIVATE :: seg__copy       ! copy segment structure in another
+   PRIVATE :: seg__copy_unit  ! copy segment structure in another
+   PRIVATE :: seg__copy_arr   ! copy array of segment structure in another
+
+   TYPE TSEG   !< segment structure
       INTEGER(i4) :: i_index = 0 !< segment index
       INTEGER(i4) :: i_width = 0 !< segment width
@@ -91,23 +170,10 @@
    END TYPE TSEG
 
-   !> @struct
-   TYPE TBDY
-      CHARACTER(LEN=lc) :: c_card = ''
-      LOGICAL           :: l_use  = .FALSE.
-      INTEGER(i4)       :: i_nseg = 0
-      TYPE(TSEG), DIMENSION(:), POINTER :: t_seg => NULL()
+   TYPE TBDY !< boundary structure
+      CHARACTER(LEN=lc) :: c_card = ''          !< boundary cardinal
+      LOGICAL           :: l_use  = .FALSE.     !< boundary use or not 
+      INTEGER(i4)       :: i_nseg = 0           !< number of segment in boundary
+      TYPE(TSEG), DIMENSION(:), POINTER :: t_seg => NULL() !<  array of segment structure
    END TYPE TBDY
-
-   INTEGER(i4), PARAMETER :: ip_ncard=4
-   CHARACTER(LEN=lc), DIMENSION(ip_ncard), PARAMETER :: ip_card = &
-   &  (/ 'north', &
-   &     'south', &
-   &     'east ', &
-   &     'west ' /)
-
-   INTEGER(i4), PARAMETER :: jp_north=1
-   INTEGER(i4), PARAMETER :: jp_south=2
-   INTEGER(i4), PARAMETER :: jp_east =3
-   INTEGER(i4), PARAMETER :: jp_west =4
 
    INTEGER(i4), PARAMETER :: im_width=10
@@ -119,11 +185,25 @@
    INTERFACE boundary_print
       MODULE PROCEDURE boundary__print_unit 
-      MODULE PROCEDURE boundary__print_tab 
+      MODULE PROCEDURE boundary__print_arr 
    END INTERFACE boundary_print
 
-   INTERFACE ASSIGNMENT(=)
+   INTERFACE boundary_clean
+      MODULE PROCEDURE boundary__clean_unit   
+      MODULE PROCEDURE boundary__clean_arr    
+   END INTERFACE
+
+   INTERFACE seg__clean
+      MODULE PROCEDURE seg__clean_unit   
+      MODULE PROCEDURE seg__clean_arr    
+   END INTERFACE
+
+   INTERFACE boundary_copy
       MODULE PROCEDURE boundary__copy_unit 
-      MODULE PROCEDURE boundary__copy_tab 
-      MODULE PROCEDURE seg__copy   ! copy segment structure
+      MODULE PROCEDURE boundary__copy_arr 
+   END INTERFACE   
+
+   INTERFACE seg__copy
+      MODULE PROCEDURE seg__copy_unit   ! copy segment structure
+      MODULE PROCEDURE seg__copy_arr    ! copy array of segment structure
    END INTERFACE   
 
@@ -131,23 +211,28 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine copy boundary structure in another boundary
-   !> structure
+   !> This subroutine copy a array of boundary structure in another one
    !> @details 
    !>
+   !> @warning do not use on the output of a function who create or read an
+   !> attribute (ex: tl_bdy=boundary_copy(boundary_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
    !
-   !> @param[out] td_bdy1  : boundary structure
-   !> @param[in] td_bdy2  : boundary structure
+   !> @param[in] td_bdy   array of boundary structure
+   !> @return copy of input array of boundary structure 
    !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE boundary__copy_tab( td_bdy1, td_bdy2 )
+   FUNCTION boundary__copy_arr( td_bdy )
       IMPLICIT NONE
       ! Argument
-      TYPE(TBDY), DIMENSION(:), INTENT(OUT) :: td_bdy1
-      TYPE(TBDY), DIMENSION(:), INTENT(IN)  :: td_bdy2
+      TYPE(TBDY), DIMENSION(:), INTENT(IN)  :: td_bdy
+      ! function
+      TYPE(TBDY), DIMENSION(SIZE(td_bdy(:))) :: boundary__copy_arr
 
       ! local variable
@@ -156,34 +241,35 @@
       !----------------------------------------------------------------
 
-      IF( SIZE(td_bdy1(:)) /= SIZE(td_bdy2(:)) )THEN
-         CALL logger_error("BOUNDARY COPY: dimension of table of boundary differ")
-      ELSE
-         DO jk=1,SIZE(td_bdy1(:))
-            td_bdy1(jk)=td_bdy2(jk)
-         ENDDO
-      ENDIF
-   END SUBROUTINE boundary__copy_tab
-   !> @endcode
+      DO jk=1,SIZE(td_bdy(:))
+         boundary__copy_arr(jk)=boundary_copy(td_bdy(jk))
+      ENDDO
+
+   END FUNCTION boundary__copy_arr
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine copy boundary structure in another boundary
-   !> structure
+   !> This subroutine copy boundary structure in another one
    !> @details 
    !>
+   !> @warning do not use on the output of a function who create or read an
+   !> attribute (ex: tl_bdy=boundary_copy(boundary_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
    !
-   !> @param[out] td_bdy1  : boundary structure
-   !> @param[in] td_bdy2  : boundary structure
+   !> @param[in] td_bdy   boundary structure
+   !> @return copy of input boundary structure
    !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE boundary__copy_unit( td_bdy1, td_bdy2 )
+   FUNCTION boundary__copy_unit( td_bdy )
       IMPLICIT NONE
       ! Argument
-      TYPE(TBDY), INTENT(OUT) :: td_bdy1
-      TYPE(TBDY), INTENT(IN)  :: td_bdy2
+      TYPE(TBDY), INTENT(IN)  :: td_bdy
+      ! function
+      TYPE(TBDY) :: boundary__copy_unit
 
       ! local variable
@@ -193,29 +279,30 @@
 
       ! copy variable name, id, ..
-      td_bdy1%c_card     = TRIM(td_bdy2%c_card)
-      td_bdy1%i_nseg     = td_bdy2%i_nseg
-      td_bdy1%l_use      = td_bdy2%l_use
+      boundary__copy_unit%c_card     = TRIM(td_bdy%c_card)
+      boundary__copy_unit%i_nseg     = td_bdy%i_nseg
+      boundary__copy_unit%l_use      = td_bdy%l_use
 
       ! copy segment
-      IF( ASSOCIATED(td_bdy1%t_seg) ) DEALLOCATE(td_bdy1%t_seg)
-      IF( ASSOCIATED(td_bdy2%t_seg) .AND. td_bdy1%i_nseg > 0 )THEN
-         ALLOCATE( td_bdy1%t_seg(td_bdy1%i_nseg) )
-         DO ji=1,td_bdy1%i_nseg
-            td_bdy1%t_seg(ji)=td_bdy2%t_seg(ji)
+      IF( ASSOCIATED(boundary__copy_unit%t_seg) )THEN
+         CALL seg__clean(boundary__copy_unit%t_seg(:))
+         DEALLOCATE(boundary__copy_unit%t_seg)
+      ENDIF
+      IF( ASSOCIATED(td_bdy%t_seg) .AND. boundary__copy_unit%i_nseg > 0 )THEN
+         ALLOCATE( boundary__copy_unit%t_seg(boundary__copy_unit%i_nseg) )
+         DO ji=1,boundary__copy_unit%i_nseg
+            boundary__copy_unit%t_seg(ji)=td_bdy%t_seg(ji)
          ENDDO
       ENDIF
 
-   END SUBROUTINE boundary__copy_unit
-   !> @endcode
+   END FUNCTION boundary__copy_unit
    !-------------------------------------------------------------------
    !> @brief This subroutine clean boundary structure
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
-   !> @param[inout] td_bdy : boundary strucutre
+   !> @param[inout] td_bdy boundary strucutre
    !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE boundary_clean( td_bdy )
+   SUBROUTINE boundary__clean_unit( td_bdy )
       IMPLICIT NONE
       ! Argument
@@ -226,42 +313,64 @@
 
       ! loop indices
+      !----------------------------------------------------------------
+
+      CALL logger_info( &
+      &  " CLEAN: reset boundary "//TRIM(td_bdy%c_card) )
+
+      ! del segment
+      IF( ASSOCIATED(td_bdy%t_seg) )THEN
+         ! clean each segment
+         CALL seg__clean(td_bdy%t_seg(:) )
+         DEALLOCATE( td_bdy%t_seg )
+      ENDIF
+
+      ! replace by empty structure
+      td_bdy=boundary_copy(tl_bdy)
+
+   END SUBROUTINE boundary__clean_unit
+   !-------------------------------------------------------------------
+   !> @brief This subroutine clean array of boundary structure
+   !
+   !> @author J.Paul
+   !> @date September, 2014 - Initial Version
+   !
+   !> @param[inout] td_bdy boundary strucutre
+   !-------------------------------------------------------------------
+   SUBROUTINE boundary__clean_arr( td_bdy )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TBDY), DIMENSION(:), INTENT(INOUT) :: td_bdy
+
+      ! local variable
+      ! loop indices
       INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
-      CALL logger_info( &
-      &  " CLEAN: reset boundary "//TRIM(td_bdy%c_card) )
-
-      ! del segment
-      IF( ASSOCIATED(td_bdy%t_seg) )THEN
-         ! clean each attribute
-         DO ji=td_bdy%i_nseg,1,-1
-            CALL seg__clean(td_bdy%t_seg(ji) )
-         ENDDO
-         DEALLOCATE( td_bdy%t_seg )
-      ENDIF
-
-      ! replace by empty structure
-      td_bdy=tl_bdy
-
-   END SUBROUTINE boundary_clean
-   !> @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This function put cardinal name inside file name  
+      DO ji=SIZE(td_bdy(:)),1,-1
+         CALL boundary_clean( td_bdy(ji) )
+      ENDDO
+
+   END SUBROUTINE boundary__clean_arr
+   !------------------------------------------------------------------- 
+   !> @brief This function put cardinal name inside file name.
    ! 
    !> @details 
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[in] cd_file : file name 
-   !> @param[in] cd_card : cardinal name 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[in] cd_file   file name 
+   !> @param[in] cd_card   cardinal name 
+   !> @param[in] id_seg    segment number 
+   !> @param[in] cd_date   file date (format: y????m??d??) 
    !> @return file name with cardinal name inside
    !------------------------------------------------------------------- 
-   !> @code 
-   FUNCTION boundary_set_filename(cd_file, cd_card) 
+   FUNCTION boundary_set_filename(cd_file, cd_card, id_seg, cd_date) 
       IMPLICIT NONE 
       ! Argument
       CHARACTER(LEN=*), INTENT(IN) :: cd_file
       CHARACTER(LEN=*), INTENT(IN) :: cd_card
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_seg
+      CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: cd_date
 
       ! function 
@@ -273,4 +382,6 @@
       CHARACTER(LEN=lc) :: cl_base
       CHARACTER(LEN=lc) :: cl_suffix
+      CHARACTER(LEN=lc) :: cl_segnum
+      CHARACTER(LEN=lc) :: cl_date
       CHARACTER(LEN=lc) :: cl_name
       ! loop indices 
@@ -288,6 +399,19 @@
          cl_base  =fct_split(TRIM(cl_basename),1,'.')
          cl_suffix=fct_split(TRIM(cl_basename),2,'.')
-
-         cl_name=TRIM(cl_base)//"_"//TRIM(cd_card)//"."//TRIM(cl_suffix)
+         
+         IF( PRESENT(id_seg) )THEN
+            cl_segnum="_"//TRIM(fct_str(id_seg))//"_"
+         ELSE
+            cl_segnum=""
+         ENDIF
+
+         IF( PRESENT(cd_date) )THEN
+            cl_date=TRIM(ADJUSTL(cd_date))
+         ELSE
+            cl_date=""
+         ENDIF
+
+         cl_name=TRIM(cl_base)//"_"//TRIM(cd_card)//TRIM(cl_segnum)//&
+         &        TRIM(cl_date)//"."//TRIM(cl_suffix)
 
          boundary_set_filename=TRIM(cl_dirname)//"/"//TRIM(cl_name)
@@ -298,7 +422,6 @@
  
    END FUNCTION boundary_set_filename 
-   !> @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This function initialise a boundary structure 
+   !------------------------------------------------------------------- 
+   !> @brief This function initialise a boundary structure.
    ! 
    !> @details 
@@ -318,21 +441,26 @@
    !> specify it for each segment.
    !> ex : cn_north='index1,first1,last1(width)|index2,first2,last2'
-   ! 
+   !>
+   !> @note boundaries are compute on T point. change will be done to get data
+   !> on other point when need be. 
+   !>
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[in] td_var : variable structure 
-   !> @param[in] ld_north : use north boundary or not 
-   !> @param[in] ld_south : use south boundary or not 
-   !> @param[in] ld_east  : use east  boundary or not 
-   !> @param[in] ld_west  : use west  boundary or not 
-   !> @param[in] cd_north : north boundary description 
-   !> @param[in] cd_south : south boundary description 
-   !> @param[in] cd_east  : east  boundary description 
-   !> @param[in] cd_west  : west  boundary description 
+   !> @date November, 2013 - Initial Version 
+   !> @date September, 2014
+   !> - add boolean to use only one segment for each boundary
+   !> - check boundary width
+   ! 
+   !> @param[in] td_var    variable structure 
+   !> @param[in] ld_north  use north boundary or not 
+   !> @param[in] ld_south  use south boundary or not 
+   !> @param[in] ld_east   use east  boundary or not 
+   !> @param[in] ld_west   use west  boundary or not 
+   !> @param[in] cd_north  north boundary description 
+   !> @param[in] cd_south  south boundary description 
+   !> @param[in] cd_east   east  boundary description 
+   !> @param[in] cd_west   west  boundary description 
+   !> @param[in] ld_oneseg force to use only one segment for each boundary 
    !> @return boundary structure
-   !> @todo use bondary_get_indices !!!!
-   !------------------------------------------------------------------- 
-   !> @code 
+   !------------------------------------------------------------------- 
    FUNCTION boundary__init_wrapper(td_var, &
    &                               ld_north, ld_south, ld_east, ld_west, &
@@ -356,4 +484,6 @@
 
       ! local variable 
+      INTEGER(i4)                            :: il_width
+      INTEGER(i4)      , DIMENSION(ip_ncard) :: il_max_width
       INTEGER(i4)      , DIMENSION(ip_ncard) :: il_index
       INTEGER(i4)      , DIMENSION(ip_ncard) :: il_min
@@ -390,16 +520,20 @@
          tl_bdy(jp_west )=boundary__init('west ',ld_west )
 
-         ! if EW cyclic no east west boundary
+         ! if EW cyclic no east west boundary and force to use one segment
          IF( td_var%i_ew >= 0 )THEN
-            CALL logger_debug("BOUNDARY INIT: cyclic no East West boundary")
+            CALL logger_info("BOUNDARY INIT: cyclic domain, "//&
+            &  "no East West boundary")
             tl_bdy(jp_east )%l_use=.FALSE.
             tl_bdy(jp_west )%l_use=.FALSE.
+
+            CALL logger_info("BOUNDARY INIT: force to use one segment due"//&
+            &  " to EW cyclic domain")
+            ll_oneseg=.TRUE.
          ENDIF
 
-         ! attention cas U /= T ???
-         il_index(jp_north)=td_var%t_dim(2)%i_len-ig_ghost
-         il_index(jp_south)=1+ig_ghost
-         il_index(jp_east )=td_var%t_dim(1)%i_len-ig_ghost
-         il_index(jp_west )=1+ig_ghost
+         il_index(jp_north)=td_var%t_dim(2)%i_len-ip_ghost
+         il_index(jp_south)=1+ip_ghost
+         il_index(jp_east )=td_var%t_dim(1)%i_len-ip_ghost
+         il_index(jp_west )=1+ip_ghost
 
          il_min(jp_north)=1
@@ -419,8 +553,28 @@
          IF( PRESENT(cd_west ) ) cl_card(jp_west )=TRIM(cd_west )
 
+         il_max_width(jp_north)=INT(0.5*(td_var%t_dim(2)%i_len-2*ip_ghost))
+         il_max_width(jp_south)=INT(0.5*(td_var%t_dim(2)%i_len-2*ip_ghost))
+         il_max_width(jp_east )=INT(0.5*(td_var%t_dim(1)%i_len-2*ip_ghost))
+         il_max_width(jp_west )=INT(0.5*(td_var%t_dim(1)%i_len-2*ip_ghost))
+
          DO jk=1,ip_ncard
 
+            ! check boundary width
+            IF( il_max_width(jk) <= im_width )THEN
+               IF( il_max_width(jk) <= 0 )THEN
+                  CALL logger_fatal("BOUNDARY INIT: domain too small to define"//&
+                  &                " boundaries.")
+               ELSE
+                  CALL logger_warn("BOUNDARY INIT: default boundary width too "//&
+                  &                "large for boundaries. force to use boundary"//&
+                  &                " on one point")
+                  il_width=1
+               ENDIF
+            ELSE
+               il_width=im_width
+            ENDIF
+
             ! define default segment
-            tl_seg=seg__init(il_index(jk),im_width,il_min(jk),il_max(jk))
+            tl_seg=seg__init(il_index(jk),il_width,il_min(jk),il_max(jk))
 
             IF( tl_bdy(jk)%l_use )THEN
@@ -453,4 +607,6 @@
 
             ENDIF
+            ! clean
+            CALL seg__clean(tl_seg)
 
          ENDDO
@@ -460,5 +616,5 @@
          CALL boundary_check(tl_bdy, td_var)
 
-         boundary__init_wrapper(:)=tl_bdy(:)
+         boundary__init_wrapper(:)=boundary_copy(tl_bdy(:))
 
          ! clean
@@ -470,5 +626,4 @@
  
    END FUNCTION boundary__init_wrapper 
-   !> @endcode 
    !------------------------------------------------------------------- 
    !> @brief This function initialise basically a boundary structure with
@@ -480,12 +635,11 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[in]  cd_card : cardinal name
-   !> @param[in]  ld_use  : boundary use or not
-   !> @param[in]  td_seg  : segment structure
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[in]  cd_card  cardinal name
+   !> @param[in]  ld_use   boundary use or not
+   !> @param[in]  td_seg   segment structure
    !> @return boundary structure
    !------------------------------------------------------------------- 
-   !> @code 
    FUNCTION boundary__init( cd_card, ld_use, td_seg ) 
       IMPLICIT NONE 
@@ -520,5 +674,4 @@
 
    END FUNCTION boundary__init
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This subroutine add one segment structure to a boundary structure 
@@ -527,10 +680,9 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[inout] td_bdy : boundary structure  
-   !> @param[in] td_seg : segment structure  
-   !------------------------------------------------------------------- 
-   !> @code 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout] td_bdy boundary structure  
+   !> @param[in] td_seg    segment structure  
+   !------------------------------------------------------------------- 
    SUBROUTINE boundary__add_seg(td_bdy, td_seg) 
       IMPLICIT NONE 
@@ -554,6 +706,7 @@
          ELSE
             ! save temporary segment
-            tl_seg(:)=td_bdy%t_seg(:)
-
+            tl_seg(:)=seg__copy(td_bdy%t_seg(:))
+
+            CALL seg__clean(td_bdy%t_seg(:))
             DEALLOCATE( td_bdy%t_seg )
             ALLOCATE( td_bdy%t_seg(td_bdy%i_nseg+1), stat=il_status )
@@ -564,6 +717,8 @@
 
             ! copy segment in boundary before
-            td_bdy%t_seg(1:td_bdy%i_nseg)=tl_seg(:)
-
+            td_bdy%t_seg(1:td_bdy%i_nseg)=seg__copy(tl_seg(:))
+
+            ! clean
+            CALL seg__clean(tl_seg(:))
             DEALLOCATE(tl_seg)            
             
@@ -572,4 +727,5 @@
          ! no segment in boundary structure
          IF( ASSOCIATED(td_bdy%t_seg) )THEN
+            CALL seg__clean(td_bdy%t_seg(:))
             DEALLOCATE(td_bdy%t_seg)
          ENDIF
@@ -585,8 +741,7 @@
 
       ! add new segment
-      td_bdy%t_seg(td_bdy%i_nseg)=td_seg
+      td_bdy%t_seg(td_bdy%i_nseg)=seg__copy(td_seg)
 
    END SUBROUTINE boundary__add_seg 
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This subroutine remove all segments of a boundary structure 
@@ -595,9 +750,8 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[inout]  td_bdy : boundary structure
-   !------------------------------------------------------------------- 
-   !> @code 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout]  td_bdy   boundary structure
+   !------------------------------------------------------------------- 
    SUBROUTINE boundary__del_seg(td_bdy) 
       IMPLICIT NONE 
@@ -610,4 +764,5 @@
 
       IF( ASSOCIATED(td_bdy%t_seg) )THEN
+         CALL seg__clean(td_bdy%t_seg(:))
          DEALLOCATE(td_bdy%t_seg)
       ENDIF
@@ -616,5 +771,4 @@
 
    END SUBROUTINE boundary__del_seg 
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This function get information about boundary from string character. 
@@ -627,10 +781,9 @@
    !> 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[in] cd_card : boundary description
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[in] cd_card   boundary description
    !> @return boundary structure
    !------------------------------------------------------------------- 
-   !> @code 
    FUNCTION boundary__get_info(cd_card) 
       IMPLICIT NONE 
@@ -737,8 +890,10 @@
          ji=ji+1
          cl_seg=fct_split(cd_card,ji)
+
+         ! clean
+         CALL seg__clean(tl_seg)
       ENDDO 
 
    END FUNCTION boundary__get_info 
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This subroutine get indices of each semgent for each boundary.
@@ -757,11 +912,10 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[inout] td_bdy : boundary structure  
-   !> @param[in] td_var : variable structure 
-   !> @param[in] ld_onseg : use only one sgment for each boundary 
-   !------------------------------------------------------------------- 
-   !> @code 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout] td_bdy boundary structure  
+   !> @param[in] td_var    variable structure 
+   !> @param[in] ld_onseg  use only one sgment for each boundary 
+   !------------------------------------------------------------------- 
    SUBROUTINE boundary_get_indices( td_bdy, td_var, ld_oneseg) 
       IMPLICIT NONE 
@@ -811,5 +965,5 @@
 
                IF( ll_oneseg .AND. td_bdy(jk)%l_use )THEN
-                  tl_seg=td_bdy(jk)%t_seg(1)
+                  tl_seg=seg__copy(td_bdy(jk)%t_seg(1))
                   ! use last indice of last segment
                   tl_seg%i_last=td_bdy(jk)%t_seg(td_bdy(jk)%i_nseg)%i_last
@@ -820,4 +974,7 @@
                   ! add one segment
                   CALL boundary__add_seg(td_bdy(jk),tl_seg)
+
+                  ! clean
+                  CALL seg__clean(tl_seg)
                ENDIF
 
@@ -829,5 +986,4 @@
 
    END SUBROUTINE boundary_get_indices 
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This subroutine compute the number of sea segment. 
@@ -841,10 +997,9 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[inout] td_bdy : boundary structure 
-   !> @param[in] td_var : variable structure 
-   !------------------------------------------------------------------- 
-   !> @code 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout] td_bdy boundary structure 
+   !> @param[in] td_var    variable structure 
+   !------------------------------------------------------------------- 
    SUBROUTINE boundary__get_seg_number( td_bdy, td_var) 
       IMPLICIT NONE 
@@ -927,8 +1082,6 @@
          END SELECT
       ENDIF
-
-      
+ 
    END SUBROUTINE boundary__get_seg_number 
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This subroutine get segment indices for one boundary.
@@ -937,14 +1090,13 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[inout] td_bdy : boundary structure  
-   !> @param[in] td_var : variable structure  
-   !> @param[in] id_index : boundary orthogonal index  
-   !> @param[in] id_width : bounary width 
-   !> @param[in] id_first : boundary first indice
-   !> @param[in] id_last  : boundary last  indice
-   !------------------------------------------------------------------- 
-   !> @code 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout] td_bdy boundary structure  
+   !> @param[in] td_var    variable structure  
+   !> @param[in] id_index  boundary orthogonal index  
+   !> @param[in] id_width  bounary width 
+   !> @param[in] id_first  boundary first indice
+   !> @param[in] id_last   boundary last  indice
+   !------------------------------------------------------------------- 
    SUBROUTINE boundary__get_seg_indices( td_bdy, td_var, &
    &                                     id_index, id_width, id_first, id_last) 
@@ -1004,13 +1156,13 @@
       END SELECT
 
-      il_max(jp_north)=td_var%t_dim(1)%i_len-ig_ghost
-      il_max(jp_south)=td_var%t_dim(1)%i_len-ig_ghost
-      il_max(jp_east )=td_var%t_dim(2)%i_len-ig_ghost
-      il_max(jp_west )=td_var%t_dim(2)%i_len-ig_ghost
-
-      il_min(jp_north)=1+ig_ghost
-      il_min(jp_south)=1+ig_ghost
-      il_min(jp_east )=1+ig_ghost
-      il_min(jp_west )=1+ig_ghost
+      il_max(jp_north)=td_var%t_dim(1)%i_len-ip_ghost
+      il_max(jp_south)=td_var%t_dim(1)%i_len-ip_ghost
+      il_max(jp_east )=td_var%t_dim(2)%i_len-ip_ghost
+      il_max(jp_west )=td_var%t_dim(2)%i_len-ip_ghost
+
+      il_min(jp_north)=1+ip_ghost
+      il_min(jp_south)=1+ip_ghost
+      il_min(jp_east )=1+ip_ghost
+      il_min(jp_west )=1+ip_ghost
          
       ! special case for EW cyclic 
@@ -1074,4 +1226,5 @@
          CALL boundary__add_seg(td_bdy,tl_seg)
 
+         ! clean
          CALL seg__clean(tl_seg)
          
@@ -1081,5 +1234,4 @@
       
    END SUBROUTINE boundary__get_seg_indices 
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This subroutine check if there is boundary at corner, and 
@@ -1094,12 +1246,9 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[inout] td_bdy : boundary structure
-   !> @param[in] td_var : variable structure
-   !> 
-   !> @todo add schematic to description
-   !------------------------------------------------------------------- 
-   !> @code 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout] td_bdy boundary structure
+   !> @param[in] td_var    variable structure
+   !------------------------------------------------------------------- 
    SUBROUTINE boundary_check_corner( td_bdy, td_var )
       IMPLICIT NONE 
@@ -1126,6 +1275,6 @@
       ! check north west corner
       IF( td_bdy(jp_north)%l_use .AND. td_bdy(jp_west)%l_use )THEN
-         tl_west =td_bdy(jp_west )%t_seg(td_bdy(jp_west)%i_nseg)
-         tl_north=td_bdy(jp_north)%t_seg(1)
+         tl_west =seg__copy(td_bdy(jp_west )%t_seg(td_bdy(jp_west)%i_nseg))
+         tl_north=seg__copy(td_bdy(jp_north)%t_seg(1))
 
          IF( tl_west%i_last  >= tl_north%i_index .AND. &
@@ -1148,6 +1297,6 @@
             ENDIF
 
-            td_bdy(jp_west )%t_seg(td_bdy(jp_west)%i_nseg)=tl_west
-            td_bdy(jp_north)%t_seg(1)                     =tl_north
+            td_bdy(jp_west )%t_seg(td_bdy(jp_west)%i_nseg)=seg__copy(tl_west)
+            td_bdy(jp_north)%t_seg(1)                     =seg__copy(tl_north)
 
          ELSE
@@ -1169,6 +1318,6 @@
       ! check north east corner
       IF( td_bdy(jp_north)%l_use .AND. td_bdy(jp_east)%l_use )THEN
-         tl_east =td_bdy(jp_east )%t_seg(td_bdy(jp_east )%i_nseg)
-         tl_north=td_bdy(jp_north)%t_seg(td_bdy(jp_north)%i_nseg)
+         tl_east =seg__copy(td_bdy(jp_east )%t_seg(td_bdy(jp_east )%i_nseg))
+         tl_north=seg__copy(td_bdy(jp_north)%t_seg(td_bdy(jp_north)%i_nseg))
 
          IF( tl_east%i_last  >= tl_north%i_index .AND. &
@@ -1191,6 +1340,6 @@
             ENDIF
 
-            td_bdy(jp_east )%t_seg(td_bdy(jp_east )%i_nseg)=tl_east
-            td_bdy(jp_north)%t_seg(td_bdy(jp_north)%i_nseg)=tl_north
+            td_bdy(jp_east )%t_seg(td_bdy(jp_east )%i_nseg)=seg__copy(tl_east)
+            td_bdy(jp_north)%t_seg(td_bdy(jp_north)%i_nseg)=seg__copy(tl_north)
          ELSE
 
@@ -1211,6 +1360,6 @@
       ! check south east corner
       IF( td_bdy(jp_south)%l_use .AND. td_bdy(jp_east)%l_use )THEN
-         tl_east =td_bdy(jp_east )%t_seg(1)
-         tl_south=td_bdy(jp_south)%t_seg(td_bdy(jp_south)%i_nseg)
+         tl_east =seg__copy(td_bdy(jp_east )%t_seg(1))
+         tl_south=seg__copy(td_bdy(jp_south)%t_seg(td_bdy(jp_south)%i_nseg))
 
          IF( tl_east%i_first <= tl_south%i_index .AND. &
@@ -1233,6 +1382,6 @@
             ENDIF
 
-            td_bdy(jp_east )%t_seg(1)                      =tl_east
-            td_bdy(jp_south)%t_seg(td_bdy(jp_south)%i_nseg)=tl_south
+            td_bdy(jp_east )%t_seg(1)                      =seg__copy(tl_east)
+            td_bdy(jp_south)%t_seg(td_bdy(jp_south)%i_nseg)=seg__copy(tl_south)
          ELSE
 
@@ -1253,6 +1402,6 @@
       ! check south west corner
       IF( td_bdy(jp_south)%l_use .AND. td_bdy(jp_west)%l_use )THEN
-         tl_west =td_bdy(jp_west )%t_seg(1)
-         tl_south=td_bdy(jp_south)%t_seg(1)
+         tl_west =seg__copy(td_bdy(jp_west )%t_seg(1))
+         tl_south=seg__copy(td_bdy(jp_south)%t_seg(1))
 
          IF( tl_west%i_first <= tl_south%i_index .AND. &
@@ -1275,6 +1424,6 @@
             ENDIF
 
-            td_bdy(jp_west )%t_seg(1) = tl_west
-            td_bdy(jp_south)%t_seg(1) = tl_south
+            td_bdy(jp_west )%t_seg(1) = seg__copy(tl_west)
+            td_bdy(jp_south)%t_seg(1) = seg__copy(tl_south)
          ELSE
 
@@ -1293,6 +1442,11 @@
       ENDIF
 
+      ! clean
+      CALL seg__clean(tl_north)
+      CALL seg__clean(tl_south)
+      CALL seg__clean(tl_east )
+      CALL seg__clean(tl_west )
+
    END SUBROUTINE boundary_check_corner 
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This subroutine check boundary.
@@ -1303,10 +1457,9 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[inout] td_bdy : boundary structure 
-   !> @param[in] td_var : variable structure 
-   !------------------------------------------------------------------- 
-   !> @code 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout] td_bdy boundary structure 
+   !> @param[in] td_var    variable structure 
+   !------------------------------------------------------------------- 
    SUBROUTINE boundary_check(td_bdy, td_var) 
       IMPLICIT NONE 
@@ -1328,8 +1481,8 @@
       il_max(jp_west )=td_var%t_dim(2)%i_len
       
-      il_maxindex(jp_north)=td_var%t_dim(2)%i_len-ig_ghost
-      il_maxindex(jp_south)=td_var%t_dim(2)%i_len-ig_ghost
-      il_maxindex(jp_east )=td_var%t_dim(1)%i_len-ig_ghost
-      il_maxindex(jp_west )=td_var%t_dim(1)%i_len-ig_ghost
+      il_maxindex(jp_north)=td_var%t_dim(2)%i_len-ip_ghost
+      il_maxindex(jp_south)=td_var%t_dim(2)%i_len-ip_ghost
+      il_maxindex(jp_east )=td_var%t_dim(1)%i_len-ip_ghost
+      il_maxindex(jp_west )=td_var%t_dim(1)%i_len-ip_ghost
 
       DO jk=1,ip_ncard
@@ -1366,127 +1519,4 @@
 
    END SUBROUTINE boundary_check
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine clean interpolated boundary in variable structure.
-   !
-   !> @detail
-   !> interpolation could create more point than needed for boundary (depending
-   !> on refinement factor). This subroutine keep only useful point on variable
-   !> 
-   !> @note we use width define in first segment, cause every segment of a
-   !> boundary should have the same width 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable strucutre
-   !> @param[in   ] td_bdy : boundary strucutre
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE boundary_clean_interp( td_var, td_bdy )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TVAR), INTENT(INOUT) :: td_var
-      TYPE(TBDY), INTENT(IN   ) :: td_bdy
-
-      ! local variable
-      TYPE(TVAR)  :: tl_var
-
-      INTEGER(i4) :: il_imin
-      INTEGER(i4) :: il_imax
-      INTEGER(i4) :: il_jmin
-      INTEGER(i4) :: il_jmax
-
-      ! loop indices
-      !----------------------------------------------------------------
-
-      ! copy input variable
-      tl_var=td_var
-
-      DEALLOCATE(td_var%d_value)
-
-      SELECT CASE(TRIM(td_bdy%c_card))
-      CASE('north')
-
-         il_imin=1
-         il_imax=tl_var%t_dim(1)%i_len
-         SELECT CASE(td_var%c_point)
-         CASE('V','F')
-            il_jmin=td_bdy%t_seg(1)%i_width+1
-            il_jmax=2
-         CASE DEFAULT ! 'T','U'
-            il_jmin=td_bdy%t_seg(1)%i_width
-            il_jmax=1
-         END SELECT
-
-         ! use width as dimension length
-         td_var%t_dim(2)%i_len=td_bdy%t_seg(1)%i_width
-
-      CASE('south')
-
-         il_imin=1
-         il_imax=tl_var%t_dim(1)%i_len
-
-         il_jmin=1
-         il_jmax=td_bdy%t_seg(1)%i_width
-         
-         ! use width as dimension length
-         td_var%t_dim(2)%i_len=td_bdy%t_seg(1)%i_width
-
-      CASE('east')
-
-         SELECT CASE(td_var%c_point)
-         CASE('U','F')
-            il_imin=td_bdy%t_seg(1)%i_width+1
-            il_imax=2
-         CASE DEFAULT ! 'T','V'
-            il_imin=td_bdy%t_seg(1)%i_width
-            il_imax=1
-         END SELECT
-
-         il_jmin=1
-         il_jmax=tl_var%t_dim(2)%i_len
-
-         ! use width as dimension length
-         td_var%t_dim(1)%i_len=td_bdy%t_seg(1)%i_width
-
-      CASE('west')
-
-         il_imin=1
-         il_imax=td_bdy%t_seg(1)%i_width
-
-         il_jmin=1
-         il_jmax=tl_var%t_dim(2)%i_len
-
-         ! use width as dimension length
-         td_var%t_dim(1)%i_len=td_bdy%t_seg(1)%i_width
-
-      END SELECT
-
-
-      ALLOCATE( td_var%d_value(td_var%t_dim(1)%i_len, &
-      &                        td_var%t_dim(2)%i_len, &
-      &                        td_var%t_dim(3)%i_len, &
-      &                        td_var%t_dim(4)%i_len) )
-
-      IF( il_imin > il_imax )THEN
-         il_imin=tl_var%t_dim(1)%i_len-il_imin+1
-         il_imax=tl_var%t_dim(1)%i_len-il_imax+1
-      ENDIF
-
-      IF( il_jmin > il_jmax )THEN
-         il_jmin=tl_var%t_dim(2)%i_len-il_jmin+1
-         il_jmax=tl_var%t_dim(2)%i_len-il_jmax+1
-      ENDIF      
-
-      td_var%d_value(:,:,:,:)=tl_var%d_value( il_imin:il_imax, &
-      &                                       il_jmin:il_jmax, &
-      &                                       :,: )
-
-      CALL var_clean(tl_var)
-
-
-   END SUBROUTINE boundary_clean_interp
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine swap array for east and north boundary.
@@ -1495,10 +1525,9 @@
    !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !
-   !> @param[inout] td_var : variable strucutre
-   !> @param[in   ] td_bdy : boundary strucutre
+   !> @param[inout] td_var variable strucutre
+   !> @param[in   ] td_bdy boundary strucutre
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE boundary_swap( td_var, td_bdy )
       IMPLICIT NONE
@@ -1516,5 +1545,5 @@
 
       IF( .NOT. ASSOCIATED(td_var%d_value) )THEN
-         CALL logger_error("BOUNDARY SWAP: no table of value "//&
+         CALL logger_error("BOUNDARY SWAP: no array of value "//&
          &  "associted to variable "//TRIM(td_var%c_name) )
       ELSE      
@@ -1555,16 +1584,12 @@
       ENDIF
    END SUBROUTINE boundary_swap
-   !> @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This subroutine print information about one boundary 
-   ! 
-   !> @details 
+   !------------------------------------------------------------------- 
+   !> @brief This subroutine print information about one boundary. 
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[in] td_bdy : boundary structure 
-   !------------------------------------------------------------------- 
-   !> @code 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[in] td_bdy boundary structure 
+   !------------------------------------------------------------------- 
    SUBROUTINE boundary__print_unit( td_bdy ) 
       IMPLICIT NONE 
@@ -1588,17 +1613,15 @@
  
    END SUBROUTINE boundary__print_unit
-   !> @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This subroutine print information about a table of boundary 
+   !------------------------------------------------------------------- 
+   !> @brief This subroutine print information about a array of boundary 
    ! 
    !> @details 
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[in] td_bdy : boundary structure 
-   !------------------------------------------------------------------- 
-   !> @code 
-   SUBROUTINE boundary__print_tab( td_bdy ) 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[in] td_bdy boundary structure 
+   !------------------------------------------------------------------- 
+   SUBROUTINE boundary__print_arr( td_bdy ) 
       IMPLICIT NONE 
       ! Argument
@@ -1613,27 +1636,30 @@
       ENDDO
  
-   END SUBROUTINE boundary__print_tab
-   !> @endcode
+   END SUBROUTINE boundary__print_arr
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine copy segment structure in another segment
-   !> structure
-   !> @details 
+   !> This subroutine copy segment structure in another one.
    !>
+   !> @warning do not use on the output of a function who create or read a
+   !> structure (ex: tl_seg=seg__copy(seg__init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
    !
-   !> @param[out] td_seg1  : segment structure
-   !> @param[in] td_seg2  : segment structure
+   !> @param[in] td_seg   segment structure
+   !> @return copy of input segment structure
    !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE seg__copy( td_seg1, td_seg2 )
+   FUNCTION seg__copy_unit( td_seg )
       IMPLICIT NONE
       ! Argument
-      TYPE(TSEG), INTENT(OUT) :: td_seg1
-      TYPE(TSEG), INTENT(IN)  :: td_seg2
+      TYPE(TSEG), INTENT(IN)  :: td_seg
+      ! function
+      TYPE(TSEG) :: seg__copy_unit
 
       ! local variable
@@ -1642,11 +1668,46 @@
 
       ! copy segment index, width, ..
-      td_seg1%i_index    = td_seg2%i_index
-      td_seg1%i_width    = td_seg2%i_width
-      td_seg1%i_first    = td_seg2%i_first
-      td_seg1%i_last     = td_seg2%i_last 
-
-   END SUBROUTINE seg__copy
-   !> @endcode
+      seg__copy_unit%i_index    = td_seg%i_index
+      seg__copy_unit%i_width    = td_seg%i_width
+      seg__copy_unit%i_first    = td_seg%i_first
+      seg__copy_unit%i_last     = td_seg%i_last 
+
+   END FUNCTION seg__copy_unit
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine copy segment structure in another one.
+   !>
+   !> @warning do not use on the output of a function who create or read a
+   !> structure (ex: tl_seg=seg__copy(seg__init()) is forbidden).
+   !> This will create memory leaks.   
+   !> @warning to avoid infinite loop, do not use any function inside 
+   !> this subroutine
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
+   !
+   !> @param[in] td_seg   segment structure
+   !> @return copy of input array of segment structure
+   !-------------------------------------------------------------------
+   FUNCTION seg__copy_arr( td_seg )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TSEG), DIMENSION(:), INTENT(IN)  :: td_seg
+      ! function
+      TYPE(TSEG), DIMENSION(SIZE(td_seg(:))) :: seg__copy_arr
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      DO ji=1,SIZE(td_seg(:))
+         seg__copy_arr(ji)=seg__copy(td_seg(ji))
+      ENDDO
+
+   END FUNCTION seg__copy_arr
    !------------------------------------------------------------------- 
    !> @brief This function  initialise segment structure.
@@ -1657,13 +1718,12 @@
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[in] id_index : orthogonal index
-   !> @param[in] id_width : width of the segment 
-   !> @param[in] id_first : first indices 
-   !> @param[in] id_last  : last  indices
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[in] id_index  orthogonal index
+   !> @param[in] id_width  width of the segment 
+   !> @param[in] id_first  first indices 
+   !> @param[in] id_last   last  indices
    !> @return segment structure
    !------------------------------------------------------------------- 
-   !> @code 
    FUNCTION seg__init( id_index, id_width, id_first, id_last ) 
       IMPLICIT NONE 
@@ -1689,17 +1749,13 @@
 
    END FUNCTION seg__init 
-   !> @endcode
    !------------------------------------------------------------------- 
    !> @brief This subroutine clean segment structure. 
    ! 
-   !> @details 
-   ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
-   !> @param[inout] td_seg : segment structure
-   !------------------------------------------------------------------- 
-   !> @code 
-   SUBROUTINE seg__clean(td_seg) 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout] td_seg segment structure
+   !------------------------------------------------------------------- 
+   SUBROUTINE seg__clean_unit(td_seg) 
       IMPLICIT NONE 
       ! Argument       
@@ -1710,48 +1766,28 @@
       !---------------------------------------------------------------- 
 
-      td_seg=tl_seg
+      td_seg=seg__copy(tl_seg)
  
-   END SUBROUTINE seg__clean 
-   !> @endcode
-!   !------------------------------------------------------------------- 
-!   !> @brief This function  
-!   ! 
-!   !> @details 
-!   ! 
-!   !> @author J.Paul 
-!   !> - Nov, 2013- Initial Version 
-!   ! 
-!   !> @param[in]  
-!   !------------------------------------------------------------------- 
-!   !> @code 
-!   FUNCTION boundary_() 
-!      IMPLICIT NONE 
-!      ! Argument       
-!      ! function 
-!      ! local variable 
-!      ! loop indices 
-!      !---------------------------------------------------------------- 
-! 
-!   END FUNCTION boundary_ 
-!   !> @endcode 
-!   !------------------------------------------------------------------- 
-!   !> @brief This subroutine  
-!   ! 
-!   !> @details 
-!   ! 
-!   !> @author J.Paul 
-!   !> - Nov, 2013- Initial Version 
-!   ! 
-!   !> @param[in]  
-!   !------------------------------------------------------------------- 
-!   !> @code 
-!   SUBROUTINE boundary_() 
-!      IMPLICIT NONE 
-!      ! Argument       
-!      ! local variable 
-!      ! loop indices 
-!      !---------------------------------------------------------------- 
-! 
-!   END SUBROUTINE boundary_ 
-!   !> @endcode
+   END SUBROUTINE seg__clean_unit
+   !------------------------------------------------------------------- 
+   !> @brief This subroutine clean segment structure. 
+   ! 
+   !> @author J.Paul 
+   !> @date November, 2013 - Initial Version 
+   ! 
+   !> @param[inout] td_seg array of segment structure
+   !------------------------------------------------------------------- 
+   SUBROUTINE seg__clean_arr(td_seg) 
+      IMPLICIT NONE 
+      ! Argument       
+      TYPE(TSEG), DIMENSION(:), INTENT(INOUT) :: td_seg
+      ! local variable 
+      ! loop indices 
+      INTEGER(i4) :: ji
+      !---------------------------------------------------------------- 
+
+      DO ji=SIZE(td_seg(:)),1,-1
+         CALL seg__clean(td_seg(ji))
+      ENDDO
+ 
+   END SUBROUTINE seg__clean_arr 
 END MODULE boundary
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_bathy.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_bathy.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_bathy.f90	(revision 5075)
@@ -3,29 +3,125 @@
 !----------------------------------------------------------------------
 !
-!
 ! PROGRAM: create_bathy
 !
 ! DESCRIPTION:
+!> @file
 !> @brief 
-!> This program create bathymetry file.
+!> This program create fine grid bathymetry file.
 !>
 !> @details
-!> Bathymetry could be extracted from fine grid Bathymetry file, or interpolated
-!> from coarse grid Bathymetry file.
-!>
-!> @author
-!> J.Paul
+!> @section sec1 method
+!> Bathymetry could be extracted from fine grid Bathymetry file, interpolated
+!> from coarse grid Bathymetry file, or manually written.
+!>
+!> @section sec2 how to
+!>    to create fine grid bathymetry file:<br/>
+!> @code{.sh}
+!>    ./SIREN/bin/create_bathy create_bathy.nam
+!> @endcode
+!>    
+!>    create_bathy.nam comprise 7 namelists:<br/>
+!>       - logger namelist (namlog)
+!>       - config namelist (namcfg)
+!>       - coarse grid namelist (namcrs)
+!>       - fine grid namelist (namfin)
+!>       - variable namelist (namvar)
+!>       - nesting namelist (namnst)
+!>       - output namelist (namout)
+!>    
+!>    @note 
+!>       All namelists have to be in file create_bathy.nam, however variables of
+!>       those namelists are all optional.
+!>
+!>    * _logger namelist (namlog)_:<br/>
+!>       - cn_logfile   : log filename
+!>       - cn_verbosity : verbosity ('trace','debug','info',
+!> 'warning','error','fatal')
+!>       - in_maxerror  : maximum number of error allowed
+!>
+!>    * _config namelist (namcfg)_:<br/>
+!>       - cn_varcfg : variable configuration file 
+!> (see ./SIREN/cfg/variable.cfg)
+!>
+!>    * _coarse grid namelist (namcrs)_:<br/>
+!>       - cn_coord0 : coordinate file
+!>       - in_perio0 : NEMO periodicity index (see Model Boundary Condition in
+!> [NEMO documentation](http://www.nemo-ocean.eu/About-NEMO/Reference-manuals))
+!>
+!>    * _fine grid namelist (namfin)_:<br/>
+!>       - cn_coord1 : coordinate file
+!>       - in_perio1 : periodicity index
+!>       - ln_fillclosed : fill closed sea or not
+!>
+!>    * _variable namelist (namvar)_:<br/>
+!>       - cn_varinfo : list of variable and extra information about request(s) 
+!>       to be used.<br/>
+!>          each elements of *cn_varinfo* is a string character.<br/>
+!>          it is composed of the variable name follow by ':', 
+!>          then request(s) to be used on this variable.<br/> 
+!>          request could be:
+!>             - interpolation method
+!>             - extrapolation method
+!>             - filter method
+!>             - > minimum value
+!>             - < maximum value
+!>
+!>                requests must be separated by ';'.<br/>
+!>                order of requests does not matter.<br/>
+!>
+!>          informations about available method could be find in @ref interp,
+!>          @ref extrap and @ref filter modules.<br/>
+!>          Example: 'Bathymetry: 2*hamming(2,3); > 0'
+!>          @note 
+!>             If you do not specify a method which is required, 
+!>             default one is apply.
+!>          @warning 
+!>             variable name must be __Bathymetry__ here.
+!>       - cn_varfile : list of variable, and corresponding file.<br/> 
+!>          *cn_varfile* is the path and filename of the file where find
+!>          variable.
+!>          @note 
+!>             *cn_varfile* could be a matrix of value, if you want to filled
+!>             manually variable value.<br/>
+!>             the variable array of value is split into equal subdomain.<br/>
+!>             Each subdomain is filled with the corresponding value 
+!>             of the matrix.<br/>          
+!>             separators used to defined matrix are:
+!>                - ',' for line
+!>                - '/' for row
+!>                - '\' for level<br/>
+!>                Example:<br/>
+!>                   3,2,3/1,4,5  =>  @f$ \left( \begin{array}{ccc}
+!>                                         3 & 2 & 3 \\
+!>                                         1 & 4 & 5 \end{array} \right) @f$
+!>
+!>          Examples: 
+!>             - 'Bathymetry:gridT.nc'
+!>             - 'Bathymetry:5000,5000,5000/5000,3000,5000/5000,5000,5000'
+!>
+!>          \image html  bathy_40.png 
+!>          \image latex bathy_30.png
+!>
+!>    * _nesting namelist (namnst)_:<br/>
+!>       - in_rhoi  : refinement factor in i-direction
+!>       - in_rhoj  : refinement factor in j-direction
+!>       @note 
+!>          coarse grid indices will be deduced from fine grid
+!>          coordinate file.
+!>
+!>    * _output namelist (namout)_:<br/>
+!>       - cn_fileout : output bathymetry file
+!>
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
+!> @date Sepember, 2014 
+!> - add header for user
+!> - Bug fix, compute offset depending of grid point
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!>
-!> @todo
-!> - add attributes indices and refinement in output file
 !----------------------------------------------------------------------
-!> @code
 PROGRAM create_bathy
 
-!   USE netcdf                          ! nf90 library
    USE global                          ! global variable
    USE kind                            ! F90 kind parameter
@@ -39,5 +135,4 @@
    USE multi                           ! multi file manager
    USE iom                             ! I/O manager
-   USE dom                             ! domain manager
    USE grid                            ! grid manager
    USE extrap                          ! extrapolation manager
@@ -45,5 +140,7 @@
    USE filter                          ! filter manager
    USE mpp                             ! MPP manager
+   USE dom                             ! domain manager
    USE iom_mpp                         ! MPP I/O manager
+   USE iom_dom                         ! DOM I/O manager
 
    IMPLICIT NONE
@@ -57,19 +154,20 @@
    INTEGER(i4)                                        :: il_status
    INTEGER(i4)                                        :: il_fileid
+   INTEGER(i4)                                        :: il_varid
    INTEGER(i4)                                        :: il_attid
-   INTEGER(i4)                                        :: il_imin
-   INTEGER(i4)                                        :: il_imax
-   INTEGER(i4)                                        :: il_jmin
-   INTEGER(i4)                                        :: il_jmax
+   INTEGER(i4)                                        :: il_imin0
+   INTEGER(i4)                                        :: il_imax0
+   INTEGER(i4)                                        :: il_jmin0
+   INTEGER(i4)                                        :: il_jmax0
    INTEGER(i4)      , DIMENSION(ip_maxdim)            :: il_rho
    INTEGER(i4)      , DIMENSION(2,2)                  :: il_offset
-   INTEGER(i4)      , DIMENSION(2,2,2)                :: il_ind
+   INTEGER(i4)      , DIMENSION(2,2)                  :: il_ind
    INTEGER(i4)      , DIMENSION(:,:)    , ALLOCATABLE :: il_mask
 
    LOGICAL                                            :: ll_exist
 
-   TYPE(TFILE)                                        :: tl_coord0
-   TYPE(TFILE)                                        :: tl_coord1
-   TYPE(TFILE)                                        :: tl_file
+   TYPE(TMPP)                                         :: tl_coord0
+   TYPE(TMPP)                                         :: tl_coord1
+   TYPE(TMPP)                                         :: tl_mpp
    TYPE(TFILE)                                        :: tl_fileout
 
@@ -88,4 +186,6 @@
    TYPE(TMULTI)                                       :: tl_multi
 
+   REAL(dp)                                           :: dl_minbat
+
    ! loop indices
    INTEGER(i4) :: ji
@@ -94,35 +194,40 @@
 
    ! namelist variable
+   ! namlog
    CHARACTER(LEN=lc) :: cn_logfile = 'create_bathy.log' 
    CHARACTER(LEN=lc) :: cn_verbosity = 'warning' 
-
+   INTEGER(i4)       :: in_maxerror = 5
+
+   ! namcfg
    CHARACTER(LEN=lc) :: cn_varcfg = 'variable.cfg' 
 
+   ! namcrs
    CHARACTER(LEN=lc) :: cn_coord0 = '' 
    INTEGER(i4)       :: in_perio0 = -1
 
+   ! namfin
    CHARACTER(LEN=lc) :: cn_coord1 = ''
    INTEGER(i4)       :: in_perio1 = -1
    LOGICAL           :: ln_fillclosed = .TRUE.
 
-   CHARACTER(LEN=lc), DIMENSION(ig_maxvar) :: cn_varinfo = ''
-   CHARACTER(LEN=lc), DIMENSION(ig_maxvar) :: cn_varfile = ''
-
-   INTEGER(i4)       :: in_imin0 = 0
-   INTEGER(i4)       :: in_imax0 = 0
-   INTEGER(i4)       :: in_jmin0 = 0
-   INTEGER(i4)       :: in_jmax0 = 0
+   ! namvar
+   CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varinfo = ''
+   CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varfile = ''
+
+   ! namnst
    INTEGER(i4)       :: in_rhoi  = 1
    INTEGER(i4)       :: in_rhoj  = 1
 
+   ! namout
    CHARACTER(LEN=lc) :: cn_fileout = 'bathy_fine.nc' 
    !-------------------------------------------------------------------
 
-   NAMELIST /namlog/ &  !< logger namelist
-   &  cn_logfile,    &  !< log file
-   &  cn_verbosity      !< log verbosity
-
-   NAMELIST /namcfg/ &  !< configuration namelist
-   &  cn_varcfg         !< variable configuration file
+   NAMELIST /namlog/ &   !< logger namelist
+   &  cn_logfile,    &   !< log file
+   &  cn_verbosity,  &   !< log verbosity
+   &  in_maxerror        !< logger maximum error
+
+   NAMELIST /namcfg/ &   !< configuration namelist
+   &  cn_varcfg          !< variable configuration file
 
    NAMELIST /namcrs/ &   !< coarse grid namelist
@@ -135,22 +240,18 @@
    &  ln_fillclosed      !< fill closed sea
  
-   NAMELIST /namvar/ &  !< variable namelist
-   &  cn_varinfo, &     !< list of variable and interpolation method to be used. (ex: 'votemper:linear','vosaline:cubic' )
-   &  cn_varfile        !< list of variable file
+   NAMELIST /namvar/ &   !< variable namelist
+   &  cn_varinfo, &      !< list of variable and interpolation method to be used. (ex: 'votemper:linear','vosaline:cubic' )
+   &  cn_varfile         !< list of variable file
    
-   NAMELIST /namnst/ &  !< nesting namelist
-   &  in_imin0,   &     !< i-direction lower left  point indice 
-   &  in_imax0,   &     !< i-direction upper right point indice
-   &  in_jmin0,   &     !< j-direction lower left  point indice
-   &  in_jmax0,   &     !< j-direction upper right point indice
-   &  in_rhoi,    &     !< refinement factor in i-direction
-   &  in_rhoj           !< refinement factor in j-direction
-
-   NAMELIST /namout/ &  !< output namlist
-   &  cn_fileout       !< fine grid bathymetry file
+   NAMELIST /namnst/ &   !< nesting namelist
+   &  in_rhoi,    &      !< refinement factor in i-direction
+   &  in_rhoj            !< refinement factor in j-direction
+
+   NAMELIST /namout/ &   !< output namlist
+   &  cn_fileout         !< fine grid bathymetry file
    !-------------------------------------------------------------------
 
-   !1- namelist
-   !1-1 get namelist
+   ! namelist
+   ! get namelist
    il_narg=COMMAND_ARGUMENT_COUNT() !f03 intrinsec
    IF( il_narg/=1 )THEN
@@ -160,9 +261,9 @@
       CALL GET_COMMAND_ARGUMENT(1,cl_namelist) !f03 intrinsec
    ENDIF
-   
-   !1-2 read namelist
+ 
+   ! read namelist
    INQUIRE(FILE=TRIM(cl_namelist), EXIST=ll_exist)
    IF( ll_exist )THEN
-      
+ 
       il_fileid=fct_getunit()
 
@@ -180,10 +281,10 @@
 
       READ( il_fileid, NML = namlog )
-      !1-2-1 define log file
-      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity))
+      ! define log file
+      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity),in_maxerror)
       CALL logger_header()
 
       READ( il_fileid, NML = namcfg )
-      !1-2-2 get variable extra information
+      ! get variable extra information
       CALL var_def_extra(TRIM(cn_varcfg))
 
@@ -191,7 +292,7 @@
       READ( il_fileid, NML = namfin )
       READ( il_fileid, NML = namvar )
-      !1-2-3 add user change in extra information
-      CALL var_chg_extra(cn_varinfo)
-      !1-2-4 match variable with file
+      ! add user change in extra information
+      CALL var_chg_extra( cn_varinfo )
+      ! match variable with file
       tl_multi=multi_init(cn_varfile)
       
@@ -211,8 +312,10 @@
    ENDIF
 
-   !2- open files
+   CALL multi_print(tl_multi)
+
+   ! open files
    IF( cn_coord0 /= '' )THEN
-      tl_coord0=file_init(TRIM(cn_coord0),id_perio=in_perio0)
-      CALL iom_open(tl_coord0)
+      tl_coord0=mpp_init( file_init(TRIM(cn_coord0)), id_perio=in_perio0)
+      CALL grid_get_info(tl_coord0)
    ELSE
       CALL logger_fatal("CREATE BATHY: no coarse grid coordinate found. "//&
@@ -221,6 +324,6 @@
 
    IF( TRIM(cn_coord1) /= '' )THEN
-      tl_coord1=file_init(TRIM(cn_coord1),id_perio=in_perio1)
-      CALL iom_open(tl_coord1)
+      tl_coord1=mpp_init( file_init(TRIM(cn_coord1)),id_perio=in_perio1)
+      CALL grid_get_info(tl_coord1)
    ELSE
       CALL logger_fatal("CREATE BATHY: no fine grid coordinate found. "//&
@@ -228,6 +331,6 @@
    ENDIF
 
-   !3- check
-   !3-1 check output file do not already exist
+   ! check
+   ! check output file do not already exist
    INQUIRE(FILE=TRIM(cn_fileout), EXIST=ll_exist)
    IF( ll_exist )THEN
@@ -236,6 +339,6 @@
    ENDIF
 
-   !3-2 check namelist
-   !3-2-1 check refinement factor
+   ! check namelist
+   ! check refinement factor
    il_rho(:)=1
    IF( in_rhoi < 1 .OR. in_rhoj < 1 )THEN
@@ -247,116 +350,132 @@
    ENDIF
 
-   !3-2-2 check domain indices
-   IF( in_imin0 < 1 .OR. in_imax0 < 1 .OR. &
-   &   in_jmin0 < 1 .OR. in_jmax0 < 1)THEN
-      ! compute coarse grid indices around fine grid
-      IF( cn_coord0 /= '' )THEN
-         il_ind(:,:,:)=grid_get_coarse_index( tl_coord0, tl_coord1, &
-         &                                    id_rho=il_rho(:) )
-      ENDIF
-
-      il_imin=il_ind(1,1,1) ; il_imax=il_ind(1,2,1)
-      il_jmin=il_ind(2,1,1) ; il_jmax=il_ind(2,2,1)
-
-      il_offset(:,:)=il_ind(:,:,2)
-   ELSE
-      il_imin=in_imin0 ; il_imax=in_imax0
-      il_jmin=in_jmin0 ; il_jmax=in_jmax0
-
-      il_offset(jp_I,:)=FLOOR(REAL(il_rho(jp_I)-1,dp)*0.5)
-      il_offset(jp_J,:)=FLOOR(REAL(il_rho(jp_J)-1,dp)*0.5)
-   ENDIF
-
-   !3-2-3 check domain validity
-   IF( cn_coord0 /= '' )THEN
-      CALL grid_check_dom(tl_coord0, il_imin, il_imax, il_jmin, il_jmax)
-   ENDIF
-
-   !3-2-4 check coincidence between coarse and fine grid
-   IF( cn_coord0 /= '' )THEN
-      CALL grid_check_coincidence( tl_coord0, tl_coord1, &
-      &                            il_imin, il_imax, &
-      &                            il_jmin, il_jmax, &
-      &                            il_rho(:) )
-   ENDIF
-
-   IF( .NOT. ASSOCIATED(tl_multi%t_file) )THEN
-      CALL logger_error("CREATE BATHY: no file to work on. "//&
+   ! check domain indices
+   ! compute coarse grid indices around fine grid
+   il_ind(:,:)=grid_get_coarse_index( tl_coord0, tl_coord1, &
+   &                                  id_rho=il_rho(:) )
+
+   il_imin0=il_ind(jp_I,1) ; il_imax0=il_ind(jp_I,2)
+   il_jmin0=il_ind(jp_J,1) ; il_jmax0=il_ind(jp_J,2)
+
+   ! check domain validity
+   CALL grid_check_dom(tl_coord0, il_imin0, il_imax0, il_jmin0, il_jmax0)
+
+   ! check coincidence between coarse and fine grid
+   CALL grid_check_coincidence( tl_coord0, tl_coord1, &
+   &                            il_imin0, il_imax0, &
+   &                            il_jmin0, il_jmax0, &
+   &                            il_rho(:) )
+
+   IF( .NOT. ASSOCIATED(tl_multi%t_mpp) )THEN
+      CALL logger_error("CREATE BATHY: no mpp file to work on. "//&
       &                 "check cn_varfile in namelist.")
    ELSE
+
       ALLOCATE( tl_var( tl_multi%i_nvar ) )
       jk=0
-      DO ji=1,tl_multi%i_nfile
-         WRITE(cl_data,'(a,i2.2)') 'data_',jk+1
-         IF( .NOT. ASSOCIATED(tl_multi%t_file(ji)%t_var) )THEN
-            CALL logger_error("CREATE BATHY: no variable to work on for "//&
-            &                 "file"//TRIM(tl_multi%t_file(ji)%c_name)//&
+      DO ji=1,tl_multi%i_nmpp
+      
+         WRITE(cl_data,'(a,i2.2)') 'data-',jk+1
+         IF( .NOT. ASSOCIATED(tl_multi%t_mpp(ji)%t_proc(1)%t_var) )THEN
+
+            CALL logger_fatal("CREATE BATHY: no variable to work on for "//&
+            &                 "mpp file"//TRIM(tl_multi%t_mpp(ji)%c_name)//&
             &                 ". check cn_varfile in namelist.")
-         ELSEIF( TRIM(tl_multi%t_file(ji)%c_name) == TRIM(cl_data) )THEN
-            DO jj=1,tl_multi%t_file(ji)%i_nvar
+
+         ELSEIF( TRIM(tl_multi%t_mpp(ji)%c_name) == TRIM(cl_data) )THEN
+
+            !- use input matrix to initialise variable
+            DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
                jk=jk+1
-               tl_tmp=tl_multi%t_file(ji)%t_var(jj)
-               !- use input matrix to initialise variable
+               tl_tmp=var_copy(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj))
+            
                tl_var(jk)=create_bathy_matrix(tl_tmp, tl_coord1)
             ENDDO
+            ! clean
+            CALL var_clean(tl_tmp)
+
          ELSE
-            ! open file
-            tl_file=file_init(TRIM(tl_multi%t_file(ji)%c_name))
-            CALL iom_open(tl_file)
+
+            tl_mpp=mpp_init( file_init(TRIM(tl_multi%t_mpp(ji)%c_name)) )
+            CALL grid_get_info(tl_mpp)
+
+            ! open mpp file
+            CALL iom_mpp_open(tl_mpp)
 
             ! get or check depth value
-            IF( tl_file%i_depthid /= 0 )THEN
+            IF( tl_multi%t_mpp(ji)%t_proc(1)%i_depthid /= 0 )THEN
+               il_varid=tl_multi%t_mpp(ji)%t_proc(1)%i_depthid
                IF( ASSOCIATED(tl_depth%d_value) )THEN
+                  tl_tmp=iom_mpp_read_var(tl_mpp,il_varid)
                   IF( ANY( tl_depth%d_value(:,:,:,:) /= &
                   &        tl_tmp%d_value(:,:,:,:) ) )THEN
                      CALL logger_fatal("CREATE BATHY: depth value from "//&
-                     &  TRIM(tl_multi%t_file(ji)%c_name)//" not conform "//&
+                     &  TRIM(tl_multi%t_mpp(ji)%c_name)//" not conform "//&
                      &  " to those from former file(s).")
                   ENDIF
+                  CALL var_clean(tl_tmp)
                ELSE
-                  tl_depth=iom_read_var(tl_file,tl_file%i_depthid)
+                  tl_depth=iom_mpp_read_var(tl_mpp,il_varid)
                ENDIF
             ENDIF
 
             ! get or check time value
-            IF( tl_file%i_timeid /= 0 )THEN
+            IF( tl_multi%t_mpp(ji)%t_proc(1)%i_timeid /= 0 )THEN
+               il_varid=tl_multi%t_mpp(ji)%t_proc(1)%i_timeid
                IF( ASSOCIATED(tl_time%d_value) )THEN
+                  tl_tmp=iom_mpp_read_var(tl_mpp,il_varid)
                   IF( ANY( tl_time%d_value(:,:,:,:) /= &
                   &        tl_tmp%d_value(:,:,:,:) ) )THEN
                      CALL logger_fatal("CREATE BATHY: time value from "//&
-                     &  TRIM(tl_multi%t_file(ji)%c_name)//" not conform "//&
+                     &  TRIM(tl_multi%t_mpp(ji)%c_name)//" not conform "//&
                      &  " to those from former file(s).")
                   ENDIF
+                  CALL var_clean(tl_tmp)
                ELSE
-                  tl_time=iom_read_var(tl_file,tl_file%i_timeid)
+                  tl_time=iom_mpp_read_var(tl_mpp,il_varid)
                ENDIF
             ENDIF
 
-            IF( ANY( tl_file%t_dim(1:2)%i_len /= &
-            &      tl_coord0%t_dim(1:2)%i_len) )THEN
-               DO jj=1,tl_multi%t_file(ji)%i_nvar
+            ! close mpp file
+            CALL iom_mpp_close(tl_mpp)
+
+            IF( ANY( tl_mpp%t_dim(1:2)%i_len /= &
+            &        tl_coord0%t_dim(1:2)%i_len) )THEN
+               !- extract bathymetry from fine grid bathymetry 
+               DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
                   jk=jk+1
-                  tl_tmp=tl_multi%t_file(ji)%t_var(jj)
-                  !- extract bathymetry from fine grid bathymetry 
-                  tl_var(jk)=create_bathy_extract( tl_tmp, tl_file, &
+                  tl_tmp=var_copy(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj))
+               
+                  tl_var(jk)=create_bathy_extract( tl_tmp, tl_mpp, &
                   &                                tl_coord1 )
                ENDDO
+               ! clean
+               CALL var_clean(tl_tmp)
             ELSE
-               DO jj=1,tl_multi%t_file(ji)%i_nvar
+               !- get bathymetry from coarse grid bathymetry 
+               DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
                   jk=jk+1
-                  tl_tmp=tl_multi%t_file(ji)%t_var(jj)
-                  !- get bathymetry from coarse grid bathymetry 
-                  tl_var(jk)=create_bathy_get_var( tl_tmp, tl_file,  &
-                  &                                il_imin, il_jmin, &
-                  &                                il_imax, il_jmax, &
-                  &                                il_offset(:,:),   &
+                  tl_tmp=var_copy(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj))
+
+                  il_offset(:,:)= grid_get_fine_offset(tl_coord0,    &
+                  &                                    il_imin0, il_jmin0, &
+                  &                                    il_imax0, il_jmax0, &
+                  &                                    tl_coord1,          &
+                  &                                    il_rho(:),          &
+                  &                                    TRIM(tl_tmp%c_point) )
+
+                  tl_var(jk)=create_bathy_get_var( tl_tmp, tl_mpp,     &
+                  &                                il_imin0, il_jmin0, &
+                  &                                il_imax0, il_jmax0, &
+                  &                                il_offset(:,:),  &
                   &                                il_rho(:) )
                ENDDO
+               ! clean
+               CALL var_clean(tl_tmp)
             ENDIF
 
-            ! close file
-            CALL iom_close(tl_file)
             ! clean structure
-            CALL file_clean(tl_file)
+            CALL mpp_clean(tl_mpp)
+
          ENDIF
       ENDDO
@@ -364,17 +483,16 @@
 
    DO jk=1,tl_multi%i_nvar
-         !6- forced min and max value
+         ! forced min and max value
          CALL var_limit_value(tl_var(jk))
 
-         !7- fill closed sea
-         IF( TRIM(tl_var(jk)%c_stdname) == 'bathymetry' .AND. &
-             ln_fillclosed )THEN
+         ! fill closed sea
+         IF( ln_fillclosed )THEN
             ALLOCATE( il_mask(tl_var(jk)%t_dim(1)%i_len, &
             &                 tl_var(jk)%t_dim(2)%i_len) )
 
-            !7-1 split domain in N sea subdomain
+            ! split domain in N sea subdomain
             il_mask(:,:)=grid_split_domain(tl_var(jk))
 
-            !7-2  fill smallest domain
+            !  fill smallest domain
             CALL grid_fill_small_dom( tl_var(jk), il_mask(:,:) )
 
@@ -382,19 +500,21 @@
          ENDIF
 
-         !8- filter
+         ! filter
          CALL filter_fill_value(tl_var(jk))
 
-         !9- check bathymetry
+         ! check bathymetry
+         dl_minbat=MINVAL(tl_var(jk)%d_value(:,:,:,:))
          IF( TRIM(tl_var(jk)%c_stdname) == 'bathymetry' .AND. &
-         &   MINVAL(tl_var(jk)%d_value(:,:,:,:)) <= 0._dp  )THEN
+         &   dl_minbat <= 0._dp  )THEN
+            CALL logger_debug("CREATE BATHY: min value "//TRIM(fct_str(dl_minbat)))
             CALL logger_error("CREATE BATHY: Bathymetry has value <= 0")
          ENDIF
+
    ENDDO
 
-
-   !10- create file
-   tl_fileout=file_init(TRIM(cn_fileout),id_perio=in_perio1)
-
-   !10-1 add dimension
+   ! create file
+   tl_fileout=file_init(TRIM(cn_fileout))
+
+   ! add dimension
    tl_dim(:)=var_max_dim(tl_var(:))
 
@@ -403,16 +523,22 @@
    ENDDO
 
-   !10-2 add variables
+   ! add variables
    IF( ALL( tl_dim(1:2)%l_use ) )THEN
 
+      ! open mpp files
+      CALL iom_mpp_open(tl_coord1)
+
       ! add longitude
-      tl_lon=iom_read_var(tl_coord1,'longitude')
+      tl_lon=iom_mpp_read_var(tl_coord1,'longitude')
       CALL file_add_var(tl_fileout, tl_lon)
       CALL var_clean(tl_lon)
 
       ! add latitude
-      tl_lat=iom_read_var(tl_coord1,'latitude')
+      tl_lat=iom_mpp_read_var(tl_coord1,'latitude')
       CALL file_add_var(tl_fileout, tl_lat)
       CALL var_clean(tl_lat)
+
+      ! close mpp files
+      CALL iom_mpp_close(tl_coord1)
 
    ENDIF
@@ -435,6 +561,7 @@
       CALL var_clean(tl_var(jk))
    ENDDO
-
-   !10-3 add some attribute
+   DEALLOCATE(tl_var)
+
+   ! add some attribute
    tl_att=att_init("Created_by","SIREN create_bathy")
    CALL file_add_att(tl_fileout, tl_att)
@@ -447,5 +574,5 @@
    il_attid=0
    IF( ASSOCIATED(tl_fileout%t_att) )THEN
-      il_attid=att_get_id(tl_fileout%t_att(:),'periodicity')
+      il_attid=att_get_index(tl_fileout%t_att(:),'periodicity')
    ENDIF
    IF( tl_coord1%i_perio >= 0 .AND. il_attid == 0 )THEN
@@ -454,7 +581,8 @@
    ENDIF
 
+   ! add attribute east west overlap
    il_attid=0
    IF( ASSOCIATED(tl_fileout%t_att) )THEN
-      il_attid=att_get_id(tl_fileout%t_att(:),'ew_overlap')
+      il_attid=att_get_index(tl_fileout%t_att(:),'ew_overlap')
    ENDIF
    IF( tl_coord1%i_ew >= 0 .AND. il_attid == 0 )THEN
@@ -462,21 +590,20 @@
       CALL file_add_att(tl_fileout,tl_att)
    ENDIF
-
-   !10-4 create file
+   
+   ! create file
    CALL iom_create(tl_fileout)
 
-   !10-5 write file
+   ! write file
    CALL iom_write_file(tl_fileout)
 
-   !10-6 close file
+   ! close file
    CALL iom_close(tl_fileout)
-   IF( cn_coord0 /= '' ) CALL iom_close(tl_coord0)
-
-   !11- clean
-   DEALLOCATE(tl_var)
+
+   ! clean
+   CALL att_clean(tl_att)
 
    CALL file_clean(tl_fileout)
-   CALL file_clean(tl_coord1)
-   CALL file_clean(tl_coord0)
+   CALL mpp_clean(tl_coord1)
+   CALL mpp_clean(tl_coord0)
 
    ! close log file
@@ -484,23 +611,27 @@
    CALL logger_close()
 
-!> @endcode
 CONTAINS
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This function create variable, filled with matrix value
    !> 
    !> @details 
+   !> A variable is create with the same name that the input variable, 
+   !> and with dimension of the coordinate file.<br/> 
+   !> Then the variable array of value is split into equal subdomain.
+   !> Each subdomain is filled with the corresponding value of the matrix.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !>
-   !> @param[in] 
+   !> @param[in] td_var    variable structure 
+   !> @param[in] td_coord  coordinate file structure
+   !> @return variable structure
    !-------------------------------------------------------------------
-   !> @code
    FUNCTION create_bathy_matrix(td_var, td_coord)
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(IN) :: td_var
-      TYPE(TFILE), INTENT(IN) :: td_coord
+      TYPE(TVAR), INTENT(IN) :: td_var
+      TYPE(TMPP), INTENT(IN) :: td_coord
 
       ! function
@@ -508,7 +639,5 @@
 
       ! local variable
-      INTEGER(i4)                                        :: il_ighost
-      INTEGER(i4)                                        :: il_jghost
-      INTEGER(i4)      , DIMENSION(2)                    :: il_xghost
+      INTEGER(i4)      , DIMENSION(2,2)                  :: il_xghost
       INTEGER(i4)      , DIMENSION(3)                    :: il_dim
       INTEGER(i4)      , DIMENSION(3)                    :: il_size
@@ -522,7 +651,7 @@
 
       TYPE(TVAR)                                         :: tl_lon
-      TYPE(TVAR)                                         :: tl_lat
-      TYPE(TVAR)                                         :: tl_var
       TYPE(TDIM)       , DIMENSION(ip_maxdim)            :: tl_dim
+
+      TYPE(TMPP)                                         :: tl_coord
 
       ! loop indices
@@ -532,25 +661,36 @@
       !----------------------------------------------------------------
 
-      !1- read output grid
-      tl_lon=iom_read_var(td_coord,'longitude')
-      tl_lat=iom_read_var(td_coord,'latitude')
-
-      !2- look for ghost cell
-      il_xghost(:)=grid_get_ghost( tl_lon, tl_lat )
-
-      il_ighost=il_xghost(1)*ig_ghost
-      il_jghost=il_xghost(2)*ig_ghost
-      
-      !3- write value on grid
-      !3-1 get matrix dimension
+      ! copy structure
+      tl_coord=mpp_copy(td_coord)
+
+      ! use only edge processor
+      CALL mpp_get_contour(tl_coord)
+
+      ! open useful processor
+      CALL iom_mpp_open(tl_coord)
+
+      ! read output grid
+      tl_lon=iom_mpp_read_var(tl_coord,'longitude')
+
+      ! look for ghost cell
+      il_xghost(:,:)=grid_get_ghost( tl_coord )
+
+      ! close processor
+      CALL iom_mpp_close(tl_coord)
+      ! clean
+      CALL mpp_clean(tl_coord)
+
+      ! remove ghost cell
+      CALL grid_del_ghost(tl_lon, il_xghost(:,:))
+
+      ! write value on grid
+      ! get matrix dimension
       il_dim(:)=td_var%t_dim(1:3)%i_len
-      !3-2 output dimension
-      tl_dim(:)=tl_lon%t_dim(:)
-
-      ! remove ghost cell
-      tl_dim(1)%i_len=tl_dim(1)%i_len - 2*il_xghost(1)*ig_ghost
-      tl_dim(2)%i_len=tl_dim(2)%i_len - 2*il_xghost(2)*ig_ghost
-
-      !3-3 split output domain in N subdomain depending of matrix dimension 
+      ! output dimension
+      tl_dim(:)=dim_copy(tl_lon%t_dim(:))
+      ! clean
+      CALL var_clean(tl_lon)
+
+      ! split output domain in N subdomain depending of matrix dimension 
       il_size(:) = tl_dim(1:3)%i_len / il_dim(:)
       il_rest(:) = MOD(tl_dim(1:3)%i_len, il_dim(:))
@@ -563,5 +703,4 @@
       ! add rest to last cell
       il_ishape(il_dim(1)+1)=il_ishape(il_dim(1)+1)+il_rest(1)
-      
 
       ALLOCATE( il_jshape(il_dim(2)+1) )
@@ -581,5 +720,5 @@
       il_kshape(il_dim(3)+1)=il_kshape(il_dim(3)+1)+il_rest(3)
 
-      !3-3 write ouput table of value 
+      ! write ouput array of value 
       ALLOCATE(dl_value( tl_dim(1)%i_len, &
       &                  tl_dim(2)%i_len, &
@@ -602,36 +741,36 @@
       ENDDO
 
-      !3-4 initialise variable with value
-      tl_var=var_init(TRIM(td_var%c_name),dl_value(:,:,:,:))
+      ! initialise variable with value
+      create_bathy_matrix=var_init(TRIM(td_var%c_name),dl_value(:,:,:,:))
 
       DEALLOCATE(dl_value)
 
-      !4- add ghost cell
-      CALL grid_add_ghost(tl_var,il_ighost,il_jghost)
-
-      !5- save result
-      create_bathy_matrix=tl_var
+      ! add ghost cell
+      CALL grid_add_ghost(create_bathy_matrix, il_xghost(:,:))
+
+      ! clean
+      CALL dim_clean(tl_dim(:))
 
    END FUNCTION create_bathy_matrix
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This function extract variable from file over coordinate domain and
+   !> return variable structure
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] 
+   !> @param[in] td_var    variable structure 
+   !> @param[in] td_mpp    mpp file structure
+   !> @param[in] td_coord  coordinate file structure
+   !> @return variable structure
    !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create_bathy_extract(td_var, td_file, &
+   FUNCTION create_bathy_extract(td_var, td_mpp, &
    &                             td_coord)
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(IN) :: td_var  
-      TYPE(TFILE), INTENT(IN) :: td_file
-      TYPE(TFILE), INTENT(IN) :: td_coord
+      TYPE(TVAR), INTENT(IN) :: td_var  
+      TYPE(TMPP), INTENT(IN) :: td_mpp
+      TYPE(TMPP), INTENT(IN) :: td_coord
 
       ! function
@@ -639,8 +778,5 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(2,2,2) :: il_ind
-
-      INTEGER(i4) :: il_pivot
-      INTEGER(i4) :: il_perio
+      INTEGER(i4), DIMENSION(2,2) :: il_ind
 
       INTEGER(i4) :: il_imin
@@ -648,6 +784,4 @@
       INTEGER(i4) :: il_imax
       INTEGER(i4) :: il_jmax
-
-      TYPE(TFILE) :: tl_file
 
       TYPE(TMPP)  :: tl_mpp
@@ -661,67 +795,42 @@
       !----------------------------------------------------------------
 
-      IF( td_file%i_id == 0 )THEN
-         CALL logger_error("CREATE BATHY EXTRACT: file "//&
-         &  TRIM(td_file%c_name)//" not opened ")
+      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
+         CALL logger_error("CREATE BATHY EXTRACT: no processor associated "//&
+         &  "to mpp "//TRIM(td_mpp%c_name))
       ELSE
 
          !init
-         tl_file=td_file
-
-         !1- open file
-         CALL iom_open(tl_file)
-
-         ! get periodicity
-         il_pivot=grid_get_pivot(tl_file)
-         il_perio=grid_get_perio(tl_file,il_pivot)
-
-         tl_file%i_perio=il_perio
-
-         !2- compute file grid indices around coord grid
-         il_ind(:,:,:)=grid_get_coarse_index(tl_file, td_coord )
-
-         il_imin=il_ind(1,1,1) ; il_imax=il_ind(1,2,1)
-         il_jmin=il_ind(2,1,1) ; il_jmax=il_ind(2,2,1)
-
-         IF( ANY( il_ind(:,:,2) /= 0 ) )THEN
-            CALL logger_error("CREATE BATHY EXTRACT: something wrong "//&
-            &  " find offset when extracting data")
-         ENDIF
-         !3- check grid coincidence
-         CALL grid_check_coincidence( tl_file, td_coord, &
+         tl_mpp=mpp_copy(td_mpp)
+
+         ! compute file grid indices around coord grid
+         il_ind(:,:)=grid_get_coarse_index(tl_mpp, td_coord )
+
+         il_imin=il_ind(1,1) ; il_imax=il_ind(1,2)
+         il_jmin=il_ind(2,1) ; il_jmax=il_ind(2,2)
+
+         ! check grid coincidence
+         CALL grid_check_coincidence( tl_mpp, td_coord, &
          &                            il_imin, il_imax, &
          &                            il_jmin, il_jmax, &
          &                            (/1, 1, 1/) )
 
-         !4- compute domain
-         tl_dom=dom_init(tl_file,         &
+         ! compute domain
+         tl_dom=dom_init(tl_mpp,           &
          &               il_imin, il_imax, &
          &               il_jmin, il_jmax)
 
-         ! close file
-         CALL iom_close(tl_file)
-
-         !5- read bathymetry on domain (ugly way to do it, have to work on it)
-         !5-1 init mpp structure
-         tl_mpp=mpp_init(tl_file)
-
-         CALL file_clean(tl_file)
-
-         !5-2 get processor to be used
-         CALL mpp_get_use( tl_mpp, tl_dom )
-
-         !5-3 open mpp files
-         CALL iom_mpp_open(tl_mpp)
-
-         !5-4 read variable on domain
-         tl_var=iom_mpp_read_var(tl_mpp,TRIM(td_var%c_name),td_dom=tl_dom)
-
-         !5-5 close mpp file
-         CALL iom_mpp_close(tl_mpp)
-
-         !6- add ghost cell
-         CALL grid_add_ghost(tl_var,tl_dom%i_ighost,tl_dom%i_jghost)
-
-         !7- check result
+         ! open mpp files over domain
+         CALL iom_dom_open(tl_mpp, tl_dom)
+
+         ! read variable on domain
+         tl_var=iom_dom_read_var(tl_mpp,TRIM(td_var%c_name),tl_dom)
+
+         ! close mpp file
+         CALL iom_dom_close(tl_mpp)
+
+         ! add ghost cell
+         CALL grid_add_ghost(tl_var,tl_dom%i_ghost(:,:))
+
+         ! check result
          IF( ANY( tl_var%t_dim(:)%l_use .AND. &
          &        tl_var%t_dim(:)%i_len /= td_coord%t_dim(:)%i_len) )THEN
@@ -743,18 +852,19 @@
          ENDIF
 
-         !8- add attribute to variable
+         ! add attribute to variable
          tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
          CALL var_move_att(tl_var, tl_att)         
 
-         tl_att=att_init('src_i-indices',(/tl_dom%i_imin, tl_dom%i_imax/))
+         tl_att=att_init('src_i_indices',(/tl_dom%i_imin, tl_dom%i_imax/))
          CALL var_move_att(tl_var, tl_att)
 
-         tl_att=att_init('src_j-indices',(/tl_dom%i_jmin, tl_dom%i_jmax/))
+         tl_att=att_init('src_j_indices',(/tl_dom%i_jmin, tl_dom%i_jmax/))
          CALL var_move_att(tl_var, tl_att)
 
-         !9- save result
-         create_bathy_extract=tl_var
+         ! save result
+         create_bathy_extract=var_copy(tl_var)
 
          ! clean structure
+         CALL att_clean(tl_att)
          CALL var_clean(tl_var)
          CALL mpp_clean(tl_mpp)
@@ -762,24 +872,23 @@
 
    END FUNCTION create_bathy_extract
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This function get coarse grid variable, interpolate variable, and return
+   !> variable structure over fine grid
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] td_var : variable structure
-   !> @param[in] td_file : file structure
-   !> @param[in] id_imin : i-direction lower left  corner indice 
-   !> @param[in] id_imax : i-direction upper right corner indice 
-   !> @param[in] id_jmin : j-direction lower left  corner indice
-   !> @param[in] id_jmax : j-direction upper right corner indice 
-   !> @param[in] id_rho  : table of refinement factor
+   !> @param[in] td_var    variable structure
+   !> @param[in] td_mpp    mpp file structure
+   !> @param[in] id_imin   i-direction lower left  corner indice 
+   !> @param[in] id_imax   i-direction upper right corner indice 
+   !> @param[in] id_jmin   j-direction lower left  corner indice
+   !> @param[in] id_jmax   j-direction upper right corner indice 
+   !> @param[in] id_offset offset between fine grid and coarse grid
+   !> @param[in] id_rho    array of refinement factor
+   !> @return variable structure
    !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create_bathy_get_var(td_var, td_file,  &
+   FUNCTION create_bathy_get_var(td_var, td_mpp,   &
             &                    id_imin, id_jmin, &
             &                    id_imax, id_jmax, &
@@ -789,5 +898,5 @@
       ! Argument
       TYPE(TVAR) , INTENT(IN) :: td_var  
-      TYPE(TFILE), INTENT(IN) :: td_file  
+      TYPE(TMPP) , INTENT(IN) :: td_mpp 
       INTEGER(i4), INTENT(IN) :: id_imin
       INTEGER(i4), INTENT(IN) :: id_imax
@@ -801,107 +910,91 @@
 
       ! local variable
-      INTEGER(i4) :: il_pivot
-      INTEGER(i4) :: il_perio
-
-      TYPE(TFILE) :: tl_file
-
       TYPE(TMPP)  :: tl_mpp
-
       TYPE(TATT)  :: tl_att
-
       TYPE(TVAR)  :: tl_var
-      
       TYPE(TDOM)  :: tl_dom
+
+      INTEGER(i4) :: il_size
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
 
       ! loop indices
       !----------------------------------------------------------------
       IF( ANY(SHAPE(id_offset(:,:)) /= 2) )THEN
-         CALL logger_error("CREATE BATHY GET VAR: invalid dimensio of "//&
-         &                 "offset table")
+         CALL logger_error("CREATE BATHY GET VAR: invalid dimension of "//&
+         &                 "offset array")
       ENDIF
 
-      !init
-      tl_file=td_file
-
-      !1- open file
-      CALL iom_open(tl_file)
-
-      ! get periodicity
-      il_pivot=grid_get_pivot(tl_file)
-      il_perio=grid_get_perio(tl_file,il_pivot)
-
-      tl_file%i_perio=il_perio
-
-      !2- compute domain
-      tl_dom=dom_init(tl_file,          &
+      ! copy structure
+      tl_mpp=mpp_copy(td_mpp)
+
+      !- compute domain
+      tl_dom=dom_init(tl_mpp,           &
       &               id_imin, id_imax, &
       &               id_jmin, id_jmax)
 
-      CALL dom_print(tl_dom)
-      print *,'id_offset ',id_offset(:,:)
-      !3- close file
-      CALL iom_close(tl_file)      
-
-      !4- add extra band (if possible) to compute interpolation
+      !- add extra band (if possible) to compute interpolation
       CALL dom_add_extra(tl_dom)
 
-      !5- read bathymetry on domain (ugly way to do it, have to work on it)
-      !5-1 init mpp sturcutre
-      tl_mpp=mpp_init(tl_file)
-
-      CALL file_clean(tl_file)
-
-      !5-2 get processor to be used
-      CALL mpp_get_use( tl_mpp, tl_dom )
-
-      !5-3 open mpp files
-      CALL iom_mpp_open(tl_mpp)
-
-      !5-4 read variable value on domain
-      tl_var=iom_mpp_read_var(tl_mpp,TRIM(td_var%c_name),td_dom=tl_dom)
-
-      !5-5 close mpp files
-      CALL iom_mpp_close(tl_mpp)      
-
-      !6- interpolate variable
-      CALL create_bathy_interp(tl_var, id_rho(:), id_offset(:,:))
-
-      !7- remove extraband added to domain
-      CALL dom_del_extra( tl_var, tl_dom, id_rho(:) )
-
-      !8- add ghost cell
-      CALL grid_add_ghost(tl_var,tl_dom%i_ighost,tl_dom%i_jghost)
+      !- open mpp files over domain
+      CALL iom_dom_open(tl_mpp, tl_dom)
+
+      !- read variable value on domain
+      tl_var=iom_dom_read_var(tl_mpp,TRIM(td_var%c_name),tl_dom)
+
+      !- close mpp files
+      CALL iom_dom_close(tl_mpp)
+
+      il_size=SIZE(id_rho(:))
+      ALLOCATE( il_rho(il_size) )
+      il_rho(:)=id_rho(:)
+      
+      !- interpolate variable
+      CALL create_bathy_interp(tl_var, il_rho(:), id_offset(:,:))
+
+      !- remove extraband added to domain
+      CALL dom_del_extra( tl_var, tl_dom, il_rho(:) )
+
+      !- add ghost cell
+      CALL grid_add_ghost(tl_var,tl_dom%i_ghost(:,:))
  
-      !9- add attribute to variable
+      !- add attribute to variable
       tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
       CALL var_move_att(tl_var, tl_att)
 
-      tl_att=att_init('src_i-indices',(/tl_dom%i_imin, tl_dom%i_imax/))
+      tl_att=att_init('src_i_indices',(/tl_dom%i_imin, tl_dom%i_imax/))
       CALL var_move_att(tl_var, tl_att)
 
-      tl_att=att_init('src_j-indices',(/tl_dom%i_jmin, tl_dom%i_jmax/))
+      tl_att=att_init('src_j_indices',(/tl_dom%i_jmin, tl_dom%i_jmax/))
       CALL var_move_att(tl_var, tl_att)
 
-      !10- save result
-      create_bathy_get_var=tl_var
-
-      !11- clean structure
+      IF( .NOT. ALL(id_rho(:)==1) )THEN
+         tl_att=att_init("refinment_factor",(/id_rho(jp_I),id_rho(jp_J)/))
+         CALL var_move_att(tl_var, tl_att)
+      ENDIF
+
+      DEALLOCATE( il_rho )
+
+      !- save result
+      create_bathy_get_var=var_copy(tl_var)
+
+      !- clean structure
+      CALL att_clean(tl_att)
+      CALL var_clean(tl_var)
       CALL mpp_clean(tl_mpp)
  
    END FUNCTION create_bathy_get_var
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine interpolate variable
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] 
-   !> @todo 
+   !> @param[inout] td_var variable structure 
+   !> @param[in] id_rho    array of refinment factor
+   !> @param[in] id_offset array of offset between fine and coarse grid
+   !> @param[in] id_iext   i-direction size of extra bands (default=im_minext)
+   !> @param[in] id_jext   j-direction size of extra bands (default=im_minext)
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE create_bathy_interp( td_var,         &
    &                               id_rho,          &
@@ -919,5 +1012,4 @@
 
       ! local variable
-      TYPE(TVAR)  :: tl_var
       TYPE(TVAR)  :: tl_mask
 
@@ -929,7 +1021,4 @@
       ! loop indices
       !----------------------------------------------------------------
-
-      ! copy variable
-      tl_var=td_var
 
       !WARNING: two extrabands are required for cubic interpolation
@@ -952,60 +1041,55 @@
       ENDIF
 
-      !1- work on mask
-      !1-1 create mask
-      ALLOCATE(bl_mask(tl_var%t_dim(1)%i_len, &
-      &                tl_var%t_dim(2)%i_len, &
-      &                tl_var%t_dim(3)%i_len, &
-      &                tl_var%t_dim(4)%i_len) )
+      ! work on mask
+      ! create mask
+      ALLOCATE(bl_mask(td_var%t_dim(1)%i_len, &
+      &                td_var%t_dim(2)%i_len, &
+      &                td_var%t_dim(3)%i_len, &
+      &                td_var%t_dim(4)%i_len) )
 
       bl_mask(:,:,:,:)=1
-      WHERE(tl_var%d_value(:,:,:,:)==tl_var%d_fill) bl_mask(:,:,:,:)=0      
-
-      SELECT CASE(TRIM(tl_var%c_point))
+      WHERE(td_var%d_value(:,:,:,:)==td_var%d_fill) bl_mask(:,:,:,:)=0      
+
+      SELECT CASE(TRIM(td_var%c_point))
       CASE DEFAULT ! 'T'
-         tl_mask=var_init('tmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('U')
-         tl_mask=var_init('umask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('V')
-         tl_mask=var_init('vmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('F')
-         tl_mask=var_init('fmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
+         tl_mask=var_init('tmask', bl_mask(:,:,:,:), td_dim=td_var%t_dim(:), &
+         &                id_ew=td_var%i_ew )
+      CASE('U','V','F')
+         CALL logger_fatal("CREATE BATHY INTERP: can not computed "//&
+         &                 "interpolation on "//TRIM(td_var%c_point)//&
+         &                 " grid point (variable "//TRIM(td_var%c_name)//&
+         &                 "). check namelist.")
       END SELECT
 
       DEALLOCATE(bl_mask)
 
-      !1-2 interpolate mask
+      ! interpolate mask
       CALL interp_fill_value( tl_mask, id_rho(:), &
       &                       id_offset=id_offset(:,:) )
 
-      !2- work on variable
-      !2-0 add extraband
-      CALL extrap_add_extrabands(tl_var, il_iext, il_jext)
-
-      !2-1 extrapolate variable
-      CALL extrap_fill_value( tl_var, id_offset=id_offset(:,:), &
+      ! work on variable
+      ! add extraband
+      CALL extrap_add_extrabands(td_var, il_iext, il_jext)
+
+      ! extrapolate variable
+      CALL extrap_fill_value( td_var, id_offset=id_offset(:,:), &
       &                               id_rho=id_rho(:),         &
       &                               id_iext=il_iext, id_jext=il_jext )
 
-      !2-2 interpolate Bathymetry
-      CALL interp_fill_value( tl_var, id_rho(:), &
+      ! interpolate Bathymetry
+      CALL interp_fill_value( td_var, id_rho(:), &
       &                       id_offset=id_offset(:,:) )
 
-      !2-3 remove extraband
-      CALL extrap_del_extrabands(tl_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
-
-      !2-2-5 keep original mask 
+      ! remove extraband
+      CALL extrap_del_extrabands(td_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
+
+      ! keep original mask 
       WHERE( tl_mask%d_value(:,:,:,:) == 0 )
-         tl_var%d_value(:,:,:,:)=tl_var%d_fill
+         td_var%d_value(:,:,:,:)=td_var%d_fill
       END WHERE
-
-      !3- save result
-      td_var=tl_var
 
       ! clean variable structure
       CALL var_clean(tl_mask)
-      CALL var_clean(tl_var)
 
    END SUBROUTINE create_bathy_interp
-   !> @endcode
 END PROGRAM create_bathy
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_boundary.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_boundary.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_boundary.f90	(revision 5075)
@@ -7,21 +7,170 @@
 !
 ! DESCRIPTION:
+!> @file
 !> @brief 
 !> This program create boundary files.
 !>
 !> @details
-!> Variables are read from standard output.
-!> Then theses variables are interpolated on fine grid boundaries.
-!>
-!> @author
-!> J.Paul
+!> @section sec1 method
+!> Variables are read from coarse grid standard output 
+!> and interpolated on fine grid or manually written.<br/>
+!> @note 
+!>    method could be different for each variable.
+!>
+!> @section sec2 how to 
+!>    to create boundaries files:<br/>
+!> @code{.sh}
+!>    ./SIREN/bin/create_boundary create_boundary.nam
+!> @endcode
+!>    
+!>    create_boundary.nam comprise 9 namelists:<br/>
+!>       - logger namelist (namlog)
+!>       - config namelist (namcfg)
+!>       - coarse grid namelist (namcrs)
+!>       - fine grid namelist (namfin)
+!>       - variable namelist (namvar)
+!>       - nesting namelist (namnst)
+!>       - boundary namelist (nambdy)
+!>       - vertical grid namelist (namzgr)
+!>       - output namelist (namout)
+!>    
+!>    @note 
+!>       All namelists have to be in file create_boundary.nam, 
+!>       however variables of those namelists are all optional.
+!>
+!>    * _logger namelist (namlog)_:<br/>
+!>       - cn_logfile   : log filename
+!>       - cn_verbosity : verbosity ('trace','debug','info',
+!> 'warning','error','fatal')
+!>       - in_maxerror  : maximum number of error allowed
+!>
+!>    * _config namelist (namcfg)_:<br/>
+!>       - cn_varcfg : variable configuration file
+!> (see ./SIREN/cfg/variable.cfg)
+!>
+!>    * _coarse grid namelist (namcrs)_:<br/>
+!>       - cn_coord0 : coordinate file
+!>       - in_perio0 : NEMO periodicity index (see Model Boundary Condition in
+!> [NEMO documentation](http://www.nemo-ocean.eu/About-NEMO/Reference-manuals))
+!>
+!>    * _fine grid namelist (namfin)_:<br/>
+!>       - cn_coord1 : coordinate file
+!>       - cn_bathy1 : bathymetry file
+!>       - in_perio1 : periodicity index
+!>
+!>    * _vertical grid namelist (namzgr)_:<br/>
+!>       - dn_pp_to_be_computed  :
+!>       - dn_ppsur              :
+!>       - dn_ppa0               :
+!>       - dn_ppa1               :
+!>       - dn_ppa2               : 
+!>       - dn_ppkth              :
+!>       - dn_ppkth2             :
+!>       - dn_ppacr              :
+!>       - dn_ppacr2             :
+!>       - dn_ppdzmin            :
+!>       - dn_pphmax             :
+!>       - in_nlevel             : number of vertical level
+!>
+!>    * _partial step namelist (namzps)_:<br/>
+!>       - dn_e3zps_mi           :
+!>       - dn_e3zps_rat          : 
+!>
+!>    * _variable namelist (namvar)_:<br/>
+!>       - cn_varinfo : list of variable and extra information about request(s)
+!> to be used.<br/>
+!>          each elements of *cn_varinfo* is a string character.<br/>
+!>          it is composed of the variable name follow by ':', 
+!>          then request(s) to be used on this variable.<br/> 
+!>          request could be:
+!>             - interpolation method
+!>             - extrapolation method
+!>             - filter method
+!>
+!>                requests must be separated by ';'.<br/>
+!>                order of requests does not matter.
+!>
+!>          informations about available method could be find in @ref interp,
+!>          @ref extrap and @ref filter.<br/>
+!>
+!>          Example: 'votemper:linear;hann;dist_weight', 'vosaline:cubic'
+!>          @note 
+!>             If you do not specify a method which is required, 
+!>             default one is apply.
+!>       - cn_varfile : list of variable, and corresponding file<br/> 
+!>          *cn_varfile* is the path and filename of the file where find
+!>          variable.<br/> 
+!>          @note 
+!>             *cn_varfile* could be a matrix of value, if you want to filled
+!>             manually variable value.<br/>
+!>             the variable array of value is split into equal subdomain.<br/>
+!>             Each subdomain is filled with the corresponding value 
+!>             of the matrix.<br/>          
+!>             separators used to defined matrix are:
+!>                - ',' for line
+!>                - '/' for row
+!>                - '\' for level<br/>
+!>                Example:<br/>
+!>                   3,2,3/1,4,5  =>  @f$ \left( \begin{array}{ccc}
+!>                                         3 & 2 & 3 \\
+!>                                         1 & 4 & 5 \end{array} \right) @f$
+!>          @warning 
+!>             the same matrix is used for all boundaries.
+!>
+!>       Examples: 
+!>          - 'votemper:gridT.nc', 'vozocrtx:gridU.nc'
+!>          - 'votemper:10\25', 'vozocrtx:gridU.nc'
+!>
+!>    * _nesting namelist (namnst)_:<br/>
+!>       - in_rhoi  : refinement factor in i-direction
+!>       - in_rhoj  : refinement factor in j-direction
+!>
+!>    * _boundary namelist (nambdy)_:<br/>
+!>       - ln_north  : use north boundary
+!>       - ln_south  : use south boundary
+!>       - ln_east   : use east  boundary
+!>       - ln_west   : use west  boundary
+!>       - cn_north  : north boundary indices on fine grid
+!>          *cn_north* is a string character defining boundary
+!>          segmentation.<br/>
+!>          segments are separated by '|'.<br/>
+!>          each segments of the boundary is composed of:
+!>             - orthogonal indice (.ie. for north boundary,
+!>             J-indice where boundary are). 
+!>             - first indice of boundary (I-indice for north boundary) 
+!>             - last  indice of boundary (I-indice for north boundary)<br/>
+!>                indices must be separated by ',' .<br/>
+!>             - optionally, boundary size could be added between '(' and ')' 
+!>             in the first segment defined.
+!>                @note 
+!>                   boundary width is the same for all segments of one boundary.
+!>
+!>          Examples:
+!>             - cn_north='index1,first1,last1(width)'
+!>             - cn_north='index1(width),first1,last1|index2,first2,last2'
+!>
+!>          \image html  boundary_50.png 
+!>          \image latex boundary_50.png
+!>
+!>       - cn_south  : south boundary indices on fine grid
+!>       - cn_east   : east  boundary indices on fine grid
+!>       - cn_west   : west  boundary indices on fine grid
+!>       - ln_oneseg : use only one segment for each boundary or not
+!>       - in_extrap : number of mask point to be extrapolated
+!>
+!>   * _output namelist (namout)_:<br/>
+!>       - cn_fileout : fine grid boundary basename
+!>         (cardinal and segment number will be automatically added)
+!>
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
+!> @date November, 2013 - Initial Version
+!> @date September, 2014
+!> - add header for user
+!> - take into account grid point to compue boundaries
+!> - reorder output dimension for north and south boundaries 
+!>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!>
-!> @todo
 !----------------------------------------------------------------------
-!> @code
 PROGRAM create_boundary
 
@@ -57,9 +206,11 @@
    CHARACTER(LEN=lc)                                  :: cl_bdyout
    CHARACTER(LEN=lc)                                  :: cl_data
+   CHARACTER(LEN=lc)                                  :: cl_dimorder
+   CHARACTER(LEN=lc)                                  :: cl_point
+   CHARACTER(LEN=lc)                                  :: cl_fmt
 
    INTEGER(i4)                                        :: il_narg
    INTEGER(i4)                                        :: il_status
    INTEGER(i4)                                        :: il_fileid
-   INTEGER(i4)                                        :: il_attid
    INTEGER(i4)                                        :: il_dim
    INTEGER(i4)                                        :: il_imin0
@@ -67,35 +218,23 @@
    INTEGER(i4)                                        :: il_jmin0
    INTEGER(i4)                                        :: il_jmax0
+   INTEGER(i4)                                        :: il_shift
    INTEGER(i4)      , DIMENSION(ip_maxdim)            :: il_rho
    INTEGER(i4)      , DIMENSION(2,2)                  :: il_offset
-   INTEGER(i4)      , DIMENSION(2,2,2)                :: il_ind
+   INTEGER(i4)      , DIMENSION(2,2)                  :: il_ind
 
    LOGICAL                                            :: ll_exist
-
-   TYPE(TFILE)                                        :: tl_coord0
-   TYPE(TFILE)                                        :: tl_bathy0
-   TYPE(TFILE)                                        :: tl_coord1
-   TYPE(TFILE)                                        :: tl_bathy1
-   TYPE(TFILE)                                        :: tl_file
-   TYPE(TFILE)                                        :: tl_fileout
-   
-   TYPE(TMPP)                                         :: tl_mpp
-
-   TYPE(TMULTI)                                       :: tl_multi
 
    TYPE(TATT)                                         :: tl_att
    
+   TYPE(TVAR)                                         :: tl_depth   
+   TYPE(TVAR)                                         :: tl_time
+   TYPE(TVAR)                                         :: tl_var1
+   TYPE(TVAR)                                         :: tl_var0
+   TYPE(TVAR)                                         :: tl_lon1
+   TYPE(TVAR)                                         :: tl_lat1
+   TYPE(TVAR)                                         :: tl_lvl1  
    TYPE(TVAR)       , DIMENSION(:)      , ALLOCATABLE :: tl_level
    TYPE(TVAR)       , DIMENSION(:,:,:)  , ALLOCATABLE :: tl_seglvl1
-   TYPE(TVAR)                                         :: tl_var1
    TYPE(TVAR)       , DIMENSION(:,:,:)  , ALLOCATABLE :: tl_segvar1
-   TYPE(TVAR)       , DIMENSION(:,:)    , ALLOCATABLE :: tl_seglon1
-   TYPE(TVAR)       , DIMENSION(:,:)    , ALLOCATABLE :: tl_seglat1
-   TYPE(TVAR)       , DIMENSION(:,:)    , ALLOCATABLE :: tl_var
-   TYPE(TVAR)       , DIMENSION(:)      , ALLOCATABLE :: tl_lon1
-   TYPE(TVAR)       , DIMENSION(:)      , ALLOCATABLE :: tl_lat1
-   TYPE(TVAR)                                         :: tl_depth   
-   TYPE(TVAR)                                         :: tl_time
-   TYPE(TVAR)                                         :: tl_tmp   
 
    TYPE(TDIM)       , DIMENSION(ip_maxdim)            :: tl_dim
@@ -104,8 +243,19 @@
    
    TYPE(TDOM)                                         :: tl_dom0
-   TYPE(TDOM)       , DIMENSION(:,:)    , ALLOCATABLE :: tl_segdom1
+   TYPE(TDOM)                                         :: tl_dom1
+   TYPE(TDOM)       , DIMENSION(:,:,:)  , ALLOCATABLE :: tl_segdom1
+
+   TYPE(TFILE)                                        :: tl_fileout
+   
+   TYPE(TMPP)                                         :: tl_coord0
+   TYPE(TMPP)                                         :: tl_coord1
+   TYPE(TMPP)                                         :: tl_bathy1
+   TYPE(TMPP)                                         :: tl_mpp
+
+   TYPE(TMULTI)                                       :: tl_multi
 
    ! loop indices
    INTEGER(i4) :: jvar
+   INTEGER(i4) :: jpoint
    INTEGER(i4) :: ji
    INTEGER(i4) :: jj
@@ -117,4 +267,8 @@
    CHARACTER(LEN=lc)                       :: cn_logfile = 'create_boundary.log' 
    CHARACTER(LEN=lc)                       :: cn_verbosity = 'warning' 
+   INTEGER(i4)                             :: in_maxerror = 5
+
+   ! namcfg
+   CHARACTER(LEN=lc)                       :: cn_varcfg = 'variable.cfg' 
 
    ! namcrs
@@ -127,18 +281,14 @@
    INTEGER(i4)                             :: in_perio1 = -1
 
-   ! namcfg
-   CHARACTER(LEN=lc)                       :: cn_varcfg = 'variable.cfg' 
+   !namzgr
+   INTEGER(i4)                             :: in_nlevel = 75
 
    ! namvar
-   CHARACTER(LEN=lc), DIMENSION(ig_maxvar) :: cn_varinfo = ''
-   CHARACTER(LEN=lc), DIMENSION(ig_maxvar) :: cn_varfile = ''
+   CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varinfo = ''
+   CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varfile = ''
 
    ! namnst
-   INTEGER(i4)                             :: in_imin0 = 0
-   INTEGER(i4)                             :: in_imax0 = 0
-   INTEGER(i4)                             :: in_jmin0 = 0
-   INTEGER(i4)                             :: in_jmax0 = 0
-   INTEGER(i4)                             :: in_rhoi  = 1
-   INTEGER(i4)                             :: in_rhoj  = 1
+   INTEGER(i4)                             :: in_rhoi  = 0
+   INTEGER(i4)                             :: in_rhoj  = 0
 
    ! nambdy
@@ -160,5 +310,6 @@
    NAMELIST /namlog/ &  !< logger namelist
    &  cn_logfile,    &  !< log file
-   &  cn_verbosity      !< log verbosity
+   &  cn_verbosity,  &  !< log verbosity
+   &  in_maxerror
 
    NAMELIST /namcfg/ &  !< config namelist
@@ -174,4 +325,7 @@
    &  in_perio1         !< periodicity index
  
+   NAMELIST /namzgr/ &
+   &  in_nlevel
+
    NAMELIST /namvar/ &  !< variable namelist
    &  cn_varinfo,    &  !< list of variable and method to apply on. (ex: 'votemper:linear','vosaline:cubic' )
@@ -179,8 +333,4 @@
    
    NAMELIST /namnst/ &  !< nesting namelist
-   &  in_imin0,      &  !< i-direction lower left  point indice on coarse grid 
-   &  in_imax0,      &  !< i-direction upper right point indice on coarse grid
-   &  in_jmin0,      &  !< j-direction lower left  point indice on coarse grid
-   &  in_jmax0,      &  !< j-direction upper right point indice on coarse grid
    &  in_rhoi,       &  !< refinement factor in i-direction
    &  in_rhoj           !< refinement factor in j-direction
@@ -196,5 +346,5 @@
    &  cn_west ,      &  !< west  boundary indices on fine grid
    &  ln_oneseg,     &  !< use only one segment for each boundary or not
-   &  in_extrap         !< number of mask point to extrapolate
+   &  in_extrap         !< number of mask point to be extrapolated
 
    NAMELIST /namout/ &  !< output namelist
@@ -202,6 +352,6 @@
    !-------------------------------------------------------------------
 
-   !1- namelist
-   !1-1 get namelist
+   ! namelist
+   ! get namelist
    il_narg=COMMAND_ARGUMENT_COUNT() !f03 intrinsec
    IF( il_narg/=1 )THEN
@@ -212,5 +362,5 @@
    ENDIF
    
-   !1-2 read namelist
+   ! read namelist
    INQUIRE(FILE=TRIM(cl_namelist), EXIST=ll_exist)
    IF( ll_exist )THEN
@@ -231,23 +381,23 @@
 
       READ( il_fileid, NML = namlog )
-      !1-2-1 define log file
-      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity))
+      ! define log file
+      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity),in_maxerror)
       CALL logger_header()
 
       READ( il_fileid, NML = namcfg )
-      !1-2-2 get variable extra information
+      ! get variable extra information
       CALL var_def_extra(TRIM(cn_varcfg))
 
       READ( il_fileid, NML = namcrs )
       READ( il_fileid, NML = namfin )
+      READ( il_fileid, NML = namzgr )
       READ( il_fileid, NML = namvar )
-      !1-2-3 add user change in extra information
+      ! add user change in extra information
       CALL var_chg_extra(cn_varinfo)
-      !1-2-4 match variable with file
+      ! match variable with file
       tl_multi=multi_init(cn_varfile)
 
       READ( il_fileid, NML = namnst )
       READ( il_fileid, NML = nambdy )
-
       READ( il_fileid, NML = namout )
 
@@ -261,11 +411,18 @@
 
       PRINT *,"CREATE BOUNDARY: ERROR. can not find "//TRIM(cl_namelist)
+      STOP
 
    ENDIF
 
-   !2- open files
+   CALL multi_print(tl_multi)
+   IF( tl_multi%i_nvar <= 0 )THEN
+      CALL logger_fatal("CREATE BOUNDARY: no variable to be used."//&
+      &  " check namelist.")
+   ENDIF
+
+   ! open files
    IF( TRIM(cn_coord0) /= '' )THEN
-      tl_coord0=file_init(TRIM(cn_coord0),id_perio=in_perio0)
-      CALL iom_open(tl_coord0)
+      tl_coord0=mpp_init( file_init(TRIM(cn_coord0)), id_perio=in_perio0)
+      CALL grid_get_info(tl_coord0)
    ELSE
       CALL logger_fatal("CREATE BOUNDARY: can not find coarse grid "//&
@@ -274,6 +431,6 @@
 
    IF( TRIM(cn_coord1) /= '' )THEN
-      tl_coord1=file_init(TRIM(cn_coord1),id_perio=in_perio1)
-      CALL iom_open(tl_coord1)
+      tl_coord1=mpp_init( file_init(TRIM(cn_coord1)), id_perio=in_perio1)
+      CALL grid_get_info(tl_coord1)
    ELSE
       CALL logger_fatal("CREATE BOUNDARY: can not find fine grid coordinate "//&
@@ -282,6 +439,6 @@
 
    IF( TRIM(cn_bathy1) /= '' )THEN
-      tl_bathy1=file_init(TRIM(cn_bathy1),id_perio=in_perio1)
-      CALL iom_open(tl_bathy1)
+      tl_bathy1=mpp_init( file_init(TRIM(cn_bathy1)), id_perio=in_perio1)
+      CALL grid_get_info(tl_bathy1)
    ELSE
       CALL logger_fatal("CREATE BOUNDARY: can not find fine grid bathymetry "//&
@@ -289,9 +446,9 @@
    ENDIF
 
-   !3- check
-   !3-1 check output file do not already exist
+   ! check
+   ! check output file do not already exist
    DO jk=1,ip_ncard
       cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
-      &                                TRIM(ip_card(jk)) )
+      &                                TRIM(cp_card(jk)), 1 )
       INQUIRE(FILE=TRIM(cl_bdyout), EXIST=ll_exist)
       IF( ll_exist )THEN
@@ -301,6 +458,6 @@
    ENDDO
 
-   !3-1 check namelist
-   !3-1-1 check refinement factor
+   ! check namelist
+   ! check refinement factor
    il_rho(:)=1
    IF( in_rhoi < 1 .OR. in_rhoj < 1 )THEN
@@ -312,20 +469,16 @@
    ENDIF
 
-   !3-1-2
-   IF( in_imin0 < 1 .OR. in_imax0 < 1 .OR. in_jmin0 < 1 .OR. in_jmax0 < 1)THEN
-      ! compute coarse grid indices around fine grid
-      il_ind(:,:,:)=grid_get_coarse_index(tl_bathy0, tl_bathy1 )
-
-      il_imin0=il_ind(1,1,1) ; il_imax0=il_ind(1,2,1)
-      il_jmin0=il_ind(2,1,1) ; il_jmax0=il_ind(2,2,1)
-   ELSE
-      il_imin0=in_imin0 ; il_imax0=in_imax0
-      il_jmin0=in_jmin0 ; il_jmax0=in_jmax0
-   ENDIF
-
-   !3-2 check domain validity
+   !
+   ! compute coarse grid indices around fine grid
+   il_ind(:,:)=grid_get_coarse_index(tl_coord0, tl_coord1, &
+   &                                 id_rho=il_rho(:))
+
+   il_imin0=il_ind(1,1) ; il_imax0=il_ind(1,2)
+   il_jmin0=il_ind(2,1) ; il_jmax0=il_ind(2,2)
+
+   ! check domain validity
    CALL grid_check_dom(tl_coord0, il_imin0, il_imax0, il_jmin0, il_jmax0)
 
-   !3-3 check coordinate file
+   ! check coordinate file
    CALL grid_check_coincidence( tl_coord0, tl_coord1, &
    &                            il_imin0, il_imax0, &
@@ -333,6 +486,12 @@
    &                            il_rho(:) )      
 
-   !4- read or compute boundary
-   tl_var1=iom_read_var(tl_bathy1,'Bathymetry')
+   ! read or compute boundary
+   CALL mpp_get_contour(tl_bathy1)
+
+   CALL iom_mpp_open(tl_bathy1)
+   
+   tl_var1=iom_mpp_read_var(tl_bathy1,'Bathymetry')
+   
+   CALL iom_mpp_close(tl_bathy1)
 
    tl_bdy(:)=boundary_init(tl_var1, ln_north, ln_south, ln_east, ln_west, &
@@ -342,25 +501,30 @@
    CALL var_clean(tl_var1)
 
-   !5- compute level
-   ALLOCATE(tl_level(ig_npoint))
+   ! compute level
+   ALLOCATE(tl_level(ip_npoint))
    tl_level(:)=vgrid_get_level(tl_bathy1, cl_namelist )
 
-   !6- get coordinate on each segment of each boundary
-   ALLOCATE( tl_seglon1(ip_ncard,ig_maxseg) )
-   ALLOCATE( tl_seglat1(ip_ncard,ig_maxseg) )
-   ALLOCATE( tl_segdom1(ip_ncard,ig_maxseg) )
-   ALLOCATE( tl_segvar1(tl_multi%i_nvar,ip_ncard,ig_maxseg) )
-   ALLOCATE( tl_seglvl1(ip_ncard,ig_maxseg,ig_npoint) )
-   DO jk=1,ip_ncard
-      IF( tl_bdy(jk)%l_use )THEN
-         DO jl=1,tl_bdy(jk)%i_nseg
-            !6-1 get fine grid segment domain
-            tl_segdom1(jk,jl)=create_boundary_get_dom( tl_bathy1, tl_bdy(jk), jl )
-
-            !6-2 get fine grid segment coordinate
-            CALL create_boundary_get_coord( tl_bathy1, tl_segdom1(jk,jl), &
-            &                               tl_seglon1(jk,jl), tl_seglat1(jk,jl) )
-            !6-2 get fine grid segment coordinate
-            tl_seglvl1(jk,jl,:)=create_bdy_get_level(tl_level(:), tl_segdom1(jk,jl))
+   ! get coordinate on each segment of each boundary
+   ALLOCATE( tl_segdom1(ip_npoint,ip_maxseg,ip_ncard) )
+   ALLOCATE( tl_seglvl1(ip_npoint,ip_maxseg,ip_ncard) )
+   
+   DO jl=1,ip_ncard
+      IF( tl_bdy(jl)%l_use )THEN
+         DO jk=1,tl_bdy(jl)%i_nseg
+
+            ! get fine grid segment domain
+            tl_segdom1(:,jk,jl)=create_boundary_get_dom( tl_bathy1, &
+            &                                            tl_bdy(jl), jk )
+
+            ! add extra band to fine grid domain (if possible)
+            ! to avoid dimension of one and so be able to compute offset
+            DO jj=1,ip_npoint
+               CALL dom_add_extra(tl_segdom1(jj,jk,jl), &
+               &                  il_rho(jp_I), il_rho(jp_J))
+            ENDDO
+
+            ! get fine grid level
+            tl_seglvl1(:,jk,jl)=create_boundary_get_level( tl_level(:), &
+                                                           tl_segdom1(:,jk,jl))
 
          ENDDO
@@ -368,253 +532,370 @@
    ENDDO
 
+   ! clean
+   CALL var_clean(tl_level(:))
    DEALLOCATE(tl_level)
 
-   !7- compute boundary for variable to be used (see namelist)
-   IF( .NOT. ASSOCIATED(tl_multi%t_file) )THEN
+   ! clean bathy
+   CALL mpp_clean(tl_bathy1)
+
+   ALLOCATE( tl_segvar1(tl_multi%i_nvar,ip_maxseg,ip_ncard) )
+   ! compute boundary for variable to be used (see namelist)
+   IF( .NOT. ASSOCIATED(tl_multi%t_mpp) )THEN
       CALL logger_error("CREATE BOUNDARY: no file to work on. "//&
       &                 "check cn_varfile in namelist.")
    ELSE
+
       jvar=0
       ! for each file
-      DO ji=1,tl_multi%i_nfile
-         WRITE(cl_data,'(a,i2.2)') 'data_',jvar+1
-
-         IF( .NOT. ASSOCIATED(tl_multi%t_file(ji)%t_var) )THEN
+      DO ji=1,tl_multi%i_nmpp
+
+         WRITE(cl_data,'(a,i2.2)') 'data-',jvar+1
+
+         IF( .NOT. ASSOCIATED(tl_multi%t_mpp(ji)%t_proc(1)%t_var) )THEN
+
             CALL logger_error("CREATE BOUNDARY: no variable to work on for "//&
-            &                 "file "//TRIM(tl_multi%t_file(ji)%c_name)//&
+            &                 "mpp "//TRIM(tl_multi%t_mpp(ji)%c_name)//&
             &                 ". check cn_varfile in namelist.")
+
+         ELSEIF( TRIM(tl_multi%t_mpp(ji)%c_name) == TRIM(cl_data) )THEN
+         !- use input matrix to fill variable
+
+            WRITE(*,'(a)') "work on data"
+            ! for each variable initialise from matrix
+            DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
+
+               jvar=jvar+1
+               WRITE(*,'(2x,a,a)') "work on variable "//&
+               &  TRIM(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
+
+               tl_var1=var_copy(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj))
+
+               SELECT CASE(TRIM(tl_var1%c_point))
+               CASE DEFAULT !'T'
+                  jpoint=jp_T
+               CASE('U')
+                  jpoint=jp_U
+               CASE('V')
+                  jpoint=jp_V
+               CASE('F')
+                  jpoint=jp_F
+               END SELECT
+
+               WRITE(*,'(4x,a,a)') 'work on '//TRIM(tl_var1%c_name)
+               DO jl=1,ip_ncard
+                  IF( tl_bdy(jl)%l_use )THEN
+
+                     DO jk=1,tl_bdy(jl)%i_nseg
+
+                        ! fill value with matrix data
+                        tl_segvar1(jvar,jk,jl)=create_boundary_matrix( &
+                        &                          tl_var1, &
+                        &                          tl_segdom1(jpoint,jk,jl), &
+                        &                          in_nlevel )
+
+                        ! use mask
+                        CALL create_boundary_use_mask( tl_segvar1(jvar,jk,jl), &
+                        &                         tl_seglvl1(jpoint,jk,jl))
+
+                        !del extra
+                        CALL dom_del_extra( tl_segvar1(jvar,jk,jl), &
+                        &                   tl_segdom1(jpoint,jk,jl) )
+
+                     ENDDO
+
+                  ENDIF
+               ENDDO
+               
+               ! clean
+               CALL var_clean(tl_var1)
+
+            ENDDO
+
+         !- end of use input matrix to fill variable
          ELSE
-            IF( .NOT. ASSOCIATED(tl_multi%t_file(ji)%t_var) )THEN
-
-               CALL logger_error("CREATE BOUNDARY: no variable to work on for "//&
-               &                 "file "//TRIM(tl_multi%t_file(ji)%c_name)//&
-               &                 ". check cn_varfile in namelist.")
-
-            ELSEIF( TRIM(tl_multi%t_file(ji)%c_name) == TRIM(cl_data) )THEN
-            !- use input matrix to fill variable
-
-               ! for each variable initialise from matrix
-               DO jj=1,tl_multi%t_file(ji)%i_nvar
-                  jvar=jvar+1
-                  tl_tmp=tl_multi%t_file(ji)%t_var(jj)
-                  DO jk=1,ip_ncard
-                     IF( tl_bdy(jk)%l_use )THEN
-                        DO jl=1,tl_bdy(jk)%i_nseg
-                           !7-1 fill value with matrix data
-                           ! pb voir comment gerer nb de dimension
-                           tl_segvar1(jvar,jk,jl)=create_bdy_matrix(tl_tmp, tl_segdom1(jk,jl), tl_coord1)
-
-                           !7-2 use mask
-                           CALL create_bdy_use_mask(tl_segvar1(jvar,jk,jl), tl_seglvl1(jk,jl,:))
-                        ENDDO
-                     ENDIF
-                  ENDDO
-               ENDDO
-
+         !- use file to fill variable
+
+            WRITE(*,'(a)') "work on file "//TRIM(tl_multi%t_mpp(ji)%c_name)
+            ! 
+            tl_mpp=mpp_init(file_init(TRIM(tl_multi%t_mpp(ji)%t_proc(1)%c_name)))
+            CALL grid_get_info(tl_mpp)
+
+            ! check vertical dimension
+            IF( tl_mpp%t_dim(jp_K)%l_use .AND. &
+            &   tl_mpp%t_dim(jp_K)%i_len /= in_nlevel  )THEN
+               CALL logger_error("CREATE BOUNDARY: dimension in file "//&
+               &  TRIM(tl_mpp%c_name)//" not agree with namelist in_nlevel ")
+            ENDIF
+
+            ! open mpp file
+            CALL iom_mpp_open(tl_mpp)
+
+            ! get or check depth value
+            CALL create_boundary_check_depth( tl_mpp, tl_depth )
+
+            ! get or check time value
+            CALL create_boundary_check_time( tl_mpp, tl_time )
+
+            ! close mpp file
+            CALL iom_mpp_close(tl_mpp)
+
+            IF( ANY( tl_mpp%t_dim(1:2)%i_len /= &
+            &        tl_coord0%t_dim(1:2)%i_len) )THEN
+            !- extract value from fine grid
+
+               IF( ANY( tl_mpp%t_dim(1:2)%i_len <= &
+               &        tl_coord1%t_dim(1:2)%i_len) )THEN
+                  CALL logger_fatal("CREATE BOUNDARY: dimension in file "//&
+                  &  TRIM(tl_mpp%c_name)//" smaller than those in fine"//&
+                  &  " grid coordinates.")
+               ENDIF
+
+               DO jl=1,ip_ncard
+                  IF( tl_bdy(jl)%l_use )THEN
+                     
+                     WRITE(*,'(2x,a,a)') 'work on '//TRIM(tl_bdy(jl)%c_card)//' boundary'
+                     DO jk=1,tl_bdy(jl)%i_nseg
+                        ! compute domain on fine grid
+                        
+                        ! for each variable of this file
+                        DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
+                           
+                           cl_name=tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name
+                           WRITE(*,'(4x,a,a)') "work on variable "//TRIM(cl_name)
+
+                           cl_point=tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_point
+                           ! open mpp file on domain
+                           SELECT CASE(TRIM(cl_point))
+                              CASE DEFAULT !'T'
+                                 jpoint=jp_T
+                              CASE('U')
+                                 jpoint=jp_U
+                              CASE('V')
+                                 jpoint=jp_V
+                              CASE('F')
+                                 jpoint=jp_F
+                           END SELECT
+
+                           tl_dom1=dom_copy(tl_segdom1(jpoint,jk,jl))
+                           tl_lvl1=var_copy(tl_seglvl1(jpoint,jk,jl))
+
+                           ! open mpp files
+                           CALL iom_dom_open(tl_mpp, tl_dom1)
+
+                           !7-5 read variable over domain
+                           tl_segvar1(jvar+jj,jk,jl)=iom_dom_read_var( &
+                           &                     tl_mpp, TRIM(cl_name), tl_dom1)
+
+                           ! use mask
+                           CALL create_boundary_use_mask( &
+                           &                 tl_segvar1(jvar+jj,jk,jl), tl_lvl1)
+
+                           ! del extra point
+                           CALL dom_del_extra( tl_segvar1(jvar+jj,jk,jl), &
+                           &                   tl_dom1 )
+
+                           ! clean extra point information on fine grid domain
+                           CALL dom_clean_extra( tl_dom1 )
+
+                           ! add attribute to variable
+                           tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
+                           CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
+
+                           tl_att=att_init('src_i_indices',(/tl_dom1%i_imin, tl_dom1%i_imax/))
+                           CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
+
+                           tl_att=att_init('src_j_indices',(/tl_dom1%i_jmin, tl_dom1%i_jmax/))
+                           CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
+
+                           ! clean structure
+                           CALL att_clean(tl_att)
+                           CALL dom_clean(tl_dom1)
+
+                           ! close mpp files
+                           CALL iom_dom_close(tl_mpp)
+
+                           ! clean
+                           CALL var_clean(tl_lvl1)
+
+                        ENDDO ! jj
+                     ENDDO ! jk
+
+                  ENDIF
+               ENDDO ! jl
+
+               ! clean
+               CALL mpp_clean(tl_mpp)
+
+               jvar=jvar+tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
+
+            !- end of extract value from fine grid
             ELSE
-            !- use file to fill variable
-
-               ! open file
-               tl_file=file_init(TRIM(tl_multi%t_file(ji)%c_name))
-               CALL iom_open(tl_file)
-
-               ! get or check depth value
-               IF( tl_file%i_depthid /= 0 )THEN
-                  IF( ASSOCIATED(tl_depth%d_value) )THEN
-                     IF( ANY( tl_depth%d_value(:,:,:,:) /= &
-                     &        tl_tmp%d_value(:,:,:,:) ) )THEN
-                        CALL logger_fatal("CREATE BOUNDARY: depth value from "//&
-                        &  TRIM(tl_multi%t_file(ji)%c_name)//" not conform "//&
-                        &  " to those from former file(s).")
-                     ENDIF
-                  ELSE
-                     tl_depth=iom_read_var(tl_file,tl_file%i_depthid)
-                  ENDIF
-               ENDIF
-
-               ! get or check time value
-               IF( tl_file%i_timeid /= 0 )THEN
-                  IF( ASSOCIATED(tl_time%d_value) )THEN
-                     IF( ANY( tl_time%d_value(:,:,:,:) /= &
-                     &        tl_tmp%d_value(:,:,:,:) ) )THEN
-                        CALL logger_fatal("CREATE BOUNDARY: time value from "//&
-                        &  TRIM(tl_multi%t_file(ji)%c_name)//" not conform "//&
-                        &  " to those from former file(s).")
-                     ENDIF
-                  ELSE
-                     tl_time=iom_read_var(tl_file,tl_file%i_timeid)
-                  ENDIF
-               ENDIF
-
-               IF( ANY( tl_file%t_dim(1:2)%i_len /= &
-               &      tl_coord0%t_dim(1:2)%i_len) )THEN
-               !- extract value from fine grid
-                  DO jk=1,ip_ncard
-                     IF( tl_bdy(jk)%l_use )THEN
-
-                        DO jl=1,tl_bdy(jk)%i_nseg
-                           !7-1 compute domain on fine grid
+            !- interpolate value from coarse grid
+
+               DO jl=1,ip_ncard
+                  IF( tl_bdy(jl)%l_use )THEN
+
+                     WRITE(*,'(2x,a,a)') 'work on '//TRIM(tl_bdy(jl)%c_card)//' boundary'
+                     DO jk=1,tl_bdy(jl)%i_nseg
+                        
+                        ! for each variable of this file
+                        DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
                            
+                           WRITE(*,'(4x,a,a)') "work on variable "//&
+                           &  TRIM(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
+
+                           tl_var0=var_copy(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj))
                            ! open mpp file on domain
-                           !7-2 init mpp structure
-                           tl_mpp=mpp_init(tl_file)
-
-                           !7-3 get processor to be used
-                           CALL mpp_get_use( tl_mpp, tl_segdom1(jk,jl) )
-                           !7-4 open mpp files
-                           CALL iom_mpp_open(tl_mpp)
-
-                           ! for each variable of this file
-                           DO jj=1,tl_multi%t_file(ji)%i_nvar
-                              
-                              cl_name=tl_multi%t_file(ji)%t_var(jj)%c_name
-                              !7-5 read variable over domain
-                              tl_segvar1(jvar+jj,jk,jl)=iom_mpp_read_var( tl_mpp, TRIM(cl_name), &
-                              &                                           td_dom=tl_segdom1(jk,jl) )
-
-                              !7-6 add attribute to variable
-                              tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
-                              CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
-
-                              tl_att=att_init('src_i-indices',(/tl_segdom1(jk,jl)%i_imin, tl_segdom1(jk,jl)%i_imax/))
-                              CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
-
-                              tl_att=att_init('src_j-indices',(/tl_segdom1(jk,jl)%i_jmin, tl_segdom1(jk,jl)%i_jmax/))
-                              CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
-                              
-                              ! clean structure
-                              CALL att_clean(tl_att)
-
-                              !7-7 use mask
-                              CALL create_bdy_use_mask(tl_segvar1(jvar+jj,jk,jl), tl_seglvl1(jk,jl,:))
-                           ENDDO
-                           
-                           !7-8 close mpp files
-                           CALL iom_mpp_close(tl_mpp)
-
-                           CALL mpp_clean(tl_mpp)
-
-                        ENDDO
-                     ENDIF
-                  ENDDO
-                  jvar=jvar+tl_multi%t_file(ji)%i_nvar
-               ELSE
-               !- interpolate value from coarse grid
-
-                  DO jk=1,ip_ncard
-                     IF( tl_bdy(jk)%l_use )THEN
-
-                        DO jl=1,tl_bdy(jk)%i_nseg
-                           !7-1 get coarse grid indices of this segment
-                           il_ind(:,:,:)=grid_get_coarse_index(tl_coord0, &
-                           &                                   tl_seglon1(jk,jl), tl_seglat1(jk,jl), &
-                           &                                   id_rho=il_rho(:) )
-
-                           IF( ANY(il_ind(:,:,:)==0) )THEN
-                              CALL logger_error("CREATE BOUNDARY: error computing "//&
-                              &                 " coarse grid indices")
+                           SELECT CASE(TRIM(tl_var0%c_point))
+                              CASE DEFAULT !'T'
+                                 jpoint=jp_T
+                              CASE('U')
+                                 jpoint=jp_U
+                              CASE('V')
+                                 jpoint=jp_V
+                              CASE('F')
+                                 jpoint=jp_F
+                           END SELECT
+
+                           tl_dom1=dom_copy(tl_segdom1(jpoint,jk,jl))
+                           tl_lvl1=var_copy(tl_seglvl1(jpoint,jk,jl))
+
+                           CALL create_boundary_get_coord( tl_coord1, tl_dom1, &
+                           &                               tl_var0%c_point,    &
+                           &                               tl_lon1, tl_lat1 )
+
+                           ! get coarse grid indices of this segment
+                           il_ind(:,:)=grid_get_coarse_index(tl_coord0, &
+                           &                                 tl_lon1, tl_lat1, &
+                           &                                 id_rho=il_rho(:) )
+
+                           IF( ANY(il_ind(:,:)==0) )THEN
+                              CALL logger_error("CREATE BOUNDARY: error "//&
+                              &  "computing coarse grid indices")
                            ELSE
-                              il_imin0=il_ind(1,1,1)
-                              il_imax0=il_ind(1,2,1)
-
-                              il_jmin0=il_ind(2,1,1)
-                              il_jmax0=il_ind(2,2,1)
-
-                              il_offset(:,:)=il_ind(:,:,2)
+                              il_imin0=il_ind(1,1)
+                              il_imax0=il_ind(1,2)
+
+                              il_jmin0=il_ind(2,1)
+                              il_jmax0=il_ind(2,2)
                            ENDIF
 
-                           !7-2 compute coarse grid segment domain
+                           il_offset(:,:)= grid_get_fine_offset( &
+                           &                    tl_coord0, &
+                           &                    il_imin0, il_jmin0,&
+                           &                    il_imax0, il_jmax0,&
+                           &                    tl_lon1%d_value(:,:,1,1),&
+                           &                    tl_lat1%d_value(:,:,1,1),&
+                           &                    il_rho(:),&
+                           &                    TRIM(tl_var0%c_point) )
+
+                           ! compute coarse grid segment domain
                            tl_dom0=dom_init( tl_coord0,         &
                            &                 il_imin0, il_imax0,&
                            &                 il_jmin0, il_jmax0 )
 
-                           !7-3 add extra band (if possible) to compute interpolation
+                           ! add extra band (if possible) to compute interpolation
                            CALL dom_add_extra(tl_dom0)
 
-                           !7-4 read variables on domain (ugly way to do it, have to work on it)
-                           !7-4-1 init mpp structure
-                           tl_mpp=mpp_init(tl_file)
- 
-                           !7-4-2 get processor to be used
-                           CALL mpp_get_use( tl_mpp, tl_dom0 )
-
-                           !7-4-3 open mpp files
-                           CALL iom_mpp_open(tl_mpp)
-
-                           ! check file dimension
-                           IF( ANY(tl_mpp%t_dim(1:2)%i_len /= tl_coord0%t_dim(1:2)%i_len) )THEN
-                              CALL logger_error("CREATE BOUNDARY INTERP: dimension of file "//&
-                              &  TRIM(tl_mpp%c_name)//" not conform to those of "//&
-                              &  TRIM(tl_coord0%c_name))
-                           ELSE
-
-                              ! for each variable of this file
-                              DO jj=1,tl_multi%t_file(ji)%i_nvar
-
-                                 cl_name=tl_multi%t_file(ji)%t_var(jj)%c_name
-                                 !7-4-4 read variable value on domain
-                                 tl_segvar1(jvar+jj,jk,jl)=iom_mpp_read_var( tl_mpp, TRIM(cl_name), &
-                                 &                                           td_dom=tl_dom0 )
-
-                                 !7-4-5 work on variable
-                                 CALL create_boundary_interp(tl_segvar1(jvar+jj,jk,jl), &
-                                 &                           il_rho(:), &
-                                 &                           il_offset(:,:) )
-
-                                 !7-4-6 remove extraband added to domain
-                                 CALL dom_del_extra( tl_segvar1(jvar+jj,jk,jl), tl_dom0, il_rho(:) )
-
-                                 !7-4-7 keep only useful point (width) 
-                                 ! interpolation could create more point than necessary
-                                 CALL boundary_clean_interp(tl_segvar1(jvar+jj,jk,jl), tl_bdy(jk) )
-
-                                 !7-4-8 add attribute to variable
-                                 tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
-                                 CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
-
-                                 tl_att=att_init('src_i-indices',(/tl_dom0%i_imin, tl_dom0%i_imax/))
-                                 CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
-
-                                 tl_att=att_init('src_j-indices',(/tl_dom0%i_jmin, tl_dom0%i_jmax/))
-                                 CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), tl_att)
-
-                                 ! clean structure
-                                 CALL att_clean(tl_att)
-
-                                 !7-4-9 use mask
-                                 CALL create_bdy_use_mask(tl_segvar1(jvar+jj,jk,jl), tl_seglvl1(jk,jl,:))
-                              ENDDO
+                           ! read variables on domain 
+                           ! open mpp files
+                           CALL iom_dom_open(tl_mpp, tl_dom0)
+
+                           cl_name=tl_var0%c_name
+                           ! read variable value on domain
+                           tl_segvar1(jvar+jj,jk,jl)= &
+                           &    iom_dom_read_var(tl_mpp, TRIM(cl_name), tl_dom0)
+
+                           ! work on variable
+                           CALL create_boundary_interp( &
+                           &                 tl_segvar1(jvar+jj,jk,jl),&
+                           &                 il_rho(:), il_offset(:,:) )
+
+                           ! remove extraband added to domain
+                           CALL dom_del_extra( tl_segvar1(jvar+jj,jk,jl), &
+                           &                   tl_dom0, il_rho(:) )
+
+                           ! use mask
+                           CALL create_boundary_use_mask( &
+                           &     tl_segvar1(jvar+jj,jk,jl), tl_lvl1)
+
+                           ! del extra point on fine grid
+                           CALL dom_del_extra( tl_segvar1(jvar+jj,jk,jl), &
+                           &                   tl_dom1 )
+                           ! clean extra point information on coarse grid domain
+                           CALL dom_clean_extra( tl_dom0 )
+
+                           ! add attribute to variable
+                           tl_att=att_init('src_file',&
+                           &  TRIM(fct_basename(tl_mpp%c_name)))
+                           CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), &
+                           &                 tl_att)
+
+                           ! use clean extra avt creer attribut
+                           tl_att=att_init('src_i-indices',&
+                           &  (/tl_dom0%i_imin, tl_dom0%i_imax/))
+                           CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), &
+                           &                 tl_att)
+
+                           tl_att=att_init('src_j-indices', &
+                           &  (/tl_dom0%i_jmin, tl_dom0%i_jmax/))
+                           CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), &
+                           &                 tl_att)
+
+                           IF( ANY(il_rho(:)/=1) )THEN
+                              tl_att=att_init("refinment_factor", &
+                              &               (/il_rho(jp_I),il_rho(jp_J)/))
+                              CALL var_move_att(tl_segvar1(jvar+jj,jk,jl), &
+                              &                 tl_att)
                            ENDIF
 
+                           ! clean structure
+                           CALL att_clean(tl_att)
+
+                           ! clean
                            CALL dom_clean(tl_dom0)
-
-                           !7-5 close mpp files
-                           CALL iom_mpp_close(tl_mpp)
-
-                           !7-6 clean structure
-                           CALL mpp_clean(tl_mpp)
-                        ENDDO
-                     ENDIF
-                  ENDDO
-                  jvar=jvar+tl_multi%t_file(ji)%i_nvar
-
-               ENDIF
-               CALL file_clean(tl_file)
-
+                           CALL dom_clean(tl_dom1)
+
+                           ! close mpp files
+                           CALL iom_dom_close(tl_mpp)
+
+                           ! clean structure
+                           CALL var_clean(tl_lon1)
+                           CALL var_clean(tl_lat1)
+                           CALL var_clean(tl_lvl1)
+
+                        ENDDO ! jj
+
+                        ! clean
+                        CALL var_clean(tl_var0)
+
+                     ENDDO ! jk
+               
+                  ENDIF
+               ENDDO ! jl
+
+               jvar=jvar+tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
+
+            !- end of interpolate value from coarse grid
             ENDIF
+
+            ! clean
+            CALL mpp_clean(tl_mpp)
+
+         !- end of use file to fill variable
          ENDIF
       ENDDO
    ENDIF
+
    IF( jvar /= tl_multi%i_nvar )THEN
       CALL logger_error("CREATE BOUNDARY: it seems some variable can not be read")
    ENDIF
 
-   !8- concatenate file
-   ALLOCATE( tl_lon1(ip_ncard) )
-   ALLOCATE( tl_lat1(ip_ncard) )
-   ALLOCATE( tl_var(tl_multi%i_nvar,ip_ncard) )
-
-   DO jk=1,ip_ncard
-      IF( tl_bdy(jk)%l_use )THEN
+   CALL var_clean(tl_seglvl1(:,:,:))
+   DEALLOCATE( tl_seglvl1 )
+
+   ! write file for each segment of each boundary
+   DO jl=1,ip_ncard
+      IF( tl_bdy(jl)%l_use )THEN
 
          SELECT CASE(TRIM(tl_bdy(jk)%c_card))
@@ -625,153 +906,169 @@
          END SELECT   
 
-         DO jl=1,tl_bdy(jk)%i_nseg
-            !- concatenate variable
-            IF( jl == 1 )THEN
-               tl_lon1(jk)=tl_seglon1(jk,jl)
-               tl_lat1(jk)=tl_seglat1(jk,jl)
-               DO jvar=1,tl_multi%i_nvar
-                  tl_var(jvar,jk)=tl_segvar1(jvar,jk,jl)
-               ENDDO
+         DO jk=1,tl_bdy(jl)%i_nseg
+            !- 
+            CALL create_boundary_get_coord( tl_coord1, tl_segdom1(jp_T,jk,jl),&
+            &                               'T', tl_lon1, tl_lat1 )
+
+            ! del extra point on fine grid
+            CALL dom_del_extra( tl_lon1, tl_segdom1(jp_T,jk,jl) )
+            CALL dom_del_extra( tl_lat1, tl_segdom1(jp_T,jk,jl) )
+
+            ! clean
+            DO jpoint=1,ip_npoint
+               CALL dom_clean(tl_segdom1(jpoint,jk,jl))
+            ENDDO
+
+            ! swap array
+            CALL boundary_swap(tl_lon1, tl_bdy(jl))
+            CALL boundary_swap(tl_lat1, tl_bdy(jl))
+            DO jvar=1,tl_multi%i_nvar
+               CALL boundary_swap(tl_segvar1(jvar,jk,jl), tl_bdy(jl))
+
+               ! use additional request
+               ! forced min and max value
+               CALL var_limit_value(tl_segvar1(jvar,jk,jl))
+
+               ! filter
+               CALL filter_fill_value(tl_segvar1(jvar,jk,jl))
+
+               ! extrapolate
+               CALL extrap_fill_value( tl_segvar1(jvar,jk,jl), &
+               &                       id_iext=in_extrap,      &
+               &                       id_jext=in_extrap,      &
+               &                       id_kext=in_extrap )
+
+            ENDDO
+
+            ! create file
+            ! create file structure
+            ! set file namearray of level variable structure
+            IF( ASSOCIATED(tl_time%d_value) )THEN
+               cl_fmt="('y',i0.4,'m',i0.2,'d',i0.2)"
+               cl_date=date_print( var_to_date(tl_time), cl_fmt ) 
+
+               cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
+               &                                TRIM(tl_bdy(jl)%c_card), jk, TRIM(cl_date) )
             ELSE
-               tl_lon1(jk)=var_concat(tl_lon1(jk),tl_seglon1(jk,jl),DIM=il_dim)
-               tl_lat1(jk)=var_concat(tl_lat1(jk),tl_seglat1(jk,jl),DIM=il_dim)
-               DO jvar=1,tl_multi%i_nvar
-                  tl_var(jvar,jk)=var_concat(tl_var(jvar,jk),tl_segvar1(jvar,jk,jl),DIM=il_dim)
-               ENDDO
-            ENDIF   
-         ENDDO
-
-         ! swap array
-         CALL boundary_swap(tl_lon1(jk), tl_bdy(jk))
-         CALL boundary_swap(tl_lat1(jk), tl_bdy(jk))
-         DO jvar=1,tl_multi%i_nvar
-            CALL boundary_swap(tl_var(jvar,jk), tl_bdy(jk))
-
-            !9- use additional request
-
-            !9-1 forced min and max value
-            CALL var_limit_value(tl_var(jvar,jk))
-
-            !9-2 filter
-            CALL filter_fill_value(tl_var(jvar,jk))
-
-            !9-3 extrapolate
-            CALL extrap_fill_value(tl_var(jvar,jk), id_iext=in_extrap, &
-            &                                       id_jext=in_extrap, &
-            &                                       id_kext=in_extrap)
-
-         ENDDO
+               cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
+               &                                TRIM(tl_bdy(jl)%c_card), jk )
+            ENDIF
+            ! 
+            tl_fileout=file_init(TRIM(cl_bdyout),id_perio=in_perio1)
+
+            ! add dimension
+            tl_dim(:)=var_max_dim(tl_segvar1(:,jk,jl))
+
+            CALL dim_unorder(tl_dim(:))
+            SELECT CASE(TRIM(tl_bdy(jl)%c_card))
+               CASE DEFAULT ! 'north','south'
+                  cl_dimorder='xyzt'
+                  CALL dim_reorder(tl_dim(:),TRIM(cl_dimorder))
+               CASE('east','west')
+                  cl_dimorder='yxzt'
+                  CALL dim_reorder(tl_dim(:),TRIM(cl_dimorder))
+                  ! reorder coordinates dimension
+                  CALL var_reorder(tl_lon1,TRIM(cl_dimorder))
+                  CALL var_reorder(tl_lat1,TRIM(cl_dimorder))
+                  ! reorder other variable dimension
+                  DO jvar=1,tl_multi%i_nvar
+                     CALL var_reorder(tl_segvar1(jvar,jk,jl),TRIM(cl_dimorder))
+                  ENDDO
+            END SELECT
+
+            DO ji=1,ip_maxdim
+               IF( tl_dim(ji)%l_use ) CALL file_add_dim(tl_fileout, tl_dim(ji))
+            ENDDO
+
+            ! add variables
+            IF( ALL( tl_dim(1:2)%l_use ) )THEN
+               ! add longitude
+               CALL file_add_var(tl_fileout, tl_lon1)
+               CALL var_clean(tl_lon1)
+
+               ! add latitude
+               CALL file_add_var(tl_fileout, tl_lat1)
+               CALL var_clean(tl_lat1)
+            ENDIF
+            
+            IF( tl_dim(3)%l_use )THEN
+               ! add depth
+               CALL file_add_var(tl_fileout, tl_depth)
+            ENDIF
+
+            IF( tl_dim(4)%l_use )THEN
+               ! add time
+               CALL file_add_var(tl_fileout, tl_time)
+            ENDIF
+
+            ! add other variable
+            DO jvar=1,tl_multi%i_nvar
+               CALL file_add_var(tl_fileout, tl_segvar1(jvar,jk,jl))
+               CALL var_clean(tl_segvar1(jvar,jk,jl))
+            ENDDO
+
+            ! add some attribute
+            tl_att=att_init("Created_by","SIREN create_boundary")
+            CALL file_add_att(tl_fileout, tl_att)
+
+            cl_date=date_print(date_now())
+            tl_att=att_init("Creation_date",cl_date)
+            CALL file_add_att(tl_fileout, tl_att)
+
+            ! add shift on north and east boundary
+            ! boundary compute on T point but express on U or V point
+            SELECT CASE(TRIM(tl_bdy(jl)%c_card))
+            CASE DEFAULT ! 'south','west'
+               il_shift=0
+            CASE('north','east')
+               il_shift=1
+            END SELECT
+
+            ! add indice of velocity row or column
+            tl_att=att_init('bdy_ind',tl_bdy(jl)%t_seg(jk)%i_index-il_shift)
+            CALL file_move_att(tl_fileout, tl_att)
+
+            ! add width of the relaxation zone
+            tl_att=att_init('bdy_width',tl_bdy(jl)%t_seg(jk)%i_width)
+            CALL file_move_att(tl_fileout, tl_att)
+            
+            ! add indice of segment start 
+            tl_att=att_init('bdy_deb',tl_bdy(jl)%t_seg(jk)%i_first)
+            CALL file_move_att(tl_fileout, tl_att)
+            
+            ! add indice of segment end 
+            tl_att=att_init('bdy_end',tl_bdy(jl)%t_seg(jk)%i_last)
+            CALL file_move_att(tl_fileout, tl_att)
+                           
+            ! clean
+            CALL att_clean(tl_att)
+
+            ! create file
+            CALL iom_create(tl_fileout)
+
+            ! write file
+            CALL iom_write_file(tl_fileout)
+
+            ! close file
+            CALL iom_close(tl_fileout)
+            CALL file_clean(tl_fileout)
+
+         ENDDO ! jk
+
       ENDIF
-   ENDDO
-
-   DEALLOCATE( tl_seglon1 )
-   DEALLOCATE( tl_seglat1 )
+      ! clean
+      CALL boundary_clean(tl_bdy(jl))
+   ENDDO !jl
+
+   ! clean
+   IF( ASSOCIATED(tl_depth%d_value) ) CALL var_clean(tl_depth)
+   IF( ASSOCIATED(tl_time%d_value) )   CALL var_clean(tl_time)
    DEALLOCATE( tl_segdom1 )
    DEALLOCATE( tl_segvar1 )
-   DEALLOCATE( tl_seglvl1 )
-   
-   DO jk=1,ip_ncard
-      IF( tl_bdy(jk)%l_use )THEN
-
-         !10   create file
-         !10-1 create file structure
-         !10-1-1 set file name
-         cl_bdyout=boundary_set_filename( TRIM(cn_fileout), &
-         &                                TRIM(tl_bdy(jk)%c_card) )
-         !10-1-2 
-         tl_fileout=file_init(TRIM(cl_bdyout),id_perio=in_perio1)
-
-         !10-2 add dimension
-         tl_dim(:)=var_max_dim(tl_var(:,jk))
-
-         DO ji=1,ip_maxdim
-            IF( tl_dim(ji)%l_use ) CALL file_add_dim(tl_fileout, tl_dim(ji))
-         ENDDO
-
-         !10-3 add variables
-         IF( ALL( tl_dim(1:2)%l_use ) )THEN
-            ! add longitude
-            CALL file_add_var(tl_fileout, tl_lon1(jk))
-            CALL var_clean(tl_lon1(jk))
-
-            ! add latitude
-            CALL file_add_var(tl_fileout, tl_lat1(jk))
-            CALL var_clean(tl_lat1(jk))
-         ENDIF
-         
-         IF( tl_dim(3)%l_use )THEN
-            ! add depth
-            CALL file_add_var(tl_fileout, tl_depth)
-         ENDIF
-
-         IF( tl_dim(4)%l_use )THEN
-            ! add time
-            CALL file_add_var(tl_fileout, tl_time)
-         ENDIF
-
-         ! add other variable
-         DO jvar=1,tl_multi%i_nvar
-            !IF( TRIM(tl_var(jvar,jk)%c_name) /= 'X' .AND. &
-            !&   TRIM(tl_var(jvar,jk)%c_name) /= 'Y' )THEN
-               CALL file_add_var(tl_fileout, tl_var(jvar,jk))
-            !ENDIF
-            CALL var_clean(tl_var(jvar,jk))
-         ENDDO
-
-         !10-4 add some attribute
-         tl_att=att_init("Created_by","SIREN create_boundary")
-         CALL file_add_att(tl_fileout, tl_att)
-
-         cl_date=date_print(date_now())
-         tl_att=att_init("Creation_date",cl_date)
-         CALL file_add_att(tl_fileout, tl_att)
-
-         ! add attribute periodicity
-         il_attid=0
-         IF( ASSOCIATED(tl_fileout%t_att) )THEN
-            il_attid=att_get_id(tl_fileout%t_att(:),'periodicity')
-         ENDIF
-         IF( tl_coord1%i_perio >= 0 .AND. il_attid == 0 )THEN
-            tl_att=att_init('periodicity',tl_coord1%i_perio)
-            CALL file_add_att(tl_fileout,tl_att)
-         ENDIF
-      
-         il_attid=0
-         IF( ASSOCIATED(tl_fileout%t_att) )THEN
-            il_attid=att_get_id(tl_fileout%t_att(:),'ew_overlap')
-         ENDIF
-         IF( tl_coord1%i_ew >= 0 .AND. il_attid == 0 )THEN
-            tl_att=att_init('ew_overlap',tl_coord1%i_ew)
-            CALL file_add_att(tl_fileout,tl_att)
-         ENDIF
-
-         !10-5 create file
-         CALL iom_create(tl_fileout)
-
-         !10-6 write file
-         CALL iom_write_file(tl_fileout)
-
-         !10-7 close file
-         CALL iom_close(tl_fileout)
-         CALL file_clean(tl_fileout)
-
-      ENDIF
-   ENDDO
-   DEALLOCATE( tl_lon1 ) 
-   DEALLOCATE( tl_lat1 ) 
-   DEALLOCATE( tl_var ) 
-
-   !11- close file
-   CALL iom_close(tl_bathy1)
-   CALL iom_close(tl_coord1)
-   CALL iom_close(tl_coord0)
-
-   !12- clean
-   CALL var_clean(tl_depth)
-   CALL var_clean(tl_time)
-   CALL file_clean(tl_fileout)
-   CALL file_clean(tl_bathy1)
-   CALL file_clean(tl_coord1)
-   CALL file_clean(tl_coord0)
+
+   CALL mpp_clean(tl_coord1)
+   CALL mpp_clean(tl_coord0)
+
+   CALL multi_clean(tl_multi)
 
    ! close log file
@@ -779,19 +1076,19 @@
    CALL logger_close()
 
-!> @endcode
 CONTAINS
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine compute boundary domain for each grid point (T,U,V,F) 
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - take into account grid point to compute boundary indices
    !>
-   !> @author J.Paul
-   !> - 2013- Initial Version
-   !>
-   !> @param[in] 
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] td_bathy1 file structure 
+   !> @param[in] td_bdy    boundary structure
+   !> @param[in] id_seg    segment indice 
+   !> @return array of domain structure 
+   !-------------------------------------------------------------------
    FUNCTION create_boundary_get_dom( td_bathy1, td_bdy, id_seg )
 
@@ -799,10 +1096,10 @@
 
       ! Argument
-      TYPE(TFILE), INTENT(IN   ) :: td_bathy1
+      TYPE(TMPP) , INTENT(IN   ) :: td_bathy1
       TYPE(TBDY) , INTENT(IN   ) :: td_bdy
       INTEGER(i4), INTENT(IN   ) :: id_seg
 
       ! function
-      TYPE(TDOM) :: create_boundary_get_dom
+      TYPE(TDOM), DIMENSION(ip_npoint) :: create_boundary_get_dom
 
       ! local variable
@@ -812,60 +1109,133 @@
       INTEGER(i4) :: il_jmax1
 
-      TYPE(TFILE) :: tl_bathy1
-      
+      INTEGER(i4) :: il_imin
+      INTEGER(i4) :: il_imax
+      INTEGER(i4) :: il_jmin
+      INTEGER(i4) :: il_jmax
+
+      INTEGER(i4), DIMENSION(ip_npoint) :: il_ishift
+      INTEGER(i4), DIMENSION(ip_npoint) :: il_jshift
+
       ! loop indices
-      INTEGER(i4) :: jl
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jk
       !----------------------------------------------------------------
-      jl=id_seg
-
-      !1- get boundary definition
+      ! init
+      jk=id_seg
+
+      il_ishift(:)=0
+      il_jshift(:)=0
+
+      ! get boundary definition
       SELECT CASE(TRIM(td_bdy%c_card))
          CASE('north')
 
-            il_imin1=td_bdy%t_seg(jl)%i_first
-            il_imax1=td_bdy%t_seg(jl)%i_last 
-            il_jmin1=td_bdy%t_seg(jl)%i_index-(td_bdy%t_seg(jl)%i_width-1)
-            il_jmax1=td_bdy%t_seg(jl)%i_index
+            il_imin1=td_bdy%t_seg(jk)%i_first
+            il_imax1=td_bdy%t_seg(jk)%i_last 
+            il_jmin1=td_bdy%t_seg(jk)%i_index-(td_bdy%t_seg(jk)%i_width-1)
+            il_jmax1=td_bdy%t_seg(jk)%i_index
+
+            il_jshift(jp_V)=-1
+            il_jshift(jp_F)=-1
 
          CASE('south')
 
-            il_imin1=td_bdy%t_seg(jl)%i_first
-            il_imax1=td_bdy%t_seg(jl)%i_last 
-            il_jmin1=td_bdy%t_seg(jl)%i_index
-            il_jmax1=td_bdy%t_seg(jl)%i_index+(td_bdy%t_seg(jl)%i_width-1)
+            il_imin1=td_bdy%t_seg(jk)%i_first
+            il_imax1=td_bdy%t_seg(jk)%i_last 
+            il_jmin1=td_bdy%t_seg(jk)%i_index
+            il_jmax1=td_bdy%t_seg(jk)%i_index+(td_bdy%t_seg(jk)%i_width-1)
 
          CASE('east')
 
-            il_imin1=td_bdy%t_seg(jl)%i_index-(td_bdy%t_seg(jl)%i_width-1)
-            il_imax1=td_bdy%t_seg(jl)%i_index
-            il_jmin1=td_bdy%t_seg(jl)%i_first
-            il_jmax1=td_bdy%t_seg(jl)%i_last 
+            il_imin1=td_bdy%t_seg(jk)%i_index-(td_bdy%t_seg(jk)%i_width-1)
+            il_imax1=td_bdy%t_seg(jk)%i_index
+            il_jmin1=td_bdy%t_seg(jk)%i_first
+            il_jmax1=td_bdy%t_seg(jk)%i_last 
+
+            il_ishift(jp_U)=-1
+            il_ishift(jp_F)=-1
 
          CASE('west')
 
-            il_imin1=td_bdy%t_seg(jl)%i_index
-            il_imax1=td_bdy%t_seg(jl)%i_index+(td_bdy%t_seg(jl)%i_width-1)
-            il_jmin1=td_bdy%t_seg(jl)%i_first
-            il_jmax1=td_bdy%t_seg(jl)%i_last 
+            il_imin1=td_bdy%t_seg(jk)%i_index
+            il_imax1=td_bdy%t_seg(jk)%i_index+(td_bdy%t_seg(jk)%i_width-1)
+            il_jmin1=td_bdy%t_seg(jk)%i_first
+            il_jmax1=td_bdy%t_seg(jk)%i_last 
 
       END SELECT         
 
-      !2 -read fine grid domain
-      tl_bathy1=td_bathy1
-      CALL iom_open(tl_bathy1)
-
-      !2-1 compute domain
-      create_boundary_get_dom=dom_init( tl_bathy1,         &
-      &                                 il_imin1, il_imax1,&
-      &                                 il_jmin1, il_jmax1 )
-
-      !2-2 close file
-      CALL iom_close(tl_bathy1)
+      !-read fine grid domain
+      DO ji=1,ip_npoint
+
+         ! shift domain
+         il_imin=il_imin1+il_ishift(ji)
+         il_imax=il_imax1+il_ishift(ji)
+
+         il_jmin=il_jmin1+il_jshift(ji)
+         il_jmax=il_jmax1+il_jshift(ji)
+
+         ! compute domain
+         create_boundary_get_dom(ji)=dom_init( td_bathy1,       &
+         &                                     il_imin, il_imax,&
+         &                                     il_jmin, il_jmax,&
+         &                                     TRIM(td_bdy%c_card) )
+
+      ENDDO
 
    END FUNCTION create_boundary_get_dom
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine get coordinates over boudnary domain
+   !> 
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !> @date September, 2014 - take into account grid point
+   !>
+   !> @param[in] td_coord1 coordinates file structure
+   !> @param[in] td_dom1   boundary domain structure
+   !> @param[in] cd_point  grid point
+   !> @param[out] td_lon1  longitude variable structure
+   !> @param[out] td_lat1  latitude variable structure
+   !-------------------------------------------------------------------
+   SUBROUTINE create_boundary_get_coord( td_coord1, td_dom1, cd_point, &
+   &                                     td_lon1, td_lat1 )
+
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TMPP)      , INTENT(IN   ) :: td_coord1
+      TYPE(TDOM)      , INTENT(IN   ) :: td_dom1
+      TYPE(TVAR)      , INTENT(  OUT) :: td_lon1
+      TYPE(TVAR)      , INTENT(  OUT) :: td_lat1 
+      CHARACTER(LEN=*), INTENT(IN   ), OPTIONAL :: cd_point
+
+      ! local variable
+      TYPE(TMPP)  :: tl_coord1
+      
+      CHARACTER(LEN=lc) :: cl_name
+      ! loop indices
+      !----------------------------------------------------------------
+      !read variables on domain (ugly way to do it, have to work on it)
+      ! init mpp structure
+      tl_coord1=mpp_copy(td_coord1)
+      
+      ! open mpp files
+      CALL iom_dom_open(tl_coord1, td_dom1)
+
+      ! read variable value on domain
+      WRITE(cl_name,*) 'longitude_'//TRIM(cd_point)
+      td_lon1=iom_dom_read_var( tl_coord1, TRIM(cl_name), td_dom1)
+      WRITE(cl_name,*) 'latitude_'//TRIM(cd_point)
+      td_lat1=iom_dom_read_var( tl_coord1, TRIM(cl_name), td_dom1)
+
+      ! close mpp files
+      CALL iom_dom_close(tl_coord1)
+
+      ! clean structure
+      CALL mpp_clean(tl_coord1)
+
+   END SUBROUTINE create_boundary_get_coord
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine interpolate variable over boundary
    !> 
    !> @details 
@@ -874,247 +1244,10 @@
    !> - Nov, 2013- Initial Version
    !>
-   !> @param[in] 
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE create_boundary_get_coord( td_bathy1, td_dom1, &
-   &                                     td_lon1, td_lat1 )
-
-      IMPLICIT NONE
-
-      ! Argument
-      TYPE(TFILE), INTENT(IN   ) :: td_bathy1
-      TYPE(TDOM) , INTENT(IN   ) :: td_dom1
-      TYPE(TVAR) , INTENT(  OUT) :: td_lon1
-      TYPE(TVAR) , INTENT(  OUT) :: td_lat1 
-
-      ! local variable
-      TYPE(TFILE) :: tl_bathy1
-      
-      TYPE(TMPP)  :: tl_mppbathy1
-
-      ! loop indices
-      !----------------------------------------------------------------
-      !read variables on domain (ugly way to do it, have to work on it)
-
-      !1 init mpp structure
-      tl_bathy1=td_bathy1
-      tl_mppbathy1=mpp_init(tl_bathy1)
-      
-      CALL file_clean(tl_bathy1)
-
-      !2 get processor to be used
-      CALL mpp_get_use( tl_mppbathy1, td_dom1 )
-
-      !3 open mpp files
-      CALL iom_mpp_open(tl_mppbathy1)
-
-      !4 read variable value on domain
-      td_lon1=iom_mpp_read_var(tl_mppbathy1,'longitude',td_dom=td_dom1)
-      td_lat1=iom_mpp_read_var(tl_mppbathy1,'latitude' ,td_dom=td_dom1)
-
-      !5 close mpp files
-      CALL iom_mpp_close(tl_mppbathy1)
-
-      !6 clean structure
-      CALL mpp_clean(tl_mppbathy1)
-
-   END SUBROUTINE create_boundary_get_coord
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] 
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE create_boundary_get_mask( td_level1, td_dom1, &
-   &                                    td_var, td_mask )
-
-      IMPLICIT NONE
-
-      ! Argument
-      TYPE(TFILE), INTENT(IN   ) :: td_level1
-      TYPE(TDOM) , INTENT(IN   ) :: td_dom1
-      TYPE(TVAR) , INTENT(IN   ) :: td_var
-      TYPE(TVAR) , INTENT(  OUT) :: td_mask 
-
-      ! local variable
-      TYPE(TFILE) :: tl_level1
-      
-      TYPE(TMPP)  :: tl_mpplevel1
-
-      ! loop indices
-      !----------------------------------------------------------------
-      !read variables on domain (ugly way to do it, have to work on it)
-
-      !1 init mpp structure
-      tl_level1=td_level1
-      tl_mpplevel1=mpp_init(tl_level1)
-      
-      CALL file_clean(tl_level1)
-
-      !2 get processor to be used
-      CALL mpp_get_use( tl_mpplevel1, td_dom1 )
-
-      !3 open mpp files
-      CALL iom_mpp_open(tl_mpplevel1)
-
-      !4 read variable value on domain
-      SELECT CASE(TRIM(td_var%c_point))
-      CASE('T')
-         td_mask=iom_mpp_read_var(tl_mpplevel1,'tlevel',td_dom=td_dom1)
-      CASE('U')
-         td_mask=iom_mpp_read_var(tl_mpplevel1,'ulevel',td_dom=td_dom1)
-      CASE('V')
-         td_mask=iom_mpp_read_var(tl_mpplevel1,'vlevel',td_dom=td_dom1)
-      CASE('F')
-         td_mask=iom_mpp_read_var(tl_mpplevel1,'flevel',td_dom=td_dom1)
-      END SELECT
-
-      !5 close mpp files
-      CALL iom_mpp_close(tl_mpplevel1)
-
-      !6 clean structure
-      CALL mpp_clean(tl_mpplevel1)
-
-   END SUBROUTINE create_boundary_get_mask
-   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief
-!   !> This subroutine
-!   !> 
-!   !> @details 
-!   !>
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !>
-!   !> @param[in] 
-!   !> @todo 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   SUBROUTINE create_boundary_get_var( td_var, td_bdy,      &
-!   &                                   td_coord0, td_dom0,  &
-!   &                                   td_mask,             &
-!   &                                   id_rhoi, id_rhoj )
-!
-!      IMPLICIT NONE
-!
-!      ! Argument
-!      TYPE(TVAR) , INTENT(INOUT) :: td_var
-!      TYPE(TBDY) , INTENT(IN   ) :: td_bdy
-!      TYPE(TFILE), INTENT(IN   ) :: td_coord0
-!      TYPE(TDOM) , INTENT(IN   ) :: td_dom0
-!      TYPE(TVAR) , INTENT(IN   ) :: td_mask
-!      INTEGER(I4), INTENT(IN   ) :: id_rhoi
-!      INTEGER(I4), INTENT(IN   ) :: id_rhoj
-!
-!      ! local variable
-!      TYPE(TVAR)  :: tl_var0
-!
-!      TYPE(TDOM)  :: tl_dom0
-!
-!      TYPE(TFILE) :: tl_file0
-!
-!      TYPE(TMPP)  :: tl_mppfile0
-!
-!      ! loop indices
-!      INTEGER(i4) :: jk
-!      INTEGER(i4) :: jl
-!      !----------------------------------------------------------------
-!
-!      CALL logger_debug("CREATE BOUNDARY INTERP: read coarse grid"// TRIM(td_var%c_file) )
-!      !1- read coarse grid variable on domain
-!      tl_file0=file_init( TRIM(td_var%c_file) )
-!
-!      !2- init
-!      tl_dom0=td_dom0
-!
-!      !3- add extra band (if possible) to compute interpolation
-!      CALL dom_add_extra(tl_dom0)
-!
-!      !4- read variables on domain (ugly way to do it, have to work on it)
-!      !4-1 init mpp structure
-!      tl_mppfile0=mpp_init(tl_file0)
-! 
-!      CALL file_clean(tl_file0)
-!
-!      !4-2 get processor to be used
-!      CALL mpp_get_use( tl_mppfile0, tl_dom0 )
-!
-!      !4-3 open mpp files
-!      CALL iom_mpp_open(tl_mppfile0)
-!
-!      ! check file dimension
-!      IF( ANY(tl_mppfile0%t_dim(1:2)%i_len /= td_coord0%t_dim(1:2)%i_len) )THEN
-!         CALL logger_error("CREATE BOUNDARY INTERP: dimension of file "//&
-!         &  TRIM(tl_mppfile0%c_name)//" not conform to those of "//&
-!         &  TRIM(td_coord0%c_name))
-!      ELSE
-!
-!         !4-4 read variable value on domain
-!         tl_var0=iom_mpp_read_var( tl_mppfile0, TRIM(td_var%c_name), &
-!         &                         td_dom=tl_dom0 )
-!
-!         !5- work on variable
-!         CALL create_boundary_interp(tl_var0, id_rhoi, id_rhoj )
-!         
-!         !6- remove extraband added to domain
-!         CALL dom_del_extra( tl_var0, tl_dom0, id_rhoi, id_rhoj )
-!
-!         !6-1 remove extraband added to domain
-!         CALL dom_clean_extra( tl_dom0 )         
-!
-!         !7- keep only useful point (width) 
-!         ! interpolation could create more point than necessary
-!         CALL boundary_clean_interp(tl_var0, td_bdy )
-!
-!         !8- forced min and max value
-!         CALL var_limit_value(tl_var0)
-!
-!         !9- filter
-!         CALL filter_fill_value(tl_var0)
-!
-!         td_var=tl_var0
-!
-!         CALL var_clean(tl_var0)
-!      ENDIF
-!
-!      !4-5 close mpp files
-!      CALL iom_mpp_close(tl_mppfile0)
-!
-!      !4-6 clean structure
-!      CALL mpp_clean(tl_mppfile0)
-!      
-!      !5- apply mask
-!      DO jl=1,td_var%t_dim(4)%i_len
-!         DO jk=1,td_var%t_dim(3)%i_len
-!            WHERE( td_mask%d_value(:,:,1,1) < jk )
-!               td_var%d_value(:,:,jk,jl)=td_var%d_fill
-!            END WHERE
-!         ENDDO
-!      ENDDO
-!
-!   END SUBROUTINE create_boundary_get_var
-!   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] 
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[inout] td_var variable structure 
+   !> @param[in] id_rho    array of refinment factor
+   !> @param[in] id_offset array of offset between fine and coarse grid
+   !> @param[in] id_iext   i-direction size of extra bands (default=im_minext)
+   !> @param[in] id_jext   j-direction size of extra bands (default=im_minext)
+   !-------------------------------------------------------------------
    SUBROUTINE create_boundary_interp( td_var,           &
    &                                  id_rho,           &
@@ -1134,13 +1267,8 @@
 
       ! local variable
-      TYPE(TVAR)  :: tl_var
-
       INTEGER(i4) :: il_iext
       INTEGER(i4) :: il_jext
       ! loop indices
       !----------------------------------------------------------------
-
-      ! copy variable
-      tl_var=td_var
 
       !WARNING: at least two extrabands are required for cubic interpolation
@@ -1163,26 +1291,19 @@
       ENDIF
 
-      !2- work on variable
-      !2-0 add extraband
-      CALL extrap_add_extrabands(tl_var, il_iext, il_jext)
-
-      !2-1 extrapolate variable
-      CALL extrap_fill_value( tl_var, id_iext=il_iext, id_jext=il_jext )
-
-      !2-2 interpolate Bathymetry
-      CALL interp_fill_value( tl_var, id_rho(:), &
+      ! work on variable
+      ! add extraband
+      CALL extrap_add_extrabands(td_var, il_iext, il_jext)
+
+      ! extrapolate variable
+      CALL extrap_fill_value( td_var, id_iext=il_iext, id_jext=il_jext )
+
+      ! interpolate Bathymetry
+      CALL interp_fill_value( td_var, id_rho(:), &
       &                       id_offset=id_offset(:,:) )
 
-      !2-3 remove extraband
-      CALL extrap_del_extrabands(tl_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
-
-      !3- save result
-      td_var=tl_var
-
-      ! clean variable structure
-      CALL var_clean(tl_var)
+      ! remove extraband
+      CALL extrap_del_extrabands(td_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
 
    END SUBROUTINE create_boundary_interp
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -1192,30 +1313,26 @@
    !> A variable is create with the same name that the input variable, 
    !> and with dimension of the coordinate file. 
-   !> Then the variable table of value is split into equal subdomain.
+   !> Then the variable array of value is split into equal subdomain.
    !> Each subdomain is fill with the linked value of the matrix.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !>
-   !> @param[in] td_var : variable structure 
-   !> @param[in] td_dom : domain structure 
-   !> @param[in] td_coord : coordinate 
+   !> @param[in] td_var    variable structure 
+   !> @param[in] td_dom    domain structure 
+   !> @param[in] id_nlevel number of levels 
    !> @return variable structure 
    !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create_bdy_matrix(td_var, td_dom, td_coord)
+   FUNCTION create_boundary_matrix(td_var, td_dom, id_nlevel)
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(IN) :: td_var
-      TYPE(TDOM) , INTENT(IN) :: td_dom
-      TYPE(TFILE), INTENT(IN) :: td_coord
+      TYPE(TVAR) ,               INTENT(IN) :: td_var
+      TYPE(TDOM) ,               INTENT(IN) :: td_dom
+      INTEGER(i4),               INTENT(IN) :: id_nlevel
 
       ! function
-      TYPE(TVAR) :: create_bdy_matrix
+      TYPE(TVAR) :: create_boundary_matrix
 
       ! local variable
-      INTEGER(i4)                                        :: il_ighost
-      INTEGER(i4)                                        :: il_jghost
-      INTEGER(i4)      , DIMENSION(2)                    :: il_xghost
       INTEGER(i4)      , DIMENSION(3)                    :: il_dim
       INTEGER(i4)      , DIMENSION(3)                    :: il_size
@@ -1228,7 +1345,4 @@
       REAL(dp)         , DIMENSION(:,:,:,:), ALLOCATABLE :: dl_value
 
-      TYPE(TVAR)                                         :: tl_lon
-      TYPE(TVAR)                                         :: tl_lat
-      TYPE(TVAR)                                         :: tl_var
       TYPE(TDIM)       , DIMENSION(ip_maxdim)            :: tl_dim
 
@@ -1239,25 +1353,12 @@
       !----------------------------------------------------------------
 
-      !1- read output grid
-      tl_lon=iom_read_var(td_coord,'longitude')
-      tl_lat=iom_read_var(td_coord,'latitude')
-
-      !2- look for ghost cell
-      il_xghost(:)=grid_get_ghost( tl_lon, tl_lat )
-
-      il_ighost=il_xghost(1)*ig_ghost
-      il_jghost=il_xghost(2)*ig_ghost
-      
-      !3- write value on grid
-      !3-1 get matrix dimension
+      ! write value on grid
+      ! get matrix dimension
       il_dim(:)=td_var%t_dim(1:3)%i_len
-      !3-2 output dimension
-      tl_dim(:)=tl_lon%t_dim(:)
-
-      ! remove ghost cell
-      tl_dim(1)%i_len=tl_dim(1)%i_len - 2*il_xghost(1)*ig_ghost
-      tl_dim(2)%i_len=tl_dim(2)%i_len - 2*il_xghost(2)*ig_ghost
-
-      !3-3 split output domain in N subdomain depending of matrix dimension 
+
+      tl_dim(jp_I:jp_J)=dim_copy(td_dom%t_dim(jp_I:jp_J))
+      tl_dim(jp_K)%i_len=id_nlevel
+
+      ! split output domain in N subdomain depending of matrix dimension 
       il_size(:) = tl_dim(1:3)%i_len / il_dim(:)
       il_rest(:) = MOD(tl_dim(1:3)%i_len, il_dim(:))
@@ -1271,5 +1372,4 @@
       il_ishape(il_dim(1)+1)=il_ishape(il_dim(1)+1)+il_rest(1)
       
-
       ALLOCATE( il_jshape(il_dim(2)+1) )
       il_jshape(:)=0
@@ -1288,5 +1388,5 @@
       il_kshape(il_dim(3)+1)=il_kshape(il_dim(3)+1)+il_rest(3)
 
-      !3-3 write ouput table of value 
+      ! write ouput array of value 
       ALLOCATE(dl_value( tl_dim(1)%i_len, &
       &                  tl_dim(2)%i_len, &
@@ -1309,37 +1409,29 @@
       ENDDO
 
-      !3-4 initialise variable with value
-      tl_var=var_init(TRIM(td_var%c_name),dl_value(:,:,:,:))
+      ! initialise variable with value
+      create_boundary_matrix=var_init(TRIM(td_var%c_name),dl_value(:,:,:,:))
 
       DEALLOCATE(dl_value)
 
-      !4- add ghost cell
-      CALL grid_add_ghost(tl_var,il_ighost,il_jghost)
-
-      !5- save result
-      create_bdy_matrix=tl_var
-
-   END FUNCTION create_bdy_matrix
-   !> @endcode
+   END FUNCTION create_boundary_matrix
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine use mask to filled land point with _FillValue
    !> 
    !> @details 
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !>
-   !> @param[in] 
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE create_bdy_use_mask( td_var, td_mask )
+   !> @param[inout] td_var variable structure 
+   !> @param[in] td_mask   mask variable structure
+   !-------------------------------------------------------------------
+   SUBROUTINE create_boundary_use_mask( td_var, td_mask )
 
       IMPLICIT NONE
 
       ! Argument
-      TYPE(TVAR)              , INTENT(INOUT) :: td_var
-      TYPE(TVAR), DIMENSION(:), INTENT(IN   ) :: td_mask
+      TYPE(TVAR), INTENT(INOUT) :: td_var
+      TYPE(TVAR), INTENT(IN   ) :: td_mask
 
       ! local variable
@@ -1351,17 +1443,20 @@
       !----------------------------------------------------------------
 
+      IF( ANY(td_var%t_dim(1:2)%i_len /= &
+      &       td_mask%t_dim(1:2)%i_len) )THEN
+         CALL logger_debug("     mask dimension ( "//&
+         &              TRIM(fct_str(td_mask%t_dim(1)%i_len))//","//&
+         &              TRIM(fct_str(td_mask%t_dim(2)%i_len))//")" )
+         CALL logger_debug(" variable dimension ( "//&
+         &              TRIM(fct_str(td_var%t_dim(1)%i_len))//","//&
+         &              TRIM(fct_str(td_var%t_dim(2)%i_len))//")" )
+         CALL logger_fatal("CREATE BOUNDARY USE MASK: mask and "//&
+         &                 "variable dimension differ."   )
+      ENDIF
+
       ALLOCATE( il_mask(td_var%t_dim(1)%i_len, &
       &                 td_var%t_dim(2)%i_len) )
 
-      SELECT CASE(TRIM(td_var%c_point))
-      CASE('T')
-         il_mask(:,:)=INT(td_mask(jp_T)%d_value(:,:,1,1))
-      CASE('U')
-         il_mask(:,:)=INT(td_mask(jp_U)%d_value(:,:,1,1))
-      CASE('V')
-         il_mask(:,:)=INT(td_mask(jp_V)%d_value(:,:,1,1))
-      CASE('F')
-         il_mask(:,:)=INT(td_mask(jp_F)%d_value(:,:,1,1))
-      END SELECT
+      il_mask(:,:)=INT(td_mask%d_value(:,:,1,1))
 
       DO jl=1,td_var%t_dim(4)%i_len
@@ -1372,62 +1467,172 @@
 
       DEALLOCATE( il_mask )
-   END SUBROUTINE create_bdy_use_mask
-   !> @endcode
+
+   END SUBROUTINE create_boundary_use_mask
    !-------------------------------------------------------------------
    !> @brief
+   !> This function extract level over domain on each grid point, and return
+   !> array of variable structure
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] td_level  array of level variable structure
+   !> @param[in] td_dom    array of domain structure
+   !> @return array of variable structure
+   !-------------------------------------------------------------------
+   FUNCTION create_boundary_get_level(td_level, td_dom)
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR), DIMENSION(:), INTENT(IN) :: td_level
+      TYPE(TDOM), DIMENSION(:), INTENT(IN) :: td_dom
+
+      ! function
+      TYPE(TVAR), DIMENSION(ip_npoint) :: create_boundary_get_level
+
+      ! local variable
+      TYPE(TVAR), DIMENSION(ip_npoint) :: tl_var
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      IF( SIZE(td_level(:)) /= ip_npoint .OR. &
+      &   SIZE(td_dom(:)) /= ip_npoint )THEN
+         CALL logger_error("CREATE BDY GET LEVEL: invalid dimension. "//&
+         &  "check input array of level and domain.")
+      ELSE
+
+         DO ji=1,ip_npoint
+
+            tl_var(ji)=var_copy(td_level(ji))
+
+            IF( ASSOCIATED(tl_var(ji)%d_value) ) DEALLOCATE(tl_var(ji)%d_value)
+
+            tl_var(ji)%t_dim(1)%i_len=td_dom(ji)%t_dim(1)%i_len
+            tl_var(ji)%t_dim(2)%i_len=td_dom(ji)%t_dim(2)%i_len
+            ALLOCATE(tl_var(ji)%d_value(tl_var(ji)%t_dim(1)%i_len, &
+            &                           tl_var(ji)%t_dim(2)%i_len, &
+            &                           tl_var(ji)%t_dim(3)%i_len, &
+            &                           tl_var(ji)%t_dim(4)%i_len) )
+
+            tl_var(ji)%d_value(:,:,:,:) = &
+            &  td_level(ji)%d_value( td_dom(ji)%i_imin:td_dom(ji)%i_imax, &
+            &                        td_dom(ji)%i_jmin:td_dom(ji)%i_jmax, :, : )
+
+         ENDDO
+         ! save result
+         create_boundary_get_level(:)=var_copy(tl_var(:))
+
+         ! clean
+         CALL var_clean(tl_var(:))
+
+      ENDIF
+   END FUNCTION create_boundary_get_level
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine get depth variable value in an open mpp structure
+   !> and check if agree with already input depth variable.
    !> 
    !> @details 
    !>
    !> @author J.Paul
-   !> - 2013- Initial Version
+   !> - November, 2014- Initial Version
    !>
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create_bdy_get_level(td_level, td_dom)
+   !> @param[in] td_mpp       mpp structure
+   !> @param[inout] td_depth  depth variable structure 
+   !-------------------------------------------------------------------
+   SUBROUTINE create_boundary_check_depth( td_mpp, td_depth )
+
       IMPLICIT NONE
+
       ! Argument
-      TYPE(TVAR), DIMENSION(:), INTENT(IN) :: td_level
-      TYPE(TDOM)              , INTENT(IN) :: td_dom
-
-      ! function
-      TYPE(TVAR), DIMENSION(ig_npoint) :: create_bdy_get_level
+      TYPE(TMPP) , INTENT(IN   ) :: td_mpp
+      TYPE(TVAR) , INTENT(INOUT) :: td_depth
 
       ! local variable
-      TYPE(TVAR), DIMENSION(ig_npoint) :: tl_var
-
+      INTEGER(i4) :: il_varid
+      TYPE(TVAR)  :: tl_depth
       ! loop indices
-      INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
-      IF( SIZE(td_level(:)) /= ig_npoint )THEN
-         CALL logger_error("CREATE BDY GET LEVEL: invalid dimension. "//&
-         &  "check input table of level.")
-      ELSE
-
-         !tl_var(1:ig_npoint)=td_level(1:ig_npoint)
-         create_bdy_get_level(:)=tl_var(:)
-         DO ji=1,ig_npoint
-
-         tl_var(ji)=td_level(ji)
-
-            IF( ASSOCIATED(tl_var(ji)%d_value) ) DEALLOCATE( tl_var(ji)%d_value )
-
-            tl_var(ji)%t_dim(1)%i_len=td_dom%t_dim(1)%i_len
-            tl_var(ji)%t_dim(2)%i_len=td_dom%t_dim(2)%i_len
-            ALLOCATE(tl_var(ji)%d_value(tl_var(ji)%t_dim(1)%i_len, &
-            &                           tl_var(ji)%t_dim(2)%i_len, &
-            &                           tl_var(ji)%t_dim(3)%i_len, &
-            &                           tl_var(ji)%t_dim(4)%i_len) )
-
-            tl_var(ji)%d_value(:,:,:,:) = &
-            &  td_level(ji)%d_value( td_dom%i_imin:td_dom%i_imax, &
-            &                        td_dom%i_jmin:td_dom%i_jmax, :, : )
-
-         ENDDO
-         !4 save result
-         create_bdy_get_level(:)=tl_var(:)
+      ! get or check depth value
+      IF( td_mpp%t_proc(1)%i_depthid /= 0 )THEN
+
+         il_varid=td_mpp%t_proc(1)%i_depthid
+         IF( ASSOCIATED(td_depth%d_value) )THEN
+
+            tl_depth=iom_mpp_read_var(td_mpp, il_varid)
+            IF( ANY( td_depth%d_value(:,:,:,:) /= &
+            &        tl_depth%d_value(:,:,:,:) ) )THEN
+
+               CALL logger_fatal("CREATE BOUNDARY: depth value from "//&
+               &  TRIM(tl_multi%t_mpp(ji)%c_name)//" not conform "//&
+               &  " to those from former file(s).")
+
+            ENDIF
+            CALL var_clean(tl_depth)
+
+         ELSE
+            td_depth=iom_mpp_read_var(td_mpp,il_varid)
+         ENDIF
 
       ENDIF
-   END FUNCTION create_bdy_get_level
-   !> @endcode
+      
+   END SUBROUTINE create_boundary_check_depth
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine get date and time in an open mpp structure
+   !> and check if agree with date and time already read.
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - November, 2014- Initial Version
+   !>
+   !> @param[in] td_mpp      mpp structure
+   !> @param[inout] td_time  time variable structure 
+   !-------------------------------------------------------------------
+   SUBROUTINE create_boundary_check_time( td_mpp, td_time )
+
+      IMPLICIT NONE
+
+      ! Argument
+      TYPE(TMPP), INTENT(IN   ) :: td_mpp
+      TYPE(TVAR), INTENT(INOUT) :: td_time
+
+      ! local variable
+      INTEGER(i4) :: il_varid
+      TYPE(TVAR)  :: tl_time
+
+      TYPE(TDATE) :: tl_date1
+      TYPE(TDATE) :: tl_date2
+      ! loop indices
+      !----------------------------------------------------------------
+
+      ! get or check depth value
+      IF( td_mpp%t_proc(1)%i_timeid /= 0 )THEN
+
+         il_varid=td_mpp%t_proc(1)%i_timeid
+         IF( ASSOCIATED(td_time%d_value) )THEN
+
+            tl_time=iom_mpp_read_var(td_mpp, il_varid)
+
+            tl_date1=var_to_date(td_time)
+            tl_date2=var_to_date(tl_time)
+            IF( tl_date1 - tl_date2 /= 0 )THEN
+
+               CALL logger_fatal("CREATE BOUNDARY: date from "//&
+               &  TRIM(tl_multi%t_mpp(ji)%c_name)//" not conform "//&
+               &  " to those from former file(s).")
+
+            ENDIF
+            CALL var_clean(tl_time)
+
+         ELSE
+            td_time=iom_mpp_read_var(td_mpp,il_varid)
+         ENDIF
+
+      ENDIF
+      
+   END SUBROUTINE create_boundary_check_time
 END PROGRAM create_boundary
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_coord.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_coord.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_coord.f90	(revision 5075)
@@ -7,26 +7,101 @@
 !
 ! DESCRIPTION:
+!> @file
 !> @brief 
-!> This program create coordinate file.
+!> This program create fine grid coordinate file.
 !>
 !> @details
-!> Variables are extracted from the input coordinates coarse grid, 
-!> and interpolated to create fine coordinates files.
-!>
-!> @author
-!> J.Paul
+!> @section sec1 method
+!>    All variables from the input coordinates coarse grid file, are extracted
+!>    and interpolated to create fine grid coordinates files.<br/>
+!>    @note 
+!>       interpolation method could be different for each variable.
+!>
+!> @section sec2 how to
+!>    to create fine grid coordinates files:<br/>
+!> @code{.sh}
+!>    ./SIREN/bin/create_coord create_coord.nam
+!> @endcode
+!>    
+!>    create_coord.nam comprise 6 namelists:<br/>
+!>       - logger namelist (namlog)
+!>       - config namelist (namcfg)
+!>       - coarse grid namelist (namcrs)
+!>       - variable namelist (namvar)
+!>       - nesting namelist (namnst)
+!>       - output namelist (namout)
+!>    
+!>    @note 
+!>       All namelists have to be in file create_coord.nam, 
+!>       however variables of those namelists are all optional.
+!>
+!>    * _logger namelist (namlog)_:<br/>
+!>       - cn_logfile   : log filename
+!>       - cn_verbosity : verbosity ('trace','debug','info',
+!> 'warning','error','fatal')
+!>       - in_maxerror  : maximum number of error allowed
+!>
+!>    * _config namelist (namcfg)_:<br/>
+!>       - cn_varcfg : variable configuration file 
+!> (see ./SIREN/cfg/variable.cfg)
+!>
+!>    * _coarse grid namelist (namcrs)_:<br/>
+!>       - cn_coord0 : coordinate file
+!>       - in_perio0 : NEMO periodicity index (see Model Boundary Condition in
+!> [NEMO documentation](http://www.nemo-ocean.eu/About-NEMO/Reference-manuals))
+!>
+!>    * _variable namelist (namvar)_:<br/>
+!>       - cn_varinfo : list of variable and extra information about request(s)
+!> to be used.<br/>
+!>          each elements of *cn_varinfo* is a string character.<br/>
+!>          it is composed of the variable name follow by ':', 
+!>          then request(s) to be used on this variable.<br/> 
+!>          request could be:
+!>             - interpolation method
+!>             - extrapolation method
+!>             - filter method
+!> 
+!>                requests must be separated by ';' .<br/>
+!>                order of requests does not matter.<br/>
+!>
+!>          informations about available method could be find in @ref interp,
+!>          @ref extrap and @ref filter modules.<br/>
+!>
+!>          Example: 'votemper: linear; hann(2,3); dist_weight', 
+!>          'vosaline: cubic'<br/>
+!>          @note 
+!>             If you do not specify a method which is required, 
+!>             default one is applied.
+!>
+!>    * _nesting namelist (namnst)_:<br/>
+!>       - in_imin0 : i-direction lower left  point indice 
+!> of coarse grid subdomain to be used
+!>       - in_imax0 : i-direction upper right point indice
+!> of coarse grid subdomain to be used
+!>       - in_jmin0 : j-direction lower left  point indice
+!> of coarse grid subdomain to be used
+!>       - in_jmax0 : j-direction upper right point indice
+!> of coarse grid subdomain to be used
+!>       - in_rhoi  : refinement factor in i-direction
+!>       - in_rhoj  : refinement factor in j-direction<br/>
+!>
+!>       \image html  grid_zoom_40.png 
+!>       \image latex grid_zoom_40.png
+!>
+!>    * _output namelist (namout)_:
+!>       - cn_fileout : output coordinate file
+!>
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
+!> @date November, 2013 - Initial Version
+!> @date September, 2014
+!> - add header for user
+!> - compute offset considering grid point
+!> - add global attributes in output file
+!>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!>
-!> @todo
-!> - add extrapolation (case coordin with mask)
-!> - add extraction from a grid at fine resolution
 !----------------------------------------------------------------------
-!> @code
 PROGRAM create_coord
 
-!   USE netcdf                          ! nf90 library
    USE global                          ! global variable
    USE kind                            ! F90 kind parameter
@@ -39,5 +114,4 @@
    USE file                            ! file manager
    USE iom                             ! I/O manager
-   USE dom                             ! domain manager
    USE grid                            ! grid manager
    USE extrap                          ! extrapolation manager
@@ -45,5 +119,7 @@
    USE filter                          ! filter manager
    USE mpp                             ! MPP manager
+   USE dom                             ! domain manager
    USE iom_mpp                         ! MPP I/O manager
+   USE iom_dom                         ! DOM I/O manager
 
    IMPLICIT NONE
@@ -56,8 +132,10 @@
    INTEGER(i4)                                          :: il_status
    INTEGER(i4)                                          :: il_fileid
+   INTEGER(i4)                                          :: il_attid
+   INTEGER(i4)                                          :: il_ind
    INTEGER(i4)                                          :: il_nvar
-!   INTEGER(i4)      , DIMENSION(:,:,:,:)  , ALLOCATABLE :: il_value
+   INTEGER(i4)                                          :: il_ew
    INTEGER(i4)      , DIMENSION(ip_maxdim)              :: il_rho
-
+   INTEGER(i4)      , DIMENSION(2,2,ip_npoint)          :: il_offset
 
    LOGICAL                                              :: ll_exist
@@ -71,22 +149,30 @@
    TYPE(TDIM)       , DIMENSION(ip_maxdim)              :: tl_dim
 
-   TYPE(TFILE)                                          :: tl_coord0
+   TYPE(TMPP)                                           :: tl_coord0
    TYPE(TFILE)                                          :: tl_fileout
 
-   TYPE(TMPP)                                           :: tl_mppcoordin
+   ! check 
+!   INTEGER(i4)                                          :: il_imin0
+!   INTEGER(i4)                                          :: il_imax0
+!   INTEGER(i4)                                          :: il_jmin0
+!   INTEGER(i4)                                          :: il_jmax0
+!   INTEGER(i4)      , DIMENSION(2,2)                    :: il_ind2
+!   TYPE(TMPP)                                           :: tl_mppout
 
    ! loop indices
    INTEGER(i4) :: ji
+   INTEGER(i4) :: jj
 
    ! namelist variable
    CHARACTER(LEN=lc) :: cn_logfile = 'create_coord.log' 
    CHARACTER(LEN=lc) :: cn_verbosity = 'warning' 
+   INTEGER(i4)       :: in_maxerror = 5
 
    CHARACTER(LEN=lc) :: cn_coord0 = '' 
    INTEGER(i4)       :: in_perio0 = -1
 
-   CHARACTER(LEN=lc) :: cn_varcfg = 'variable.cfg' 
-
-   CHARACTER(LEN=lc), DIMENSION(ig_maxvar) :: cn_varinfo = ''
+   CHARACTER(LEN=lc) :: cn_varcfg = '../cfg/variable.cfg' 
+
+   CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varinfo = ''
 
    INTEGER(i4)       :: in_imin0 = 0
@@ -100,21 +186,22 @@
    !-------------------------------------------------------------------
 
-   NAMELIST /namlog/ & !< logger namelist
-   &  cn_logfile,    & !< log file
-   &  cn_verbosity     !< logger verbosity
-
-   NAMELIST /namcfg/ &  !< config namelist
+   NAMELIST /namlog/ &  !  logger namelist
+   &  cn_logfile,    &  !< logger file name
+   &  cn_verbosity,  &  !< logger verbosity
+   &  in_maxerror       !< logger maximum error
+
+   NAMELIST /namcfg/ &  !  config namelist
    &  cn_varcfg         !< variable configuration file
 
-   NAMELIST /namcrs/ &  ! coarse grid namelist
+   NAMELIST /namcrs/ &  !  coarse grid namelist
    &  cn_coord0 , &     !< coordinate file
    &  in_perio0         !< periodicity index
 
-   NAMELIST /namvar/ &  ! namvar
+   NAMELIST /namvar/ &  !  variable namelist
    &  cn_varinfo        !< list of variable and extra information about 
                         !< interpolation, extrapolation or filter method to be used. 
-                        !< (ex: 'votemper/linear/hann/dist_weight','vosaline/cubic' ) 
+                        !< (ex: 'votemper:linear,hann,dist_weight','vosaline:cubic' ) 
    
-   NAMELIST /namnst/ &  !< nesting namelist
+   NAMELIST /namnst/ &  !  nesting namelist
    &  in_imin0,   &     !< i-direction lower left  point indice 
    &  in_imax0,   &     !< i-direction upper right point indice
@@ -124,10 +211,10 @@
    &  in_rhoj           !< refinement factor in j-direction
 
-   NAMELIST /namout/ &  !< output namelist
-   &  cn_fileout       !< fine grid coordinate file   
+   NAMELIST /namout/ &  !  output namelist
+   &  cn_fileout        !< fine grid coordinate file   
    !-------------------------------------------------------------------
 
-   !1- namelist
-   !1-1 get namelist
+   ! namelist
+   ! get namelist
    il_narg=COMMAND_ARGUMENT_COUNT() !f03 intrinsec
    IF( il_narg/=1 )THEN
@@ -138,8 +225,8 @@
    ENDIF
    
-   !1-2 read namelist
+   ! read namelist
    INQUIRE(FILE=TRIM(cl_namelist), EXIST=ll_exist)
    IF( ll_exist )THEN
-      
+ 
       il_fileid=fct_getunit()
 
@@ -157,15 +244,15 @@
 
       READ( il_fileid, NML = namlog )
-      !1-2-1 define log file
-      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity))
+      ! define logger file
+      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity),in_maxerror)
       CALL logger_header()
 
       READ( il_fileid, NML = namcfg )
-      !1-2-2 get variable extra information on configuration file
+      ! get variable extra information on configuration file
       CALL var_def_extra(TRIM(cn_varcfg))
 
       READ( il_fileid, NML = namcrs )
       READ( il_fileid, NML = namvar )
-      !1-2-3 add user change in extra information
+      ! add user change in extra information
       CALL var_chg_extra( cn_varinfo )
 
@@ -182,18 +269,19 @@
 
       PRINT *,"ERROR in create_coord: can't find "//TRIM(cl_namelist)
-
-   ENDIF
-
-   !2- open files
+      STOP
+
+   ENDIF
+
+   ! open files
    IF( cn_coord0 /= '' )THEN
-      tl_coord0=file_init(TRIM(cn_coord0),id_perio=in_perio0)
-      CALL iom_open(tl_coord0)
+      tl_coord0=mpp_init( file_init(TRIM(cn_coord0)), id_perio=in_perio0)
+      CALL grid_get_info(tl_coord0)
    ELSE
-       CALL logger_fatal("CREATE COORD: no coarse grid coordinate found. "//&
+      CALL logger_fatal("CREATE COORD: no coarse grid coordinate found. "//&
       &     "check namelist")      
    ENDIF
 
-   !3- check
-   !3-1 check output file do not already exist
+   ! check
+   ! check output file do not already exist
    INQUIRE(FILE=TRIM(cn_fileout), EXIST=ll_exist)
    IF( ll_exist )THEN
@@ -202,7 +290,7 @@
    ENDIF
 
-   !3-2 check namelist
-   IF( in_imin0 < 1 .OR. in_imax0 < 1 .OR. in_jmin0 < 1 .OR. in_jmax0 < 1)THEN
-      CALL logger_error("CREATE COORD: invalid point indice."//&
+   ! check nesting parameters
+   IF( in_imin0 < 0 .OR. in_imax0 < 0 .OR. in_jmin0 < 0 .OR. in_jmax0 < 0)THEN
+      CALL logger_fatal("CREATE COORD: invalid points indices."//&
       &  " check namelist "//TRIM(cl_namelist))
    ENDIF
@@ -215,67 +303,68 @@
       il_rho(jp_I)=in_rhoi
       il_rho(jp_J)=in_rhoj      
-   ENDIF
-
-   !3-3 check domain validity
+
+      il_offset(:,:,:)=create_coord_get_offset(il_rho(:))
+
+   ENDIF
+
+   ! check domain validity
    CALL grid_check_dom(tl_coord0, in_imin0, in_imax0, in_jmin0, in_jmax0 )
 
-   !4- compute domain
+   ! compute domain
    tl_dom=dom_init( tl_coord0,         &
    &                in_imin0, in_imax0,&
    &                in_jmin0, in_jmax0 )
 
-   ! close file
-   CALL iom_close(tl_coord0)
-
-   !4-1 add extra band (if possible) to compute interpolation
+   ! add extra band (if need be) to compute interpolation
    CALL dom_add_extra(tl_dom)
 
-   !5- read variables on domain (ugly way to do it, have to work on it)
-   !5-1 init mpp structure
-   tl_mppcoordin=mpp_init(tl_coord0)
-
-   CALL file_clean(tl_coord0)
-
-   !5-2 get processor to be used
-   CALL mpp_get_use( tl_mppcoordin, tl_dom )
-
-   !5-3 open mpp files
-   CALL iom_mpp_open(tl_mppcoordin)
-
-   !5-4 fill variable value on domain
-   CALL iom_mpp_fill_var(tl_mppcoordin, tl_dom)
-
-   !5-5 close mpp files
-   CALL iom_mpp_close(tl_mppcoordin)
-
-   il_nvar=tl_mppcoordin%t_proc(1)%i_nvar
+   ! open mpp files
+   CALL iom_dom_open(tl_coord0, tl_dom)
+
+   il_nvar=tl_coord0%t_proc(1)%i_nvar
    ALLOCATE( tl_var(il_nvar) )
    DO ji=1,il_nvar
 
-      tl_var(ji)=tl_mppcoordin%t_proc(1)%t_var(ji)
-      !7- interpolate variables
-      CALL create_coord_interp( tl_var(ji), il_rho(:) )
-
-      !6- remove extraband added to domain
-      CALL dom_del_extra( tl_var(ji), tl_dom, il_rho(:) )
-
-      !7- add ghost cell
-      CALL grid_add_ghost(tl_var(ji),tl_dom%i_ighost,tl_dom%i_jghost)      
-
-      !8- filter
+      tl_var(ji)=iom_dom_read_var(tl_coord0, &
+      &                          TRIM(tl_coord0%t_proc(1)%t_var(ji)%c_name),&
+      &                          tl_dom)
+
+      SELECT CASE(TRIM(tl_var(ji)%c_point))
+         CASE('T')
+            jj=jp_T
+         CASE('U')
+            jj=jp_U
+         CASE('V')
+            jj=jp_V
+         CASE('F')
+            jj=jp_F
+      END SELECT
+
+      ! interpolate variables
+      CALL create_coord_interp( tl_var(ji), il_rho(:), &
+      &                         il_offset(:,:,jj) )
+
+      ! remove extraband added to domain
+      CALL dom_del_extra( tl_var(ji), tl_dom, il_rho(:), .true. )
+
+      ! do not add ghost cell. 
+      ! ghost cell already replace by value for coordinates 
+      ! CALL grid_add_ghost(tl_var(ji),tl_dom%i_ghost(:,:))
+
+      ! filter
       CALL filter_fill_value(tl_var(ji))      
 
    ENDDO
 
-   !9- clean
-   DO ji=1,il_nvar
-      CALL var_clean(tl_mppcoordin%t_proc(1)%t_var(ji))
-   ENDDO
-   CALL mpp_clean(tl_mppcoordin)
-
-   !10- create file
+   ! close mpp files
+   CALL iom_dom_close(tl_coord0)
+
+   ! clean
+   CALL mpp_clean(tl_coord0)
+
+   ! create file
    tl_fileout=file_init(TRIM(cn_fileout))
 
-   !10-1 add dimension
+   ! add dimension
    ! save biggest dimension
    tl_dim(:)=var_max_dim(tl_var(:))
@@ -285,11 +374,12 @@
    ENDDO
 
-   !10-2 add variables
-
+   ! add variables
    DO ji=1,il_nvar
       CALL file_add_var(tl_fileout, tl_var(ji))
    ENDDO
 
-   !10-3 add some attribute
+   ! recompute some attribute
+
+   ! add some attribute
    tl_att=att_init("Created_by","SIREN create_coord")
    CALL file_add_att(tl_fileout, tl_att)
@@ -299,50 +389,158 @@
    CALL file_add_att(tl_fileout, tl_att)
 
-   tl_att=att_init("source_file",TRIM(fct_basename(cn_coord0)))
+   tl_att=att_init("src_file",TRIM(fct_basename(cn_coord0)))
    CALL file_add_att(tl_fileout, tl_att)   
 
-   tl_att=att_init("source_i-indices",(/in_imin0,in_imax0/))
+   tl_att=att_init("src_i_indices",(/in_imin0,in_imax0/))
    CALL file_add_att(tl_fileout, tl_att)   
-   tl_att=att_init("source_j-indices",(/in_jmin0,in_jmax0/))
-   CALL file_add_att(tl_fileout, tl_att)   
-
-   !10-4 create file
+   tl_att=att_init("src_j_indices",(/in_jmin0,in_jmax0/))
+   CALL file_add_att(tl_fileout, tl_att)
+   IF( .NOT. ALL(il_rho(:)==1) )THEN
+      tl_att=att_init("refinment_factor",(/il_rho(jp_I),il_rho(jp_J)/))
+      CALL file_add_att(tl_fileout, tl_att)
+   ENDIF
+
+   ! add attribute periodicity
+   il_attid=0
+   IF( ASSOCIATED(tl_fileout%t_att) )THEN
+      il_attid=att_get_index(tl_fileout%t_att(:),'periodicity')
+   ENDIF
+   IF( tl_dom%i_perio >= 0 .AND. il_attid == 0 )THEN
+      tl_att=att_init('periodicity',tl_dom%i_perio)
+      CALL file_add_att(tl_fileout,tl_att)
+   ENDIF
+
+   ! add attribute east west overlap
+   il_attid=0
+   IF( ASSOCIATED(tl_fileout%t_att) )THEN
+      il_attid=att_get_index(tl_fileout%t_att(:),'ew_overlap')
+   ENDIF
+   IF( il_attid == 0 )THEN
+      il_ind=var_get_index(tl_fileout%t_var(:),'longitude')
+      il_ew=grid_get_ew_overlap(tl_fileout%t_var(il_ind))
+      IF( il_ew >= 0 )THEN
+         tl_att=att_init('ew_overlap',il_ew)
+         CALL file_add_att(tl_fileout,tl_att)
+      ENDIF
+   ENDIF
+
+   ! create file
    CALL iom_create(tl_fileout)
 
-   !10-5 write file
+   ! write file
    CALL iom_write_file(tl_fileout)
 
-   !10-6 close file
+   ! close file
    CALL iom_close(tl_fileout)
 
-   !11- clean
-   DO ji=1,il_nvar
-      CALL var_clean(tl_var(ji))
-   ENDDO
+   ! clean
+   CALL att_clean(tl_att)
+   CALL var_clean(tl_var(:))
+   DEALLOCATE( tl_var) 
+
    CALL file_clean(tl_fileout)
 
-   DEALLOCATE( tl_var) 
+!   ! check domain
+!   tl_coord0=mpp_init( file_init(TRIM(cn_coord0)), id_perio=in_perio0)
+!   tl_mppout=mpp_init( file_init(TRIM(cn_fileout)) )
+!   CALL grid_get_info(tl_coord0)
+!   CALL iom_mpp_open(tl_mppout)
+!
+!   il_ind2(:,:)=grid_get_coarse_index( tl_coord0, tl_mppout, &
+!   &                                   id_rho=il_rho(:) )
+!
+!   il_imin0=il_ind2(1,1) ; il_imax0=il_ind2(1,2)
+!   il_jmin0=il_ind2(2,1) ; il_jmax0=il_ind2(2,2)
+!
+!   IF( il_imin0 /= in_imin0 .OR. &
+!   &   il_imax0 /= in_imax0 .OR. &
+!   &   il_jmin0 /= in_jmin0 .OR. &
+!   &   il_jmax0 /= in_jmax0 )THEN
+!      CALL logger_debug("CREATE COORD: output indices ("//&
+!      &                 TRIM(fct_str(il_imin0))//","//&
+!      &                 TRIM(fct_str(il_imax0))//") ("//&
+!      &                 TRIM(fct_str(il_jmin0))//","//&
+!      &                 TRIM(fct_str(il_jmax0))//")" ) 
+!      CALL logger_debug("CREATE COORD: input indices ("//&
+!      &                 TRIM(fct_str(in_imin0))//","//&
+!      &                 TRIM(fct_str(in_imax0))//") ("//&
+!      &                 TRIM(fct_str(in_jmin0))//","//&
+!      &                 TRIM(fct_str(in_jmax0))//")" ) 
+!      CALL logger_fatal("CREATE COORD: output domain not confrom "//&
+!      &                 "with input indices")
+!   ENDIF
+!
+!   CALL iom_mpp_close(tl_coord0)
+!   CALL iom_mpp_close(tl_mppout)
 
    ! close log file
    CALL logger_footer()
-   CALL logger_close()   
-
-!> @endcode
+   CALL logger_close() 
+
 CONTAINS
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This function compute offset over Arakawa grid points, 
+   !> given refinement factor.
+   !> 
+   !> @author J.Paul
+   !> @date August, 2014 - Initial Version
+   !>
+   !> @param[in] id_rho array of refinement factor
+   !> @return array of offset
+   !-------------------------------------------------------------------
+   FUNCTION create_coord_get_offset( id_rho )
+      IMPLICIT NONE
+      ! Argument      
+      INTEGER(i4), DIMENSION(:), INTENT(IN) :: id_rho
+
+      ! function
+      INTEGER(i4), DIMENSION(2,2,ip_npoint) :: create_coord_get_offset
+      ! local variable
+      ! loop indices
+      !----------------------------------------------------------------
+
+      ! case 'T'
+      create_coord_get_offset(jp_I,:,jp_T)=FLOOR(REAL(id_rho(jp_I)-1,dp)*0.5)
+      create_coord_get_offset(jp_J,:,jp_T)=FLOOR(REAL(id_rho(jp_J)-1,dp)*0.5)
+      ! case 'U'
+      create_coord_get_offset(jp_I,1,jp_U)=0
+      create_coord_get_offset(jp_I,2,jp_U)=id_rho(jp_I)-1
+      create_coord_get_offset(jp_J,:,jp_U)=FLOOR(REAL(id_rho(jp_J)-1,dp)*0.5)
+      ! case 'V'
+      create_coord_get_offset(jp_I,:,jp_V)=FLOOR(REAL(id_rho(jp_I)-1,dp)*0.5)
+      create_coord_get_offset(jp_J,1,jp_V)=0
+      create_coord_get_offset(jp_J,2,jp_V)=id_rho(jp_J)-1
+      ! case 'F'
+      create_coord_get_offset(jp_I,1,jp_F)=0
+      create_coord_get_offset(jp_I,2,jp_F)=id_rho(jp_I)-1
+      create_coord_get_offset(jp_J,1,jp_F)=0
+      create_coord_get_offset(jp_J,2,jp_F)=id_rho(jp_J)-1
+
+
+   END FUNCTION create_coord_get_offset
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine interpolate variable, given refinment factor.
    !> 
    !> @details 
+   !>  Optionaly, you could specify number of points 
+   !>    to be extrapolated in i- and j-direction.<br/>
+   !>  variable mask is first computed (using _FillValue) and interpolated.<br/>
+   !>  variable is then extrapolated, and interpolated.<br/> 
+   !>  Finally interpolated mask is applied on refined variable.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> @date November, 2013 - Initial Version
    !>
-   !> @param[in] 
-   !> @todo 
+   !> @param[inout] td_var variable strcuture 
+   !> @param[in] id_rho    array of refinement factor
+   !> @param[in] id_offset offset between fine grid and coarse grid
+   !> @param[in] id_iext   number of points to be extrapolated in i-direction
+   !> @param[in] id_jext   number of points to be extrapolated in j-direction
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE create_coord_interp( td_var,          &
    &                               id_rho,          &
+   &                               id_offset,       &
    &                               id_iext, id_jext)
 
@@ -350,16 +548,14 @@
 
       ! Argument
-      TYPE(TVAR) ,               INTENT(INOUT) :: td_var
-      INTEGER(i4), DIMENSION(:), INTENT(IN   ) :: id_rho
-      INTEGER(i4),               INTENT(IN   ), OPTIONAL :: id_iext
-      INTEGER(i4),               INTENT(IN   ), OPTIONAL :: id_jext
+      TYPE(TVAR) ,                 INTENT(INOUT) :: td_var
+      INTEGER(i4), DIMENSION(:)  , INTENT(IN   ) :: id_rho
+      INTEGER(i4), DIMENSION(:,:), INTENT(IN)    :: id_offset
+      INTEGER(i4),                 INTENT(IN   ), OPTIONAL :: id_iext
+      INTEGER(i4),                 INTENT(IN   ), OPTIONAL :: id_jext
 
       ! local variable
       TYPE(TVAR)  :: tl_mask
-      TYPE(TVAR)  :: tl_var
 
       INTEGER(i1), DIMENSION(:,:,:,:), ALLOCATABLE :: bl_mask
-
-      INTEGER(i4), DIMENSION(2,2) :: il_offset
 
       INTEGER(i4) :: il_iext
@@ -369,6 +565,8 @@
       !----------------------------------------------------------------
 
-      ! copy variable
-      tl_var=td_var
+      IF( ANY(SHAPE(id_offset(:,:)) /= 2) )THEN
+         CALL logger_error("CREATE COORD INTERP: invalid dimension of "//&
+         &                 "offset array")
+      ENDIF
 
       !WARNING: two extrabands are required for cubic interpolation
@@ -391,60 +589,59 @@
       ENDIF
 
-      !1- work on mask
-      !1-1 create mask
-      ALLOCATE(bl_mask(tl_var%t_dim(1)%i_len, &
-      &                tl_var%t_dim(2)%i_len, &
-      &                tl_var%t_dim(3)%i_len, &
-      &                tl_var%t_dim(4)%i_len) )
-
-      bl_mask(:,:,:,:)=1
-      WHERE(tl_var%d_value(:,:,:,:)==tl_var%d_fill) bl_mask(:,:,:,:)=0      
-
-      SELECT CASE(TRIM(tl_var%c_point))
-      CASE DEFAULT ! 'T'
-         tl_mask=var_init('tmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('U')
-         tl_mask=var_init('umask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('V')
-         tl_mask=var_init('vmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('F')
-         tl_mask=var_init('fmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      END SELECT         
-
-      DEALLOCATE(bl_mask)
-
-      !1-2 interpolate mask
-      il_offset(:,:)=1
-      CALL interp_fill_value( tl_mask, id_rho(:), &
-      &                       id_offset=il_offset(:,:) )
-
-      !2- work on variable
-      !2-0 add extraband
-      CALL extrap_add_extrabands(tl_var, il_iext, il_jext)
-
-      !2-1 extrapolate variable
-      CALL extrap_fill_value( tl_var, id_iext=il_iext, id_jext=il_jext )
-
-      !2-2 interpolate variable
-      il_offset(:,:)=1
-      CALL interp_fill_value( tl_var, id_rho(:), &
-      &                       id_offset=il_offset(:,:))
-
-      !2-3 remove extraband
-      CALL extrap_del_extrabands(tl_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
-
-      !3- keep original mask 
-      WHERE( tl_mask%d_value(:,:,:,:) == 0 )
-         tl_var%d_value(:,:,:,:)=tl_var%d_fill
-      END WHERE
-
-      !4- save result
-      td_var=tl_var
+      IF( ANY(id_rho(:)>1) )THEN
+         ! work on mask
+         ! create mask
+         ALLOCATE(bl_mask(td_var%t_dim(1)%i_len, &
+         &                td_var%t_dim(2)%i_len, &
+         &                td_var%t_dim(3)%i_len, &
+         &                td_var%t_dim(4)%i_len) )
+
+         bl_mask(:,:,:,:)=1
+         WHERE(td_var%d_value(:,:,:,:)==td_var%d_fill) bl_mask(:,:,:,:)=0      
+
+         SELECT CASE(TRIM(td_var%c_point))
+         CASE DEFAULT ! 'T'
+            tl_mask=var_init('tmask',bl_mask(:,:,:,:),td_dim=td_var%t_dim(:),&
+            &                id_ew=td_var%i_ew )
+         CASE('U')
+            tl_mask=var_init('umask',bl_mask(:,:,:,:),td_dim=td_var%t_dim(:),&
+            &                id_ew=td_var%i_ew )
+         CASE('V')
+            tl_mask=var_init('vmask',bl_mask(:,:,:,:),td_dim=td_var%t_dim(:),&
+            &                id_ew=td_var%i_ew )
+         CASE('F')
+            tl_mask=var_init('fmask',bl_mask(:,:,:,:),td_dim=td_var%t_dim(:),&
+            &                id_ew=td_var%i_ew )
+         END SELECT         
+
+         DEALLOCATE(bl_mask)
+
+         ! interpolate mask
+         CALL interp_fill_value( tl_mask, id_rho(:), &
+         &                       id_offset=id_offset(:,:) )
+
+         ! work on variable
+         ! add extraband
+         CALL extrap_add_extrabands(td_var, il_iext, il_jext)
+
+         ! extrapolate variable
+         CALL extrap_fill_value( td_var, id_iext=il_iext, id_jext=il_jext )
+
+         ! interpolate variable
+         CALL interp_fill_value( td_var, id_rho(:), &
+         &                       id_offset=id_offset(:,:))
+
+         ! remove extraband
+         CALL extrap_del_extrabands(td_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
+
+         ! keep original mask 
+         WHERE( tl_mask%d_value(:,:,:,:) == 0 )
+            td_var%d_value(:,:,:,:)=td_var%d_fill
+         END WHERE
+      ENDIF
 
       ! clean variable structure
       CALL var_clean(tl_mask)
-      CALL var_clean(tl_var)
 
    END SUBROUTINE create_coord_interp
-   !> @endcode
 END PROGRAM create_coord
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_restart.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_restart.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/create_restart.f90	(revision 5075)
@@ -7,27 +7,150 @@
 !
 ! DESCRIPTION:
+!> @file
 !> @brief 
 !> This program create restart file.
 !>
 !> @details
-!> Variables are read from restart file, or standard output.
-!> Then theses variables are interpolated on fine grid. 
-!> Finally table are split over new decomposition. 
-!>
-!> @author
-!> J.Paul
+!> @section sec1 method
+!> Variables could be extracted from fine grid file, interpolated from coarse
+!> grid file or restart file, or manually written.<br/> 
+!> Then they are split over new decomposition. 
+!> @note 
+!>    method could be different for each variable.
+!>
+!> @section sec2 how to
+!>    to create restart file:<br/>
+!> @code{.sh}
+!>    ./SIREN/bin/create_restart create_restart.nam
+!> @endcode
+!>    
+!>    create_restart.nam comprise 9 namelists:<br/>
+!>       - logger namelist (namlog)
+!>       - config namelist (namcfg)
+!>       - coarse grid namelist (namcrs)
+!>       - fine grid namelist (namfin)
+!>       - vertical grid namelist (namzgr)
+!>       - partial step namelist (namzps)
+!>       - variable namelist (namvar)
+!>       - nesting namelist (namnst)
+!>       - output namelist (namout)
+!>    
+!>    @note 
+!>       All namelists have to be in file create_restart.nam 
+!>       however variables of those namelists are all optional.
+!>
+!>    * _logger namelist (namlog)_:<br/>
+!>       - cn_logfile   : log filename
+!>       - cn_verbosity : verbosity ('trace','debug','info',
+!> 'warning','error','fatal')
+!>       - in_maxerror  : maximum number of error allowed
+!>
+!>    * _config namelist (namcfg)_:<br/>
+!>       - cn_varcfg : variable configuration file
+!> (see ./SIREN/cfg/variable.cfg)
+!>
+!>    * _coarse grid namelist (namcrs):<br/>
+!>       - cn_coord0 : coordinate file
+!>       - in_perio0 : NEMO periodicity index (see Model Boundary Condition in
+!> [NEMO documentation](http://www.nemo-ocean.eu/About-NEMO/Reference-manuals))
+!>
+!>    * _fine grid namelist (namfin)_:<br/>
+!>       - cn_coord1 : coordinate file
+!>       - cn_bathy1 : bathymetry file
+!>       - in_perio1 : NEMO periodicity index
+!>       - in_extrap : number of land point to be extrapolated 
+!>       before writing file
+!>
+!>    * _vertical grid namelist (namzgr)_:<br/>
+!>       - dn_pp_to_be_computed  :
+!>       - dn_ppsur              :
+!>       - dn_ppa0               :
+!>       - dn_ppa1               :
+!>       - dn_ppa2               : 
+!>       - dn_ppkth              :
+!>       - dn_ppkth2             :
+!>       - dn_ppacr              :
+!>       - dn_ppacr2             :
+!>       - dn_ppdzmin            :
+!>       - dn_pphmax             :
+!>       - in_nlevel             : number of vertical level
+!>
+!>    * _partial step namelist (namzps)_:<br/>
+!>       - dn_e3zps_min          :
+!>       - dn_e3zps_rat          : 
+!>
+!>    * _variable namelist (namvar)_:<br/>
+!>       - cn_varinfo : list of variable and extra information about request(s) 
+!>       to be used.<br/>
+!>          each elements of *cn_varinfo* is a string character.<br/>
+!>          it is composed of the variable name follow by ':', 
+!>          then request(s) to be used on this variable.<br/> 
+!>          request could be:
+!>             - interpolation method
+!>             - extrapolation method
+!>             - filter method
+!>             - > minimum value
+!>             - < maximum value
+!>
+!>             requests must be separated by ';'.<br/>
+!>             order of requests does not matter.<br/>
+!>
+!>          informations about available method could be find in @ref interp,
+!>          @ref extrap and @ref filter.<br/>
+!>          Example: 'votemper: linear; hann; dist_weight','vosaline: cubic'
+!>          @note 
+!>             If you do not specify a method which is required, 
+!>             default one is apply.
+!>       - cn_varfile : list of variable, and corresponding file<br/> 
+!>          *cn_varfile* is the path and filename of the file where find
+!>          variable.<br/>
+!>          @note 
+!>             *cn_varfile* could be a matrix of value, if you want to filled
+!>             manually variable value.<br/>
+!>             the variable array of value is split into equal subdomain.<br/>
+!>             Each subdomain is filled with the corresponding value 
+!>             of the matrix.<br/>          
+!>             separators used to defined matrix are:
+!>                - ',' for line
+!>                - '/' for row
+!>                - '\' for level<br/>
+!>                Example:<br/>
+!>                   3,2,3/1,4,5  =>  @f$ \left( \begin{array}{ccc}
+!>                                         3 & 2 & 3 \\
+!>                                         1 & 4 & 5 \end{array} \right) @f$
+!>
+!>          Examples: 
+!>             - 'votemper:gridT.nc', 'vozocrtx:gridU.nc'
+!>             - 'votemper:10\25', 'vozocrtx:gridU.nc'
+!>
+!>             to get all variable from one file:
+!>             - 'all:restart.dimg'
+!>
+!>    * _nesting namelist (namnst)_:<br/>
+!>       - in_rhoi  : refinement factor in i-direction
+!>       - in_rhoj  : refinement factor in j-direction
+!>       @note 
+!>          coarse grid indices will be deduced from fine grid
+!>          coordinate file.
+!>
+!>    * _output namelist (namout)_:<br/>
+!>       - cn_fileout : output file
+!>       - in_nproc  : total number of processor to be used
+!>       - in_niproc : i-direction number of processor
+!>       - in_njproc : j-direction numebr of processor
+!>       - cn_type   : output format ('dimg', 'cdf')
+!>
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
+!> @date November, 2013 - Initial Version
+!> @date September, 2014
+!> - add header for user
+!> - offset computed considering grid point
+!> - add attributes in output variable
+!>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!>
-!> @todo
-!> - add attributes indices and refinement in output file
-!> - check fileout exist at the beginning
 !----------------------------------------------------------------------
-!> @code
 PROGRAM create_restart
 
-!   USE netcdf                         ! nf90 library
    USE global                          ! global variable
    USE kind                            ! F90 kind parameter
@@ -41,5 +164,4 @@
    USE multi                           ! multi file manager
    USE iom                             ! I/O manager
-   USE dom                             ! domain manager
    USE grid                            ! grid manager
    USE vgrid                           ! vertical grid manager
@@ -48,5 +170,7 @@
    USE filter                          ! filter manager
    USE mpp                             ! MPP manager
+   USE dom                             ! domain manager
    USE iom_mpp                         ! MPP I/O manager
+   USE iom_dom                         ! DOM I/O manager
 
    IMPLICIT NONE
@@ -58,24 +182,26 @@
    CHARACTER(LEN=lc)                                  :: cl_name
    CHARACTER(LEN=lc)                                  :: cl_data
+   CHARACTER(LEN=lc)                                  :: cl_fileout 
 
    INTEGER(i4)                                        :: il_narg
    INTEGER(i4)                                        :: il_status
    INTEGER(i4)                                        :: il_fileid
+   INTEGER(i4)                                        :: il_nvar
    INTEGER(i4)                                        :: il_attid
+   INTEGER(i4)                                        :: il_imin1
+   INTEGER(i4)                                        :: il_imax1
+   INTEGER(i4)                                        :: il_jmin1
+   INTEGER(i4)                                        :: il_jmax1
    INTEGER(i4)                                        :: il_imin0
    INTEGER(i4)                                        :: il_imax0
    INTEGER(i4)                                        :: il_jmin0
    INTEGER(i4)                                        :: il_jmax0
+   INTEGER(i4)                                        :: il_index
    INTEGER(i4)      , DIMENSION(ip_maxdim)            :: il_rho
-   INTEGER(i4)      , DIMENSION(2)                    :: il_xghost
+   INTEGER(i4)      , DIMENSION(2,2)                  :: il_xghost
    INTEGER(i4)      , DIMENSION(2,2)                  :: il_offset
-   INTEGER(i4)      , DIMENSION(2,2,2)                :: il_ind
+   INTEGER(i4)      , DIMENSION(2,2)                  :: il_ind
 
    LOGICAL                                            :: ll_exist
-
-   TYPE(TFILE)                                        :: tl_coord0
-   TYPE(TFILE)                                        :: tl_coord1
-   TYPE(TFILE)                                        :: tl_bathy1
-   TYPE(TFILE)                                        :: tl_file
 
    TYPE(TDOM)                                         :: tl_dom1
@@ -88,5 +214,4 @@
    TYPE(TVAR)                                         :: tl_lon
    TYPE(TVAR)                                         :: tl_lat
-   TYPE(TVAR)                                         :: tl_tmp
    TYPE(TVAR)       , DIMENSION(:)      , ALLOCATABLE :: tl_var
    TYPE(TVAR)       , DIMENSION(:)      , ALLOCATABLE :: tl_level
@@ -94,6 +219,10 @@
    TYPE(TDIM)       , DIMENSION(ip_maxdim)            :: tl_dim
 
+   TYPE(TMPP)                                         :: tl_coord0
+   TYPE(TMPP)                                         :: tl_coord1
+   TYPE(TMPP)                                         :: tl_bathy1
    TYPE(TMPP)                                         :: tl_mpp
    TYPE(TMPP)                                         :: tl_mppout
+
    TYPE(TMULTI)                                       :: tl_multi
 
@@ -104,29 +233,50 @@
 
    ! namelist variable
+   ! namlog
    CHARACTER(LEN=lc) :: cn_logfile = 'create_restart.log' 
    CHARACTER(LEN=lc) :: cn_verbosity = 'warning' 
-
+   INTEGER(i4)       :: in_maxerror = 5
+
+   ! namcfg
    CHARACTER(LEN=lc) :: cn_varcfg = 'variable.cfg' 
 
+   ! namcrs
    CHARACTER(LEN=lc) :: cn_coord0 = '' 
    INTEGER(i4)       :: in_perio0 = -1
 
+   ! namfin
    CHARACTER(LEN=lc) :: cn_coord1 = ''
    CHARACTER(LEN=lc) :: cn_bathy1 = ''
    INTEGER(i4)       :: in_perio1 = -1
    INTEGER(i4)       :: in_extrap = 0
-   LOGICAL           :: ln_fillclosed = .TRUE.
-
-   CHARACTER(LEN=lc), DIMENSION(ig_maxvar) :: cn_varinfo = ''
-   CHARACTER(LEN=lc), DIMENSION(ig_maxvar) :: cn_varfile = ''
-
-   INTEGER(i4)       :: in_imin0 = 0
-   INTEGER(i4)       :: in_imax0 = 0
-   INTEGER(i4)       :: in_jmin0 = 0
-   INTEGER(i4)       :: in_jmax0 = 0
+
+   !namzgr
+   REAL(dp)          :: dn_pp_to_be_computed = 0._dp
+   REAL(dp)          :: dn_ppsur     = -3958.951371276829_dp
+   REAL(dp)          :: dn_ppa0      =   103.9530096000000_dp
+   REAL(dp)          :: dn_ppa1      =     2.4159512690000_dp
+   REAL(dp)          :: dn_ppa2      =   100.7609285000000_dp
+   REAL(dp)          :: dn_ppkth     =    15.3510137000000_dp
+   REAL(dp)          :: dn_ppkth2    =    48.0298937200000_dp
+   REAL(dp)          :: dn_ppacr     =     7.0000000000000_dp
+   REAL(dp)          :: dn_ppacr2    =    13.000000000000_dp
+   REAL(dp)          :: dn_ppdzmin   = 6._dp
+   REAL(dp)          :: dn_pphmax    = 5750._dp
+   INTEGER(i4)       :: in_nlevel    = 75
+
+   !namzps
+   REAL(dp)          :: dn_e3zps_min = 25._dp
+   REAL(dp)          :: dn_e3zps_rat = 0.2_dp
+
+   ! namvar
+   CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varinfo = ''
+   CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varfile = ''
+
+   ! namnst
    INTEGER(i4)       :: in_rhoi = 0
    INTEGER(i4)       :: in_rhoj = 0
 
-   CHARACTER(LEN=lc) :: cn_fileout = 'restart' 
+   ! namout
+   CHARACTER(LEN=lc) :: cn_fileout = 'restart.nc' 
    INTEGER(i4)       :: in_nproc   = 0
    INTEGER(i4)       :: in_niproc  = 0
@@ -138,29 +288,43 @@
    NAMELIST /namlog/ &  !< logger namelist
    &  cn_logfile,    &  !< log file
-   &  cn_verbosity      !< log verbosity
+   &  cn_verbosity,  &  !< log verbosity
+   &  in_maxerror       !< logger maximum error
 
    NAMELIST /namcfg/ &  !< configuration namelist
    &  cn_varcfg         !< variable configuration file
 
-   NAMELIST /namcrs/ &   !< coarse grid namelist
-   &  cn_coord0,  &      !< coordinate file
-   &  in_perio0          !< periodicity index
+   NAMELIST /namcrs/ &  !< coarse grid namelist
+   &  cn_coord0,  &     !< coordinate file
+   &  in_perio0         !< periodicity index
    
-   NAMELIST /namfin/ &   !< fine grid namelist
-   &  cn_coord1,   &     !< coordinate file
-   &  cn_bathy1,   &     !< bathymetry file
-   &  in_perio1,   &     !< periodicity index
-   &  in_extrap,   &     !<
-   &  ln_fillclosed      !< fill closed sea
+   NAMELIST /namfin/ &  !< fine grid namelist
+   &  cn_coord1,   &    !< coordinate file
+   &  cn_bathy1,   &    !< bathymetry file
+   &  in_perio1,   &    !< periodicity index
+   &  in_extrap
  
+   NAMELIST /namzgr/ &
+   &  dn_pp_to_be_computed, &
+   &  dn_ppsur,     &
+   &  dn_ppa0,      &
+   &  dn_ppa1,      &
+   &  dn_ppa2,      &
+   &  dn_ppkth,     &
+   &  dn_ppkth2,    &
+   &  dn_ppacr,     &
+   &  dn_ppacr2,    &
+   &  dn_ppdzmin,   &
+   &  dn_pphmax,    &
+   &  in_nlevel         !< number of vertical level
+
+   NAMELIST /namzps/ &
+   &  dn_e3zps_min, &
+   &  dn_e3zps_rat
+
    NAMELIST /namvar/ &  !< variable namelist
-   &  cn_varinfo, &     !< list of variable and interpolation method to be used. (ex: 'votemper:linear','vosaline:cubic' )
+   &  cn_varinfo, &     !< list of variable and interpolation method to be used.
    &  cn_varfile        !< list of variable file
    
    NAMELIST /namnst/ &  !< nesting namelist
-   &  in_imin0,    &     !< i-direction lower left  point indice 
-   &  in_imax0,    &     !< i-direction upper right point indice
-   &  in_jmin0,    &     !< j-direction lower left  point indice
-   &  in_jmax0,    &     !< j-direction upper right point indice
    &  in_rhoi,    &     !< refinement factor in i-direction
    &  in_rhoj           !< refinement factor in j-direction
@@ -174,6 +338,6 @@
    !-------------------------------------------------------------------
 
-   !1- namelist
-   !1-1 get namelist
+   ! namelist
+   ! get namelist
    il_narg=COMMAND_ARGUMENT_COUNT() !f03 intrinsec
    IF( il_narg/=1 )THEN
@@ -184,5 +348,5 @@
    ENDIF
    
-   !1-2 read namelist
+   ! read namelist
    INQUIRE(FILE=TRIM(cl_namelist), EXIST=ll_exist)
    IF( ll_exist )THEN
@@ -203,18 +367,19 @@
 
       READ( il_fileid, NML = namlog )
-      !1-2-1 define log file
-      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity))
+      ! define log file
+      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity),in_maxerror)
       CALL logger_header()
 
       READ( il_fileid, NML = namcfg )
-      !1-2-2 get variable extra information
+      ! get variable extra information
       CALL var_def_extra(TRIM(cn_varcfg))
 
       READ( il_fileid, NML = namcrs )
       READ( il_fileid, NML = namfin )
+      READ( il_fileid, NML = namzgr )
       READ( il_fileid, NML = namvar )
-      !1-2-3 add user change in extra information
+      ! add user change in extra information
       CALL var_chg_extra(cn_varinfo)
-      !1-2-4 match variable with file
+      ! match variable with file
       tl_multi=multi_init(cn_varfile)
       
@@ -231,11 +396,19 @@
 
       PRINT *,"ERROR in create_restart: can't find "//TRIM(cl_namelist)
-
-   ENDIF
-
-   !2- open files
+      STOP
+
+   ENDIF
+
+   ! 
+   CALL multi_print(tl_multi)
+   IF( tl_multi%i_nvar <= 0 )THEN
+      CALL logger_fatal("CREATE RESTART: no variable to be used."//&
+      &  " check namelist.")
+   ENDIF
+
+   ! open files
    IF( cn_coord0 /= '' )THEN
-      tl_coord0=file_init(TRIM(cn_coord0),id_perio=in_perio0)
-      CALL iom_open(tl_coord0)
+      tl_coord0=mpp_init( file_init(TRIM(cn_coord0)), id_perio=in_perio0)
+      CALL grid_get_info(tl_coord0)
    ELSE
       CALL logger_fatal("CREATE RESTART: no coarse grid coordinate found. "//&
@@ -244,6 +417,6 @@
 
    IF( TRIM(cn_coord1) /= '' )THEN
-      tl_coord1=file_init(TRIM(cn_coord1),id_perio=in_perio1)
-      CALL iom_open(tl_coord1)
+      tl_coord1=mpp_init( file_init(TRIM(cn_coord1)), id_perio=in_perio1)
+      CALL grid_get_info(tl_coord1)
    ELSE
       CALL logger_fatal("CREATE RESTART: no fine grid coordinate found. "//&
@@ -252,6 +425,6 @@
 
    IF( TRIM(cn_bathy1) /= '' )THEN
-      tl_bathy1=file_init(TRIM(cn_bathy1),id_perio=in_perio1)
-      CALL iom_open(tl_bathy1)
+      tl_bathy1=mpp_init( file_init(TRIM(cn_bathy1)), id_perio=in_perio1)
+      CALL grid_get_info(tl_bathy1)
    ELSE
       CALL logger_fatal("CREATE RESTART: no fine grid bathymetry found. "//&
@@ -259,6 +432,14 @@
    ENDIF
 
-   !3- check
-   !3-2-1 check refinement factor
+   ! check
+   ! check output file do not already exist
+   cl_fileout=file_rename(cn_fileout,1)
+   INQUIRE(FILE=TRIM(cl_fileout), EXIST=ll_exist)
+   IF( ll_exist )THEN
+      CALL logger_fatal("CREATE RESTART: output file "//TRIM(cl_fileout)//&
+      &  " already exist.")
+   ENDIF
+
+   ! check refinement factor
    il_rho(:)=1
    IF( in_rhoi < 1 .OR. in_rhoj < 1 )THEN
@@ -270,163 +451,164 @@
    ENDIF
 
-   IF( cn_coord0 /= '' )THEN !.OR. cn_bathy0 /= '' )THEN
-
-      !3-1 check namelist
-      IF( in_imin0 < 1 .OR. in_imax0 < 1 .OR. in_jmin0 < 1 .OR. in_jmax0 < 1)THEN
-         ! compute coarse grid indices around fine grid
-         IF( cn_coord0 /= '' )THEN
-            il_ind(:,:,:)=grid_get_coarse_index(tl_coord0, tl_coord1 )
-         ENDIF
-
-         il_imin0=il_ind(1,1,1) ; il_imax0=il_ind(1,2,1)
-         il_jmin0=il_ind(2,1,1) ; il_jmax0=il_ind(2,2,1)
-
-         il_offset(:,:)=il_ind(:,:,2)
-      ELSE
-         il_imin0=in_imin0 ; il_imax0=in_imax0
-         il_jmin0=in_jmin0 ; il_jmax0=in_jmax0
-
-         il_offset(1,:)=FLOOR(REAL(il_rho(jp_I)-1,dp)*0.5)
-         il_offset(2,:)=FLOOR(REAL(il_rho(jp_J)-1,dp)*0.5)         
-      ENDIF
-
-      !3-2 check domain validity
-      IF( cn_coord0 /= '' )THEN
-         CALL grid_check_dom(tl_coord0, il_imin0, il_imax0, il_jmin0, il_jmax0)
-      ENDIF
-
-      !3-3 check coordinate file
-      IF( cn_coord0 /= '' )THEN
-         CALL grid_check_coincidence( tl_coord0, tl_coord1, &
-         &                            il_imin0, il_imax0, &
-         &                            il_jmin0, il_jmax0, &
-         &                            il_rho(:) )
-      ENDIF
-
-   ENDIF
+   ! check domain indices
+   ! compute coarse grid indices around fine grid
+   il_ind(:,:)=grid_get_coarse_index(tl_coord0, tl_coord1, &
+   &                                 id_rho=il_rho(:))
+
+   il_imin0=il_ind(1,1) ; il_imax0=il_ind(1,2)
+   il_jmin0=il_ind(2,1) ; il_jmax0=il_ind(2,2)
+
+   ! check domain validity
+   CALL grid_check_dom(tl_coord0, il_imin0, il_imax0, il_jmin0, il_jmax0)
+
+   !3-2-4 check coincidence between coarse and fine grid
+   CALL grid_check_coincidence( tl_coord0, tl_coord1, &
+   &                            il_imin0, il_imax0, &
+   &                            il_jmin0, il_jmax0, &
+   &                            il_rho(:) )
 
    ! compute level
-   ALLOCATE(tl_level(ig_npoint))
+   ALLOCATE(tl_level(ip_npoint))
    tl_level(:)=vgrid_get_level(tl_bathy1, cl_namelist )
 
    ! remove ghost cell
-   il_xghost(:)=grid_get_ghost(tl_bathy1)
-
-   DO ji=1,ig_npoint
-      CALL grid_del_ghost(tl_level(ji), il_xghost(1), il_xghost(2))
+   il_xghost(:,:)=grid_get_ghost(tl_bathy1)
+   DO ji=1,ip_npoint
+      CALL grid_del_ghost(tl_level(ji), il_xghost(:,:))
    ENDDO
 
-   ! close
-   CALL iom_close(tl_bathy1)
-
-   !4- work on variables
-   IF( .NOT. ASSOCIATED(tl_multi%t_file) )THEN
+   ! clean
+   CALL mpp_clean(tl_bathy1)
+
+   ! work on variables
+   IF( .NOT. ASSOCIATED(tl_multi%t_mpp) )THEN
       CALL logger_error("CREATE RESTART: no file to work on. "//&
       &                 "check cn_varfile in namelist.")
    ELSE
       ALLOCATE( tl_var( tl_multi%i_nvar ) )
+
       jvar=0
       ! for each file
-      DO ji=1,tl_multi%i_nfile
-         WRITE(cl_data,'(a,i2.2)') 'data_',jvar+1
-
-         IF( .NOT. ASSOCIATED(tl_multi%t_file(ji)%t_var) )THEN
+      DO ji=1,tl_multi%i_nmpp
+         WRITE(cl_data,'(a,i2.2)') 'data-',jvar+1
+
+         IF( .NOT. ASSOCIATED(tl_multi%t_mpp(ji)%t_proc(1)%t_var) )THEN
 
             CALL logger_error("CREATE RESTART: no variable to work on for "//&
-            &                 "file "//TRIM(tl_multi%t_file(ji)%c_name)//&
+            &                 "mpp "//TRIM(tl_multi%t_mpp(ji)%c_name)//&
             &                 ". check cn_varfile in namelist.")
 
-         ELSEIF( TRIM(tl_multi%t_file(ji)%c_name) == TRIM(cl_data) )THEN
-         !4-1 use input matrix to fill variable
-
+         ELSEIF( TRIM(tl_multi%t_mpp(ji)%c_name) == TRIM(cl_data) )THEN
+         !- use input matrix to fill variable
+
+            WRITE(*,'(a)') "work on data"
             ! for each variable initialise from matrix
-            DO jj=1,tl_multi%t_file(ji)%i_nvar
+            DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
+
                jvar=jvar+1
-               tl_tmp=tl_multi%t_file(ji)%t_var(jj)
-               !4-1-1 fill value with matrix data
-               ! pb voir comment gerer nb de dimension
-               tl_var(jvar)=create_restart_matrix(tl_tmp, tl_coord1)
-
-               !4-1-2 use mask
-               CALL create_restart_mask(tl_var(jvar), tl_level(:))
+               
+               WRITE(*,'(2x,a,a)') "work on variable "//&
+               &  TRIM(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
+
+               ! fill value with matrix data
+               tl_var(jvar) = create_restart_matrix( &
+               &  tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj), tl_coord1, &
+               &  in_nlevel, tl_level(:) )
+
             ENDDO
-
+         !- end of use input matrix to fill variable
          ELSE
-         !4-2 use file to fill variable
-
-            ! open file
-            tl_file=file_init(TRIM(tl_multi%t_file(ji)%c_name))
-            CALL iom_open(tl_file)
+         !- use mpp file to fill variable
+
+            WRITE(*,'(a)') "work on file "//TRIM(tl_multi%t_mpp(ji)%c_name)
+            !
+            tl_mpp=mpp_init( file_init(TRIM(tl_multi%t_mpp(ji)%t_proc(1)%c_name)) )
+            CALL grid_get_info(tl_mpp)
+
+            ! check vertical dimension
+            IF( tl_mpp%t_dim(jp_K)%l_use .AND. &
+            &   tl_mpp%t_dim(jp_K)%i_len /= in_nlevel  )THEN
+               CALL logger_error("CREATE RESTART: dimension in file "//&
+               &  TRIM(tl_mpp%c_name)//" not agree with namelist in_nlevel ")
+            ENDIF
+
+            ! open mpp file
+            CALL iom_mpp_open(tl_mpp)
 
             ! get or check depth value
-            IF( tl_file%i_depthid /= 0 )THEN
-               IF( ASSOCIATED(tl_depth%d_value) )THEN
-                  IF( ANY( tl_depth%d_value(:,:,:,:) /= &
-                  &        tl_tmp%d_value(:,:,:,:) ) )THEN
-                     CALL logger_fatal("CREATE RESTART: depth value from "//&
-                     &  TRIM(tl_multi%t_file(ji)%c_name)//" not conform "//&
-                     &  " to those from former file(s).")
-                  ENDIF
-               ELSE
-                  tl_depth=iom_read_var(tl_file,tl_file%i_depthid)
+            CALL create_restart_check_depth( tl_mpp, tl_depth )
+
+            ! get or check time value
+            CALL create_restart_check_time( tl_mpp, tl_time )
+
+            ! close mpp file
+            CALL iom_mpp_close(tl_mpp)
+
+            IF( ANY( tl_mpp%t_dim(1:2)%i_len /= &
+            &        tl_coord0%t_dim(1:2)%i_len) )THEN
+            !!! extract value from fine grid 
+
+               IF( ANY( tl_mpp%t_dim(1:2)%i_len <= &
+               &        tl_coord1%t_dim(1:2)%i_len) )THEN
+                  CALL logger_fatal("CREATE RESTART: dimension in file "//&
+                  &  TRIM(tl_mpp%c_name)//" smaller than those in fine"//&
+                  &  " grid coordinates.")
                ENDIF
-            ENDIF
-
-            ! get or check time value
-            IF( tl_file%i_timeid /= 0 )THEN
-               IF( ASSOCIATED(tl_time%d_value) )THEN
-                  IF( ANY( tl_time%d_value(:,:,:,:) /= &
-                  &        tl_tmp%d_value(:,:,:,:) ) )THEN
-                     CALL logger_fatal("CREATE RESTART: time value from "//&
-                     &  TRIM(tl_multi%t_file(ji)%c_name)//" not conform "//&
-                     &  " to those from former file(s).")
-                  ENDIF
-               ELSE
-                  tl_time=iom_read_var(tl_file,tl_file%i_timeid)
-               ENDIF
-            ENDIF
-
-            IF( ANY( tl_file%t_dim(1:2)%i_len /= &
-            &      tl_coord0%t_dim(1:2)%i_len) )THEN
-            !4-2-1 extract value from fine grid 
-
-               !4-2-1-1 compute domain on fine grid
-               tl_dom1=create__restart_get_dom_coord(tl_file, tl_coord1)
+
+               ! compute domain on fine grid
+               il_ind(:,:)=grid_get_coarse_index(tl_mpp, tl_coord1 )
+
+               il_imin1=il_ind(1,1) ; il_imax1=il_ind(1,2)
+               il_jmin1=il_ind(2,1) ; il_jmax1=il_ind(2,2)
+
+               !- check grid coincidence
+               CALL grid_check_coincidence( tl_mpp, tl_coord1, &
+               &                            il_imin1, il_imax1, &
+               &                            il_jmin1, il_jmax1, &
+               &                            il_rho(:) )
+
+               ! compute domain
+               tl_dom1=dom_init(tl_mpp,         &
+               &                il_imin1, il_imax1, &
+               &                il_jmin1, il_jmax1)
                
-               ! open mpp file on domain
-               !4-2-1-2 init mpp structure
-               tl_mpp=mpp_init(tl_file)
-
-               !4-2-1-3 get processor to be used
-               CALL mpp_get_use( tl_mpp, tl_dom1 )
-               !4-2-1-4 open mpp files
-               CALL iom_mpp_open(tl_mpp)
+               ! open mpp files
+               CALL iom_dom_open(tl_mpp, tl_dom1)
 
                ! for each variable of this file
-               DO jj=1,tl_multi%t_file(ji)%i_nvar
+               DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
+
+                  WRITE(*,'(2x,a,a)') "work on variable "//&
+                  &  TRIM(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
+
                   jvar=jvar+1
-                  cl_name=tl_multi%t_file(ji)%t_var(jj)%c_name
-                  !4-2-1-5 read variable over domain
-                  tl_var(jvar)=iom_mpp_read_var( tl_mpp, TRIM(cl_name), &
-                  &                              td_dom=tl_dom1 )
-
-                  !4-2-1-7 add attribute to variable
+                  cl_name=tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name
+                  ! read variable over domain
+                  tl_var(jvar)=iom_dom_read_var(tl_mpp, TRIM(cl_name), tl_dom1)
+
+                  ! add attribute to variable
                   tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
                   CALL var_move_att(tl_var(jvar), tl_att)
 
+                  tl_att=att_init('src_i_indices',(/il_imin0, il_imax0/))
+                  CALL var_move_att(tl_var(jvar), tl_att)
+
+                  tl_att=att_init('src_j_indices',(/il_jmin0, il_jmax0/))
+                  CALL var_move_att(tl_var(jvar), tl_att)
+
                   ! clean structure
                   CALL att_clean(tl_att)
 
-                  !4-2-1-8 use mask
+                  ! use mask
                   CALL create_restart_mask(tl_var(jvar), tl_level(:))
 
-                  !4-2-1-9 add ghost cell
-                  CALL grid_add_ghost( tl_var(jvar), &
-                  &                    tl_dom1%i_ighost,tl_dom1%i_jghost )
+                  ! add ghost cell
+                  CALL grid_add_ghost( tl_var(jvar), tl_dom1%i_ghost(:,:) )
 
                ENDDO
 
-               !4-2-1-2 close mpp file
-               CALL iom_mpp_close(tl_mpp)
+               ! close mpp file
+               CALL iom_dom_close(tl_mpp)
+
                ! clean structure
                CALL mpp_clean(tl_mpp)
@@ -434,64 +616,75 @@
 
             ELSE
-            !4-2-2 get value from coarse grid 
-
-               !4-2-2-1 compute domain on coarse grid
-               tl_dom0=create__restart_get_dom_index(tl_file, il_imin0, il_jmin0, &
-               &                                              il_imax0, il_jmax0)
-
-               !4-2-2-2 add extra band (if possible) to compute interpolation
+            !!! get value from coarse grid 
+
+               ! compute domain on coarse grid
+               tl_dom0=dom_init(tl_mpp,             &
+               &                il_imin0, il_imax0, &
+               &                il_jmin0, il_jmax0 )
+
+               ! add extra band (if possible) to compute interpolation
                CALL dom_add_extra(tl_dom0)
 
-               ! open mpp file on domain
-               !4-2-2-3 init mpp structure
-               tl_mpp=mpp_init(tl_file)
-
-               !4-2-2-4 get processor to be used
-               CALL mpp_get_use( tl_mpp, tl_dom0 )
-
-               !4-2-2-5 open mpp files
-               CALL iom_mpp_open(tl_mpp)
-
+               ! open mpp files
+               CALL iom_dom_open(tl_mpp, tl_dom0)
                ! for each variable of this file
-               DO jj=1,tl_multi%t_file(ji)%i_nvar
+               DO jj=1,tl_multi%t_mpp(ji)%t_proc(1)%i_nvar
+
+                  WRITE(*,'(2x,a,a)') "work on variable "//&
+                  &  TRIM(tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
 
                   jvar=jvar+1
-                  cl_name=tl_multi%t_file(ji)%t_var(jj)%c_name
-                  print *,'work on ',trim(cl_name)
-                  !4-2-2-6 read variable over domain
-                  tl_var(jvar)=iom_mpp_read_var( tl_mpp, TRIM(cl_name), &
-                  &                              td_dom=tl_dom0 )
-
-                  !4-2-2-7 interpolate variable
+                  cl_name=tl_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name
+
+                  ! read variable over domain
+                  tl_var(jvar)=iom_dom_read_var(tl_mpp, TRIM(cl_name), tl_dom0)
+
+                  il_offset(:,:)=grid_get_fine_offset(tl_coord0, &
+                  &                                   il_imin0, il_jmin0, &
+                  &                                   il_imax0, il_jmax0, &
+                  &                                   tl_coord1, &
+                  &                                   id_rho=il_rho(:), &
+                  &                                   cd_point=TRIM(tl_var(jvar)%c_point))
+                  
+
+                  ! interpolate variable
                   CALL create_restart_interp(tl_var(jvar), tl_level(:), &
                   &                          il_rho(:), &
                   &                          id_offset=il_offset(:,:))
 
-                  !tl_att=att_init('add_offset',0.)
-                  !CALL var_move_att(tl_var(jvar), tl_att)
-                  !tl_att=att_init('scale_factor',1.)
-                  !CALL var_move_att(tl_var(jvar), tl_att)
-
-                  !4-2-2-8 remove extraband added to domain
+                  ! remove extraband added to domain
                   CALL dom_del_extra( tl_var(jvar), tl_dom0, il_rho(:) )
 
-                  !4-2-2-10 add attribute to variable
+                  ! add attribute to variable
                   tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
                   CALL var_move_att(tl_var(jvar), tl_att)
 
+                  tl_att=att_init('src_i-indices',(/il_imin0, il_imax0/))
+                  CALL var_move_att(tl_var(jvar), tl_att)
+
+                  tl_att=att_init('src_j-indices',(/il_jmin0, il_jmax0/))
+                  CALL var_move_att(tl_var(jvar), tl_att)
+
+                  IF( ANY(il_rho(:)/=1) )THEN
+                     tl_att=att_init("refinment_factor", &
+                     &               (/il_rho(jp_I),il_rho(jp_J)/))
+                     CALL var_move_att(tl_var(jvar), tl_att)
+                  ENDIF
+
                   ! clean structure
                   CALL att_clean(tl_att)
 
-                  !4-2-2-11 use mask
+                  ! use mask
                   CALL create_restart_mask(tl_var(jvar), tl_level(:))
 
-                  !4-2-2-12 add ghost cell
-                  CALL grid_add_ghost( tl_var(jvar), &
-                  &                    tl_dom0%i_ighost,tl_dom0%i_jghost )
+                  ! add ghost cell
+                  CALL grid_add_ghost( tl_var(jvar), il_xghost(:,:) )
+
 
                ENDDO
 
-               !4-2-2-2 close mpp file
-               CALL iom_mpp_close(tl_mpp)
+               ! close mpp file
+               CALL iom_dom_close(tl_mpp)
+
                ! clean structure
                CALL mpp_clean(tl_mpp)
@@ -500,29 +693,33 @@
             ENDIF
 
-            ! close file
-            CALL iom_close(tl_file)
             ! clean structure
-            CALL file_clean(tl_file)
+            CALL mpp_clean(tl_mpp)
          ENDIF
       ENDDO
    ENDIF
 
-   !5- use additional request
-   DO jvar=1,tl_multi%i_nvar
-
-         !5-1 forced min and max value
-         CALL var_limit_value(tl_var(jvar))
-
-         !5-2 filter
-         CALL filter_fill_value(tl_var(jvar))
-
-         !5-3 extrapolate
-         CALL extrap_fill_value(tl_var(jvar), id_iext=in_extrap, &
-         &                                    id_jext=in_extrap, &
-         &                                    id_kext=in_extrap)
+   il_nvar=tl_multi%i_nvar
+
+   ! clean
+   CALL multi_clean(tl_multi)
+   CALL mpp_clean(tl_coord0)
+
+   ! use additional request
+   DO jvar=1,il_nvar
+
+      ! forced min and max value
+      CALL var_limit_value(tl_var(jvar))
+
+      ! filter
+      CALL filter_fill_value(tl_var(jvar))
+
+      ! extrapolate
+      CALL extrap_fill_value(tl_var(jvar), id_iext=in_extrap, &
+      &                                    id_jext=in_extrap, &
+      &                                    id_kext=in_extrap)
 
    ENDDO
 
-   !6- create file
+   ! create file
    IF( in_niproc == 0 .AND. &
    &   in_njproc == 0 .AND. &
@@ -532,10 +729,18 @@
       in_nproc = 1
    ENDIF
-   tl_mppout=mpp_init( TRIM(cn_fileout), tl_var(1), &
-   &                   in_niproc, in_njproc, in_nproc, &
-   &                   cd_type=cn_type)
-
-   !6-1 add dimension
+
+   ! add dimension
    tl_dim(:)=var_max_dim(tl_var(:))
+
+   DO ji=1,il_nvar
+
+      IF( ALL(tl_var(ji)%t_dim(:)%i_len == tl_dim(:)%i_len) )THEN
+         tl_mppout=mpp_init( TRIM(cn_fileout), tl_var(ji), &
+         &                   in_niproc, in_njproc, in_nproc, &
+         &                   cd_type=cn_type)
+         EXIT
+      ENDIF
+
+   ENDDO
 
    DO ji=1,ip_maxdim
@@ -551,43 +756,61 @@
    ENDDO
 
-   !6-2 add variables
-
-   !IF( ALL( tl_dim(1:2)%l_use ) )THEN
-   !   ! add longitude
-   !   tl_lon=iom_read_var(tl_coord1,'longitude')
-
-   !   CALL mpp_add_var(tl_mppout, tl_lon)
-   !   CALL var_clean(tl_lon)
-
-   !   ! add latitude
-   !   tl_lat=iom_read_var(tl_coord1,'latitude')
-
-   !   CALL mpp_add_var(tl_mppout, tl_lat)
-   !   CALL var_clean(tl_lat)
-   !ENDIF
-
-   !IF( tl_dim(3)%l_use )THEN
-   !   ! add depth
-   !   CALL mpp_add_var(tl_mppout, tl_depth)
-   !   CALL var_clean(tl_depth)
-   !ENDIF
-
-   !IF( tl_dim(4)%l_use )THEN
-   !   ! add time
-   !   CALL mpp_add_var(tl_mppout, tl_time)
-   !   CALL var_clean(tl_time)
-   !ENDIF
+   ! add variables
+   IF( ALL( tl_dim(1:2)%l_use ) )THEN
+
+      ! open mpp files
+      CALL iom_mpp_open(tl_coord1)
+
+      ! add longitude
+      tl_lon=iom_mpp_read_var(tl_coord1,'longitude')
+      CALL mpp_add_var(tl_mppout, tl_lon)
+      CALL var_clean(tl_lon)
+
+      ! add latitude
+      tl_lat=iom_mpp_read_var(tl_coord1,'latitude')
+      CALL mpp_add_var(tl_mppout, tl_lat)
+      CALL var_clean(tl_lat)
+
+      ! close mpp files
+      CALL iom_mpp_close(tl_coord1)
+
+   ENDIF
+
+   IF( tl_dim(3)%l_use )THEN
+      IF( ASSOCIATED(tl_depth%d_value) )THEN
+         ! add depth
+         CALL mpp_add_var(tl_mppout, tl_depth)
+      ELSE
+         CALL logger_error("CREATE RESTART: no value for depth variable.")
+      ENDIF
+   ENDIF
+   IF( ASSOCIATED(tl_depth%d_value) ) CALL var_clean(tl_depth)
+
+   IF( tl_dim(4)%l_use )THEN
+      IF( ASSOCIATED(tl_time%d_value) )THEN
+         ! add time
+         CALL mpp_add_var(tl_mppout, tl_time)
+      ELSE
+         CALL logger_error("CREATE RESTART: no value for time variable.")
+      ENDIF
+   ENDIF
+   IF( ASSOCIATED(tl_time%d_value) ) CALL var_clean(tl_time)
 
    ! add other variable
-   DO jvar=1,tl_multi%i_nvar
-      CALL mpp_add_var(tl_mppout, tl_var(jvar))
-      CALL var_clean(tl_var(jvar))
+   DO jvar=1,il_nvar
+      ! check if variable already add
+      il_index=var_get_index(tl_mppout%t_proc(1)%t_var(:), tl_var(jvar)%c_name)
+      IF( il_index == 0 )THEN
+         CALL mpp_add_var(tl_mppout, tl_var(jvar))
+         CALL var_clean(tl_var(jvar))
+      ENDIF
    ENDDO
 
-   DO ji=1,4
-      CALL mpp_add_var(tl_mppout,tl_level(ji))
-   ENDDO
-
-   !6-3 add some attribute
+!   DO ji=1,4
+!      CALL grid_add_ghost( tl_level(ji), il_xghost(:,:) )
+!      CALL var_clean(tl_level(ji))
+!   ENDDO
+
+   ! add some attribute
    tl_att=att_init("Created_by","SIREN create_restart")
    CALL mpp_add_att(tl_mppout, tl_att)
@@ -616,20 +839,24 @@
    ENDIF
 
-   !6-4 create file
+   ! create file
    CALL iom_mpp_create(tl_mppout)
 
-   !6-5 write file
+   ! write file
    CALL iom_mpp_write_file(tl_mppout)
-
-   !6-6 close file
+   ! close file
    CALL iom_mpp_close(tl_mppout)
-   IF( cn_coord0 /= '' ) CALL iom_close(tl_coord0)
-
-   !7- clean
+
+   ! print
+   CALL mpp_print(tl_mppout)
+
+   ! clean
+   CALL att_clean(tl_att)
+   CALL var_clean(tl_var(:))
    DEALLOCATE(tl_var)
+   CALL var_clean(tl_level(:))
+   DEALLOCATE(tl_level)
 
    CALL mpp_clean(tl_mppout)
-   CALL file_clean(tl_coord1)
-   CALL file_clean(tl_coord0)
+   CALL mpp_clean(tl_coord1)
 
    ! close log file
@@ -637,60 +864,5 @@
    CALL logger_close()
 
-!> @endcode
 CONTAINS
-   !-------------------------------------------------------------------
-   !> @brief
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create_restart_level(td_level1)
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TFILE), INTENT(IN) :: td_level1
-
-      ! function
-      TYPE(TVAR), DIMENSION(4) :: create_restart_level
-
-      ! local variable
-      TYPE(TFILE)              :: tl_level1
-      TYPE(TVAR), DIMENSION(4) :: tl_var
-      TYPE(TMPP)               :: tl_mpplevel1
-
-      ! loop indices
-      !----------------------------------------------------------------
-
-      !0- compute domain
-      tl_dom1=dom_init(td_level1)
-
-      !1 init mpp structure
-      tl_level1=td_level1
-      tl_mpplevel1=mpp_init(tl_level1)
-      
-      CALL file_clean(tl_level1)
-
-      !2 get processor to be used
-      CALL mpp_get_use( tl_mpplevel1, tl_dom1 )
-
-      !3 open mpp files
-      CALL iom_mpp_open(tl_mpplevel1)
-      tl_var(jp_T)=iom_mpp_read_var(tl_mpplevel1,'tlevel',td_dom=tl_dom1)
-      tl_var(jp_U)=iom_mpp_read_var(tl_mpplevel1,'ulevel',td_dom=tl_dom1)
-      tl_var(jp_V)=iom_mpp_read_var(tl_mpplevel1,'vlevel',td_dom=tl_dom1)
-      tl_var(jp_F)=iom_mpp_read_var(tl_mpplevel1,'flevel',td_dom=tl_dom1)
-
-      !4 save result
-      create_restart_level(:)=tl_var(:)
-
-      !5 clean
-      CALL iom_mpp_close(tl_mpplevel1)
-      CALL mpp_clean(tl_mpplevel1)
-
-   END FUNCTION create_restart_level
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -699,21 +871,24 @@
    !> @details 
    !> A variable is create with the same name that the input variable, 
-   !> and with dimension of the coordinate file. 
-   !> Then the variable table of value is split into equal subdomain.
-   !> Each subdomain is fill with the linked value of the matrix.
+   !> and with dimension of the coordinate file.<br/> 
+   !> Then the variable array of value is split into equal subdomain.
+   !> Each subdomain is filled with the corresponding value of the matrix.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !>
-   !> @param[in] td_var : variable structure 
-   !> @param[in] td_coord : coordinate 
+   !> @param[in] td_var    variable structure 
+   !> @param[in] td_coord  coordinate file structure 
+   !> @param[in] id_nlevel number of vertical level  
+   !> @param[in] td_level  array of level on T,U,V,F point (variable structure) 
    !> @return variable structure 
    !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create_restart_matrix(td_var, td_coord)
+   FUNCTION create_restart_matrix(td_var, td_coord, id_nlevel, td_level)
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(IN) :: td_var
-      TYPE(TFILE), INTENT(IN) :: td_coord
+      TYPE(TVAR)              , INTENT(IN) :: td_var
+      TYPE(TMPP)              , INTENT(IN) :: td_coord
+      INTEGER(i4)             , INTENT(IN) :: id_nlevel
+      TYPE(TVAR), DIMENSION(:), INTENT(IN) :: td_level
 
       ! function
@@ -721,10 +896,8 @@
 
       ! local variable
-      INTEGER(i4)                                        :: il_ighost
-      INTEGER(i4)                                        :: il_jghost
-      INTEGER(i4)      , DIMENSION(2)                    :: il_xghost
       INTEGER(i4)      , DIMENSION(3)                    :: il_dim
       INTEGER(i4)      , DIMENSION(3)                    :: il_size
       INTEGER(i4)      , DIMENSION(3)                    :: il_rest
+      INTEGER(i4)      , DIMENSION(2,2)                  :: il_xghost
 
       INTEGER(i4)      , DIMENSION(:)      , ALLOCATABLE :: il_ishape
@@ -734,7 +907,4 @@
       REAL(dp)         , DIMENSION(:,:,:,:), ALLOCATABLE :: dl_value
 
-      TYPE(TVAR)                                         :: tl_lon
-      TYPE(TVAR)                                         :: tl_lat
-      TYPE(TVAR)                                         :: tl_var
       TYPE(TDIM)       , DIMENSION(ip_maxdim)            :: tl_dim
 
@@ -745,25 +915,22 @@
       !----------------------------------------------------------------
 
-      !1- read output grid
-      tl_lon=iom_read_var(td_coord,'longitude')
-      tl_lat=iom_read_var(td_coord,'latitude')
-
-      !2- look for ghost cell
-      il_xghost(:)=grid_get_ghost( tl_lon, tl_lat )
-
-      il_ighost=il_xghost(1)*ig_ghost
-      il_jghost=il_xghost(2)*ig_ghost
-      
-      !3- write value on grid
-      !3-1 get matrix dimension
+      ! look for ghost cell
+      il_xghost(:,:)=grid_get_ghost( td_coord )
+
+      ! write value on grid
+      ! get matrix dimension
       il_dim(:)=td_var%t_dim(1:3)%i_len
-      !3-2 output dimension
-      tl_dim(:)=tl_lon%t_dim(:)
+
+      ! output dimension
+      tl_dim(jp_I:jp_J)=dim_copy(td_coord%t_dim(jp_I:jp_J))
+      IF( id_nlevel >= 1 )THEN
+         tl_dim(jp_K)=dim_init('Z',id_nlevel)
+      ENDIF
 
       ! remove ghost cell
-      tl_dim(1)%i_len=tl_dim(1)%i_len - 2*il_xghost(1)*ig_ghost
-      tl_dim(2)%i_len=tl_dim(2)%i_len - 2*il_xghost(2)*ig_ghost
-
-      !3-3 split output domain in N subdomain depending of matrix dimension 
+      tl_dim(jp_I)%i_len=tl_dim(jp_I)%i_len - SUM(il_xghost(jp_I,:))*ip_ghost
+      tl_dim(jp_J)%i_len=tl_dim(jp_J)%i_len - SUM(il_xghost(jp_J,:))*ip_ghost
+
+      ! split output domain in N subdomain depending of matrix dimension 
       il_size(:) = tl_dim(1:3)%i_len / il_dim(:)
       il_rest(:) = MOD(tl_dim(1:3)%i_len, il_dim(:))
@@ -776,5 +943,4 @@
       ! add rest to last cell
       il_ishape(il_dim(1)+1)=il_ishape(il_dim(1)+1)+il_rest(1)
-      
 
       ALLOCATE( il_jshape(il_dim(2)+1) )
@@ -794,5 +960,5 @@
       il_kshape(il_dim(3)+1)=il_kshape(il_dim(3)+1)+il_rest(3)
 
-      !3-3 write ouput table of value 
+      ! write ouput array of value 
       ALLOCATE(dl_value( tl_dim(1)%i_len, &
       &                  tl_dim(2)%i_len, &
@@ -815,160 +981,37 @@
       ENDDO
 
-      !3-4 initialise variable with value
-      tl_var=var_init(TRIM(td_var%c_name),dl_value(:,:,:,:))
+      ! keep attribute and type
+      create_restart_matrix=var_copy(td_var)
+      DEALLOCATE( create_restart_matrix%d_value )
+      ! save new dimension
+      create_restart_matrix%t_dim(:)=dim_copy(tl_dim(:))
+      ! add variable value
+      CALL var_add_value( create_restart_matrix, dl_value(:,:,:,:), &
+      &                   id_type=td_var%i_type)
 
       DEALLOCATE(dl_value)
 
-      !4- add ghost cell
-      CALL grid_add_ghost(tl_var,il_ighost,il_jghost)
-
-      !5- save result
-      create_restart_matrix=tl_var
+      ! use mask
+      CALL create_restart_mask(create_restart_matrix, td_level(:))
+
+      ! add ghost cell
+      CALL grid_add_ghost( create_restart_matrix, il_xghost(:,:) )
+
+      ! clean 
+      DEALLOCATE(il_ishape)
+      DEALLOCATE(il_jshape)
+      DEALLOCATE(il_kshape)
 
    END FUNCTION create_restart_matrix
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
+   !> This subroutine use mask to filled land point with _FillValue
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_mask   mask variable structure
    !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create__restart_get_dom_coord( td_file, td_coord, &
-   &                                       id_rho )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TFILE),               INTENT(IN) :: td_file
-      TYPE(TFILE),               INTENT(IN) :: td_coord
-      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
-
-      ! function
-      TYPE(TDOM) :: create__restart_get_dom_coord
-
-      ! local variable
-      INTEGER(i4)                 :: il_pivot
-      INTEGER(i4)                 :: il_perio
-
-      INTEGER(i4)                 :: il_imin
-      INTEGER(i4)                 :: il_imax
-      INTEGER(i4)                 :: il_jmin
-      INTEGER(i4)                 :: il_jmax
-
-      INTEGER(i4), DIMENSION(2,2,2) :: il_ind
-
-      TYPE(TFILE)                 :: tl_file
-
-      TYPE(TDOM)                  :: tl_dom
-      ! loop indices
-      !----------------------------------------------------------------
-
-      tl_file=td_file
-      !1- open file
-      CALL iom_open(tl_file)
-
-      ! get periodicity
-      il_pivot=grid_get_pivot(tl_file)
-      il_perio=grid_get_perio(tl_file,il_pivot)
-
-      tl_file%i_perio=il_perio
-
-      !2- compute file grid indices around coord grid
-      il_ind(:,:,:)=grid_get_coarse_index(tl_file, td_coord )
-
-      il_imin=il_ind(1,1,1) ; il_imax=il_ind(1,2,1)
-      il_jmin=il_ind(2,1,1) ; il_jmax=il_ind(2,2,1)
-
-      !3- check grid coincidence
-      CALL grid_check_coincidence( tl_file, td_coord, &
-      &                            il_imin, il_imax, &
-      &                            il_jmin, il_jmax, &
-      &                            id_rho(:) )
-
-      !4- compute domain
-      tl_dom=dom_init(tl_file,         &
-      &               il_imin, il_imax, &
-      &               il_jmin, il_jmax)
-
-      ! close file
-      CALL iom_close(tl_file)
-
-      ! save result
-      create__restart_get_dom_coord=tl_dom
-
-   END FUNCTION create__restart_get_dom_coord
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create__restart_get_dom_index( td_file, id_imin, id_jmin, &
-   &                                                id_imax, id_jmax )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TFILE), INTENT(IN) :: td_file
-      INTEGER(i4), INTENT(IN) :: id_imin
-      INTEGER(i4), INTENT(IN) :: id_imax
-      INTEGER(i4), INTENT(IN) :: id_jmin
-      INTEGER(i4), INTENT(IN) :: id_jmax
-
-      ! function
-      TYPE(TDOM) :: create__restart_get_dom_index
-
-      ! local variable
-      INTEGER(i4)                 :: il_pivot
-      INTEGER(i4)                 :: il_perio
-
-      TYPE(TFILE)                 :: tl_file
-
-      TYPE(TDOM)                  :: tl_dom
-      ! loop indices
-      !----------------------------------------------------------------
-
-      ! init
-      tl_file=td_file
-      !1- open file
-      CALL iom_open(tl_file)
-
-      ! get periodicity
-      il_pivot=grid_get_pivot(tl_file)
-      il_perio=grid_get_perio(tl_file,il_pivot)
-
-      tl_file%i_perio=il_perio
-
-      !2- compute domain
-      tl_dom=dom_init(tl_file,         &
-      &               id_imin, id_imax, &
-      &               id_jmin, id_jmax)
-
-      ! close file
-      CALL iom_close(tl_file)
-
-      ! save result
-      create__restart_get_dom_index=tl_dom
-
-   END FUNCTION create__restart_get_dom_index
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] 
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE create_restart_mask( td_var, td_mask )
 
@@ -987,192 +1030,54 @@
       !----------------------------------------------------------------
 
-      IF( ANY(td_var%t_dim(1:2)%i_len /= td_mask(1)%t_dim(1:2)%i_len) )THEN
-         CALL logger_error("CREATE RESTART MASK: dimension differ between "//&
-         &                 "variable ("//&
-         &                 TRIM(fct_str(td_var%t_dim(1)%i_len))//","//&
-         &                 TRIM(fct_str(td_var%t_dim(2)%i_len))//&
-         &                 ") and level ("//&
-         &                 TRIM(fct_str(td_mask(1)%t_dim(1)%i_len))//","//&
-         &                 TRIM(fct_str(td_mask(1)%t_dim(2)%i_len))//")")
-      ELSE
-         ALLOCATE( il_mask(td_var%t_dim(1)%i_len, &
-         &                 td_var%t_dim(2)%i_len) )
-
-         SELECT CASE(TRIM(td_var%c_point))
-         CASE('T')
-            il_mask(:,:)=INT(td_mask(jp_T)%d_value(:,:,1,1))
-         CASE('U')
-            il_mask(:,:)=INT(td_mask(jp_U)%d_value(:,:,1,1))
-         CASE('V')
-            il_mask(:,:)=INT(td_mask(jp_V)%d_value(:,:,1,1))
-         CASE('F')
-            il_mask(:,:)=INT(td_mask(jp_F)%d_value(:,:,1,1))
-         END SELECT
-
-         DO jl=1,td_var%t_dim(4)%i_len
-            DO jk=1,td_var%t_dim(3)%i_len
-               WHERE( il_mask(:,:) < jk ) td_var%d_value(:,:,jk,jl)=99 !td_var%d_fill
-                  !.AND. &
-                  !&   td_var%d_value(:,:,jk,jl) == td_var%d_fill .OR. &
-                  !&   il_mask(:,:) < jk .AND. &
-                  !&   td_var%d_value(:,:,jk,jl) == 1 ) td_var%d_value(:,:,jk,jl)=99 !td_var%d_fill
+      IF( ALL(td_var%t_dim(1:2)%l_use) )THEN
+         IF( ANY(td_var%t_dim(1:2)%i_len /= td_mask(1)%t_dim(1:2)%i_len) )THEN
+            CALL logger_error("CREATE RESTART MASK: dimension differ between"//&
+            &                 " variable "//TRIM(td_var%c_name)//" ("//&
+            &                 TRIM(fct_str(td_var%t_dim(1)%i_len))//","//&
+            &                 TRIM(fct_str(td_var%t_dim(2)%i_len))//&
+            &                 ") and level ("//&
+            &                 TRIM(fct_str(td_mask(1)%t_dim(1)%i_len))//","//&
+            &                 TRIM(fct_str(td_mask(1)%t_dim(2)%i_len))//")")
+         ELSE
+            ALLOCATE( il_mask(td_var%t_dim(1)%i_len, &
+            &                 td_var%t_dim(2)%i_len) )
+
+            SELECT CASE(TRIM(td_var%c_point))
+            CASE('T')
+               il_mask(:,:)=INT(td_mask(jp_T)%d_value(:,:,1,1))
+            CASE('U')
+               il_mask(:,:)=INT(td_mask(jp_U)%d_value(:,:,1,1))
+            CASE('V')
+               il_mask(:,:)=INT(td_mask(jp_V)%d_value(:,:,1,1))
+            CASE('F')
+               il_mask(:,:)=INT(td_mask(jp_F)%d_value(:,:,1,1))
+            END SELECT
+
+            DO jl=1,td_var%t_dim(4)%i_len
+               DO jk=1,td_var%t_dim(3)%i_len
+                  WHERE( il_mask(:,:) < jk )
+                     td_var%d_value(:,:,jk,jl)=td_var%d_fill
+                  END WHERE
+               ENDDO
             ENDDO
-         ENDDO
-
-         DEALLOCATE( il_mask )
+
+            DEALLOCATE( il_mask )
+         ENDIF
       ENDIF
    END SUBROUTINE create_restart_mask
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine interpolate variable
    !> 
-   !> @details 
-   !>
    !> @author J.Paul
    !> - Nov, 2013- Initial Version
    !>
-   !> @param[in] 
+   !> @param[inout] td_var    variable structure 
+   !> @param[inout] td_level  fine grid level, array of variable structure
+   !> @param[in] id_rho       array of refinment factor
+   !> @param[in] id_offset    array of offset between fine and coarse grid
+   !> @param[in] id_iext      i-direction size of extra bands (default=im_minext)
+   !> @param[in] id_jext      j-direction size of extra bands (default=im_minext)
    !-------------------------------------------------------------------
-   !> @code
-   FUNCTION create_restart_extract(td_var, td_file, &
-   &                             td_coord)
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TVAR) , INTENT(IN) :: td_var  
-      TYPE(TFILE), INTENT(IN) :: td_file
-      TYPE(TFILE), INTENT(IN) :: td_coord
-
-      ! function
-      TYPE(TVAR) :: create_restart_extract
-
-      ! local variable
-      INTEGER(i4), DIMENSION(2,2,2) :: il_ind
-
-      INTEGER(i4) :: il_pivot
-      INTEGER(i4) :: il_perio
-
-      INTEGER(i4) :: il_imin
-      INTEGER(i4) :: il_jmin
-      INTEGER(i4) :: il_imax
-      INTEGER(i4) :: il_jmax
-
-      TYPE(TFILE) :: tl_file
-
-      TYPE(TMPP)  :: tl_mpp
-
-      TYPE(TATT)  :: tl_att
-
-      TYPE(TVAR)  :: tl_var
-      
-      TYPE(TDOM)  :: tl_dom
-      ! loop indices
-      !----------------------------------------------------------------
-
-      IF( td_file%i_id == 0 )THEN
-         CALL logger_error("CREATE RESTART EXTRACT: file "//&
-         &  TRIM(td_file%c_name)//" not opened ")
-      ELSE
-
-         !init
-         tl_file=td_file
-
-         !1- open file
-         CALL iom_open(tl_file)
-
-         ! get periodicity
-         il_pivot=grid_get_pivot(tl_file)
-         il_perio=grid_get_perio(tl_file,il_pivot)
-
-         tl_file%i_perio=il_perio
-
-         !2- compute file grid indices around coord grid
-         il_ind(:,:,:)=grid_get_coarse_index(tl_file, td_coord )
-
-         il_imin=il_ind(1,1,1) ; il_imax=il_ind(1,2,1)
-         il_jmin=il_ind(2,1,1) ; il_jmax=il_ind(2,2,1)
-   
-         !3- check grid coincidence
-         CALL grid_check_coincidence( tl_file, td_coord, &
-         &                            il_imin, il_imax, &
-         &                            il_jmin, il_jmax, &
-         &                            (/1, 1, 1/) )
-
-         !4- compute domain
-         tl_dom=dom_init(tl_file,         &
-         &               il_imin, il_imax, &
-         &               il_jmin, il_jmax)
-
-         ! close file
-         CALL iom_close(tl_file)
-
-         !5- read bathymetry on domain (ugly way to do it, have to work on it)
-         !5-1 init mpp structure
-         tl_mpp=mpp_init(tl_file)
-
-         CALL file_clean(tl_file)
-
-         !5-2 get processor to be used
-         CALL mpp_get_use( tl_mpp, tl_dom )
-
-         !5-3 open mpp files
-         CALL iom_mpp_open(tl_mpp)
-
-         !5-4 read variable on domain
-         tl_var=iom_mpp_read_var(tl_mpp,TRIM(td_var%c_name),td_dom=tl_dom)
-
-         !5-5 close mpp file
-         CALL iom_mpp_close(tl_mpp)
-
-         !6- add ghost cell
-         CALL grid_add_ghost(tl_var,tl_dom%i_ighost,tl_dom%i_jghost)
-
-         !7- check result
-         IF( ANY( tl_var%t_dim(:)%l_use .AND. &
-         &        tl_var%t_dim(:)%i_len /= td_coord%t_dim(:)%i_len) )THEN
-            CALL logger_debug("CREATE BATHY EXTRACT: "//&
-            &        "dimensoin of variable "//TRIM(td_var%c_name)//" "//&
-            &        TRIM(fct_str(tl_var%t_dim(1)%i_len))//","//&
-            &        TRIM(fct_str(tl_var%t_dim(2)%i_len))//","//&
-            &        TRIM(fct_str(tl_var%t_dim(3)%i_len))//","//&
-            &        TRIM(fct_str(tl_var%t_dim(4)%i_len)) )
-            CALL logger_debug("CREATE BATHY EXTRACT: "//&
-            &        "dimensoin of coordinate file "//&
-            &        TRIM(fct_str(td_coord%t_dim(1)%i_len))//","//&
-            &        TRIM(fct_str(td_coord%t_dim(2)%i_len))//","//&
-            &        TRIM(fct_str(td_coord%t_dim(3)%i_len))//","//&
-            &        TRIM(fct_str(td_coord%t_dim(4)%i_len)) )
-            CALL logger_fatal("CREATE BATHY EXTRACT: "//&
-            &  "dimensoin of extracted "//&
-            &  "variable and coordinate file dimension differ")
-         ENDIF
-
-         !8- add attribute to variable
-         tl_att=att_init('src_file',TRIM(fct_basename(tl_mpp%c_name)))
-         CALL var_move_att(tl_var, tl_att)         
-
-         !9- save result
-         create_restart_extract=tl_var
-
-         ! clean structure
-         CALL var_clean(tl_var)
-         CALL mpp_clean(tl_mpp)
-      ENDIF
-
-   END FUNCTION create_restart_extract
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] 
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE create_restart_interp( td_var, td_level,&
    &                                 id_rho,          &
@@ -1191,6 +1096,4 @@
 
       ! local variable
-      TYPE(TVAR)  :: tl_var
-
       INTEGER(i4) :: il_iext
       INTEGER(i4) :: il_jext
@@ -1198,7 +1101,4 @@
       ! loop indices
       !----------------------------------------------------------------
-
-      ! copy variable
-      tl_var=td_var
 
       il_iext=3
@@ -1220,31 +1120,128 @@
       ENDIF
 
-      il_iext=0
-      il_jext=0
-
       ! work on variable
-      !1 add extraband
-      CALL extrap_add_extrabands(tl_var, il_iext, il_jext)
-
-      !2 extrapolate variable
-      CALL extrap_fill_value( tl_var, td_level(:),    &
+      ! add extraband
+      CALL extrap_add_extrabands(td_var, il_iext, il_jext)
+
+      ! extrapolate variable
+      CALL extrap_fill_value( td_var, td_level(:),    &
       &                               id_offset(:,:), &
       &                               id_rho(:),      &
       &                               id_iext=il_iext, id_jext=il_jext )
 
-      !3 interpolate variable
-      CALL interp_fill_value( tl_var, id_rho(:), &
+      ! interpolate variable
+      CALL interp_fill_value( td_var, id_rho(:), &
       &                       id_offset=id_offset(:,:) )
 
-      !4 remove extraband
-      CALL extrap_del_extrabands(tl_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
-
-      !5- save result
-      td_var=tl_var
-
-      ! clean variable structure
-      CALL var_clean(tl_var)
+      ! remove extraband
+      CALL extrap_del_extrabands(td_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
 
    END SUBROUTINE create_restart_interp
-   !> @endcode
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine get depth variable value in an open mpp structure
+   !> and check if agree with already input depth variable.
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - November, 2014- Initial Version
+   !>
+   !> @param[in] td_mpp       mpp structure
+   !> @param[inout] td_depth  depth variable structure 
+   !-------------------------------------------------------------------
+   SUBROUTINE create_restart_check_depth( td_mpp, td_depth )
+
+      IMPLICIT NONE
+
+      ! Argument
+      TYPE(TMPP), INTENT(IN   ) :: td_mpp
+      TYPE(TVAR), INTENT(INOUT) :: td_depth
+
+      ! local variable
+      INTEGER(i4) :: il_varid
+      TYPE(TVAR)  :: tl_depth
+      ! loop indices
+      !----------------------------------------------------------------
+
+      ! get or check depth value
+      IF( td_mpp%t_proc(1)%i_depthid /= 0 )THEN
+
+         il_varid=td_mpp%t_proc(1)%i_depthid
+         IF( ASSOCIATED(td_depth%d_value) )THEN
+
+            tl_depth=iom_mpp_read_var(td_mpp, il_varid)
+            IF( ANY( td_depth%d_value(:,:,:,:) /= &
+            &        tl_depth%d_value(:,:,:,:) ) )THEN
+
+               CALL logger_fatal("CREATE BOUNDARY: depth value from "//&
+               &  TRIM(tl_multi%t_mpp(ji)%c_name)//" not conform "//&
+               &  " to those from former file(s).")
+
+            ENDIF
+            CALL var_clean(tl_depth)
+
+         ELSE
+            td_depth=iom_mpp_read_var(td_mpp,il_varid)
+         ENDIF
+
+      ENDIF
+      
+   END SUBROUTINE create_restart_check_depth
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine get date and time in an open mpp structure
+   !> and check if agree with date and time already read.
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - November, 2014- Initial Version
+   !>
+   !> @param[in] td_mpp      mpp structure
+   !> @param[inout] td_time  time variable structure 
+   !-------------------------------------------------------------------
+   SUBROUTINE create_restart_check_time( td_mpp, td_time )
+
+      IMPLICIT NONE
+
+      ! Argument
+      TYPE(TMPP), INTENT(IN   ) :: td_mpp
+      TYPE(TVAR), INTENT(INOUT) :: td_time
+
+      ! local variable
+      INTEGER(i4) :: il_varid
+      TYPE(TVAR)  :: tl_time
+
+      TYPE(TDATE) :: tl_date1
+      TYPE(TDATE) :: tl_date2
+      ! loop indices
+      !----------------------------------------------------------------
+
+      ! get or check depth value
+      IF( td_mpp%t_proc(1)%i_timeid /= 0 )THEN
+
+         il_varid=td_mpp%t_proc(1)%i_timeid
+         IF( ASSOCIATED(td_time%d_value) )THEN
+
+            tl_time=iom_mpp_read_var(td_mpp, il_varid)
+
+            tl_date1=var_to_date(td_time)
+            tl_date2=var_to_date(tl_time)
+            IF( tl_date1 - tl_date2 /= 0 )THEN
+
+               CALL logger_fatal("CREATE BOUNDARY: date from "//&
+               &  TRIM(tl_multi%t_mpp(ji)%c_name)//" not conform "//&
+               &  " to those from former file(s).")
+
+            ENDIF
+            CALL var_clean(tl_time)
+
+         ELSE
+            td_time=iom_mpp_read_var(td_mpp,il_varid)
+         ENDIF
+
+      ENDIF
+      
+   END SUBROUTINE create_restart_check_time
 END PROGRAM create_restart
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/date.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/date.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/date.f90	(revision 5075)
@@ -7,70 +7,122 @@
 ! DESCRIPTION:
 !> @brief This module provide the calculation of Julian dates, and
-!> do many manipulations with dates.<br/>
-!> Actually we use Modified Julian Dates, with origin the 
-!> 17 Nov 1858 at 00:00:00
-!
+!> do many manipulations with dates.
+!>
 !> @details
+!> Actually we use Modified Julian Dates, with  
+!> 17 Nov 1858 at 00:00:00 as origin.<br/>
+!>
 !>   define type TDATE:<br/>
-!>   TYPE(TDATE) :: tl_date1<br/>
+!> @code
+!>   TYPE(TDATE) :: tl_date1
+!> @endcode
 !>   default date is 17 Nov 1858 at 00:00:00<br/>
 !>
 !>   to intialise date : <br/>
-!>   - from date of the day at 12:00:00 : tl_date1=date_today()<br/>
-!>   - from date and time of the day    : tl_date1=date_now()<br/>
-!>   - from julian day                  : tl_date1=date_init(1.)<br/>  
-!>   - from year month day              : tl_date1=date_init(2012,12,10)<br/>
+!>   - from date of the day at 12:00:00 : 
+!> @code
+!> tl_date1=date_today()
+!> @endcode
+!>   - from date and time of the day    : 
+!> @code
+!> tl_date1=date_now()
+!> @endcode
+!>   - from julian day                  : 
+!> @code
+!> tl_date1=date_init(dd_jd)
+!> @endcode
+!>      - dd_jd julian day (double precision) 
+!>   - from number of second since julian day origin   : 
+!> @code
+!> tl_date1=date_init(kd_nsec)
+!> @endcode
+!>      - kd_nsec number of second (integer 8) 
+!>   - from year month day              : 
+!> @code
+!> tl_date1=date_init(2012,12,10)
+!> @endcode
+!>   - from string character formatted date  : 
+!> @code
+!> tl_date1=date_init(cd_fmtdate)
+!> @endcode
+!>      - cd_fmtdate date in format YYYY-MM-DD hh:mm:ss
 !>
 !>   to print date in format YYYY-MM-DD hh:mm:ss<br/>
 !>   CHARACTER(LEN=lc) :: cl_date<br/>
-!>   cl_date=date_print(tl_date1)<br/>
-!>   PRINT *, TRIM(cl_date)<br/>
-!>
-!>   to print day if the week:<br/>
-!>   PRINT *,"dow ", tl_date1\%i_dow<br/>
+!> @code
+!>   cl_date=date_print(tl_date1)
+!>   PRINT *, TRIM(cl_date)
+!> @endcode
+!>    
+!>   to print date in another format (only year, month, day):
+!> @code
+!>   cl_date=date_print(tl_date1, cd_fmt)
+!>   PRINT *, TRIM(cl_date)
+!> @endcode
+!>       - cd_fmt ouput format (ex: cd_fmt="('y',i0.4,'m',i0.2,'d',i0.2)" ) 
+!>
+!>   to print day of the week:<br/>
+!> @code
+!>   PRINT *,"dow ", tl_date1\%i_dow
+!> @endcode
 !>   to print last day of the month:<br/>
-!>   PRINT *,"last day ", tl_date1\%i_lday<br/>
+!> @code
+!>   PRINT *,"last day ", tl_date1\%i_lday
+!> @endcode
+!>
 !>   to know if year is a leap year:<br/>
-!>   LOGICAL :: ll_isleap<br/>
-!>   ll_isleap=date_leapyear(tl_date1)<br/>
-!>
-!>   to compute difference between to dates:<br/>
-!>   tl_date2=date_init(2010,12,10)<br/>
-!>   print *,"diff ",tl_date1-tl_date2<br/>
+!> @code
+!>   ll_isleap=date_leapyear(tl_date1)
+!> @endcode
+!>    - ll_isleap is logical
+!>
+!>   to compute number of days between two dates:<br/>
+!> @code
+!>   tl_date2=date_init(2010,12,10)
+!>   dl_diff=tl_date1-tl_date2
+!> @endcode
+!>    - dl_diff is the number of days between date1 and date2 (double precision)
 !>
 !>   to add or substract nday to a date:<br/>
-!>   tl_date2=tl_date1+2.<br/>
-!>   print *,"add ",trim(date_print(tl_date2))<br/>
-!>   tl_date2=tl_date1-2.6<br/>
-!>   print *,"sub ",trim(date_print(tl_date2))<br/>
+!> @code
+!>   tl_date2=tl_date1+2.
+!>   tl_date2=tl_date1-2.6
+!> @endcode
+!>    - number of day (double precision)
 !>
 !>   to print julian day:<br/>
-!>   print *," julian day",tl_date1\%r_jd<br/>
+!> @code
+!>   PRINT *," julian day",tl_date1\%r_jd
+!> @endcode
 !>
 !>   to print CNES julian day (origin 1950-01-01 00:00:00)<br/>
-!>   print *," CNES julian day",tl_date1\%r_jc<br/>
+!> @code
+!>   PRINT *," CNES julian day",tl_date1\%r_jc
+!> @endcode
 !>
 !>   to create pseudo julian day with origin date_now:<br/>
-!>   tl_date1=date_init(2012,12,10,td_dateo=date_now())<br/>
-!>   print *," new julian day",tl_date1\%r_jc<br/>
-!>   Note that you erase CNES julian day when doing so<br/> 
+!> @code
+!>   tl_date1=date_init(2012,12,10,td_dateo=date_now())
+!> @endcode
+!>   @note you erase CNES julian day when doing so<br/> 
 !>
 !>   to print julian day in seconds:<br/>
-!>   print *, tl_date1\%k_jdsec<br/>
+!> @code
+!>   PRINT *, tl_date1\%k_jdsec
+!> @endcode
 !>   to print CNES or new julian day in seconds:<br/>
-!>   print *, tl_date1\%k_jcsec<br/>
-!>
-!> @author
-!> J.Paul
+!> @code
+!>   PRINT *, tl_date1\%k_jcsec
+!> @endcode
+!>
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
 !
 !> @note This module is based on Perderabo's date calculator (ksh)
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+!>
 !> @todo
-!> - check if real(sp), integer(i8) is enough
 !> - see calendar.f90 and select Gregorian, NoLeap, or D360 calendar
-!> - add suffix to number
-!> - add log message
 !----------------------------------------------------------------------
 MODULE date
@@ -78,28 +130,30 @@
    USE kind                            ! F90 kind parameter
    USE fct                             ! basic useful function
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
-   PUBLIC :: TDATE              ! date structure
+   PUBLIC :: TDATE              !< date structure
+
+   PRIVATE :: cm_fmtdate        !< date and time format
+   PRIVATE :: im_secbyday       !< number of second by day
 
    ! function and subroutine
-   PUBLIC :: OPERATOR(-)        ! substract two dates or n days to a date
-   PUBLIC :: OPERATOR(+)        ! add n days to a date
-   PUBLIC :: date_init          ! initiazed date structure form julian day or year month day
-   PUBLIC :: date_now           ! return the date and time
-   PUBLIC :: date_today         ! return the date of the day at 12:00:00
-   PUBLIC :: date_print         ! print the date with format YYYY-MM-DD hh:mm:ss
-   PUBLIC :: date_leapyear      ! check if year is a leap year
-
-   PRIVATE :: date__init_fmtdate ! initiazed date structure from character YYYY-MM-DD hh:mm:ss
-   PRIVATE :: date__init_jd      ! initiazed date structure from julian day
-   PRIVATE :: date__init_nsec    ! initiazed date structure from number of second since origin of julian day
-   PRIVATE :: date__init_ymd     ! initiazed date structure from year month day
+   PUBLIC :: date_today         !< return the date of the day at 12:00:00
+   PUBLIC :: date_now           !< return the date and time
+   PUBLIC :: date_init          !< initialized date structure form julian day or year month day
+   PUBLIC :: date_print         !< print the date with format YYYY-MM-DD hh:mm:ss
+   PUBLIC :: date_leapyear      !< check if year is a leap year
+   PUBLIC :: OPERATOR(-)        !< substract two dates or n days to a date
+   PUBLIC :: OPERATOR(+)        !< add n days to a date
+
+   PRIVATE :: date__init_fmtdate ! initialized date structure from character YYYY-MM-DD hh:mm:ss
+   PRIVATE :: date__init_jd      ! initialized date structure from julian day
+   PRIVATE :: date__init_nsec    ! initialized date structure from number of second since origin of julian day
+   PRIVATE :: date__init_ymd     ! initialized date structure from year month day
    PRIVATE :: date__addnday      ! add nday to a date
    PRIVATE :: date__subnday      ! substract nday to a date
-   PRIVATE :: date__diffdate     ! compute number of day between two dates 
+   PRIVATE :: date__diffdate     ! compute number of days between two dates 
    PRIVATE :: date__lastday      ! compute last day of the month
    PRIVATE :: date__ymd2jd       ! compute julian day from year month day
@@ -115,10 +169,8 @@
    PRIVATE :: date__sec2jd       ! convert seconds since julian day origin in julian day
 
-   !> @struct TDATE
-   TYPE TDATE
+   TYPE TDATE !< date structure
       INTEGER(i4) :: i_year  = 1858   !< year
       INTEGER(i4) :: i_month = 11     !< month
       INTEGER(i4) :: i_day   = 17     !< day
-      INTEGER(i4) :: i_hms   = 0      !< fraction of the day
       INTEGER(i4) :: i_hour  = 0      !< hour
       INTEGER(i4) :: i_min   = 0      !< min
@@ -126,6 +178,6 @@
       INTEGER(i4) :: i_dow   = 0      !< day of week
       INTEGER(i4) :: i_lday  = 0      !< last day of the month
-      REAL(sp)    :: r_jd = 0         !< julian day (origin : 1858/11/17 00:00:00)
-      REAL(sp)    :: r_jc = 0         !< CNES julian day or pseudo julian day with new date origin    
+      REAL(dp)    :: d_jd = 0         !< julian day (origin : 1858/11/17 00:00:00)
+      REAL(dp)    :: d_jc = 0         !< CNES julian day or pseudo julian day with new date origin    
       INTEGER(i8) :: k_jdsec  = 0     !< number of seconds since julian day origin
       INTEGER(i8) :: k_jcsec  = 0     !< number of seconds since CNES or pseudo julian day origin
@@ -133,5 +185,5 @@
 
    !  module variable   
-   CHARACTER(LEN=lc), PARAMETER :: cm_fmtdate = &  !< date format
+   CHARACTER(LEN=lc), PARAMETER :: cm_fmtdate = &  !< date and time format
    &  "(i0.4,'-',i0.2,'-',i0.2,1x,i0.2,':',i0.2,':',i0.2)"
 
@@ -139,8 +191,8 @@
 
    INTERFACE date_init
-      MODULE PROCEDURE date__init_jd    ! initiazed date structure from julian day
-      MODULE PROCEDURE date__init_nsec  ! initiazed date structure from number of second since origin of julian day
-      MODULE PROCEDURE date__init_ymd   ! initiazed date structure from year month day
-      MODULE PROCEDURE date__init_fmtdate   ! initiazed date structure from character YYYY-MM-DD hh:mm:ss
+      MODULE PROCEDURE date__init_jd    ! initialized date structure from julian day
+      MODULE PROCEDURE date__init_nsec  ! initialized date structure from number of second since origin of julian day
+      MODULE PROCEDURE date__init_ymd   ! initialized date structure from year month day
+      MODULE PROCEDURE date__init_fmtdate   ! initialized date structure from character YYYY-MM-DD hh:mm:ss
    END INTERFACE date_init
 
@@ -156,36 +208,43 @@
 CONTAINS
    !-------------------------------------------------------------------
-   !> @brief This function print the date with 
-   !> format YYYY/MM/DD hh:mm:ss
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
+   !> @brief This function print the date and time with 
+   !> format YYYY/MM/DD hh:mm:ss.
+   !> @details
+   !> Optionally, you could specify output format. However it will be only apply
+   !> to year, month, day.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date   date strutcutre
+   !> @param[in] cd_fmt    ouput format (only for year,month,day)
    !> @return date in format YYYY-MM-DD hh:mm:ss
    !-------------------------------------------------------------------
-   ! @code
-   CHARACTER(LEN=lc) FUNCTION date_print(td_date)
-      IMPLICIT NONE
-      ! Argument   
-      TYPE(TDATE), INTENT(IN) :: td_date
-      !----------------------------------------------------------------
-
-      WRITE(date_print,cm_fmtdate) &
-      &    td_date%i_year,td_date%i_month,td_date%i_day, &
-      &    td_date%i_hour,td_date%i_min,td_date%i_sec
+   CHARACTER(LEN=lc) FUNCTION date_print(td_date, cd_fmt)
+      IMPLICIT NONE
+      ! Argument   
+      TYPE(TDATE)     , INTENT(IN) :: td_date
+      CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: cd_fmt
+      !----------------------------------------------------------------
+
+      IF( PRESENT(cd_fmt) )THEN
+         WRITE(date_print,TRIM(cd_fmt)) &
+         &    td_date%i_year,td_date%i_month,td_date%i_day
+      ELSE
+         WRITE(date_print,cm_fmtdate) &
+         &    td_date%i_year,td_date%i_month,td_date%i_day, &
+         &    td_date%i_hour,td_date%i_min,td_date%i_sec
+      ENDIF
 
    END FUNCTION date_print
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This function check if year is a leap year.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date   date strutcutre
    !> @return true if year is leap year
    !-------------------------------------------------------------------
-   ! @code
    LOGICAL FUNCTION date_leapyear(td_date)
       IMPLICIT NONE
@@ -206,14 +265,12 @@
 
    END FUNCTION date_leapyear
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function return the date and time 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @return date and time of the day in a date structure
-   !-------------------------------------------------------------------
-   ! @code
+   !-------------------------------------------------------------------
+   !> @brief This function return the current date and time.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @return current date and time in a date structure
+   !-------------------------------------------------------------------
    TYPE(TDATE) FUNCTION date_now()
       IMPLICIT NONE
@@ -228,14 +285,12 @@
 
    END FUNCTION date_now
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function return the date of the day at 12:00:00 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !-------------------------------------------------------------------
+   !> @brief This function return the date of the day at 12:00:00.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
    !
    !> @return date of the day at 12:00:00 in a date structure
    !-------------------------------------------------------------------
-   ! @code
    TYPE(TDATE) FUNCTION date_today()
       IMPLICIT NONE
@@ -249,25 +304,28 @@
 
    END FUNCTION date_today
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initiazed date structure from a character 
-   !> date with format YYYY-MM-DD hh:mm:ss
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_date : date in format YYYY-MM-DD hh:mm:ss
-   !> @param[in] td_dateo : new date origin for pseudo julian day
+   !-------------------------------------------------------------------
+   !> @brief This function initialized date structure from a character 
+   !> date with format YYYY-MM-DD hh:mm:ss.<br/>
+   !> @details
+   !> Optionaly create pseudo julian day with new origin.<br/>
+   !> julian day origin is 17 Nov 1858 at 00:00:00
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_date   date in format YYYY-MM-DD hh:mm:ss
+   !> @param[in] td_dateo  new date origin for pseudo julian day
    !> @return date structure
    !-------------------------------------------------------------------
-   ! @code
-   TYPE(TDATE) FUNCTION date__init_fmtdate(cd_date, td_dateo)
-      IMPLICIT NONE
-      ! Argument   
-      CHARACTER(LEN=*), INTENT(IN)  :: cd_date
+   TYPE(TDATE) FUNCTION date__init_fmtdate(cd_datetime, td_dateo)
+      IMPLICIT NONE
+      ! Argument   
+      CHARACTER(LEN=*), INTENT(IN)  :: cd_datetime
       TYPE(TDATE),      INTENT(IN), OPTIONAL :: td_dateo
 
       ! local variable
+      CHARACTER(LEN=lc) :: cl_datetime
       CHARACTER(LEN=lc) :: cl_date
+      CHARACTER(LEN=lc) :: cl_time
       CHARACTER(LEN=lc) :: cl_year
       CHARACTER(LEN=lc) :: cl_month
@@ -285,17 +343,20 @@
       !----------------------------------------------------------------
 
-      cl_date=TRIM(ADJUSTL(cd_date))
-
-      cl_year=cl_date(1:4)
+      cl_datetime=TRIM(ADJUSTL(cd_datetime))
+
+      cl_date=fct_split(cl_datetime,1,' ')
+      cl_time=fct_split(cl_datetime,2,' ')
+
+      cl_year = fct_split(cl_date,1,'-')
       READ(cl_year,*) il_year
-      cl_month=cl_date(6:7)
+      cl_month= fct_split(cl_date,2,'-')
       READ(cl_month, *) il_month
-      cl_day=cl_date(9:10)
+      cl_day  = fct_split(cl_date,3,'-')
       READ(cl_day, *) il_day
-      cl_hour=cl_date(12:13)
+      cl_hour = fct_split(cl_time,1,':')
       READ(cl_hour, *) il_hour
-      cl_min=cl_date(15:16)
+      cl_min  = fct_split(cl_time,2,':')
       READ(cl_min, *) il_min
-      cl_sec=cl_date(18:19)
+      cl_sec  = fct_split(cl_time,3,':')
       READ(cl_sec, *) il_sec
 
@@ -304,23 +365,22 @@
 
    END FUNCTION date__init_fmtdate
-   ! @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This function initiazed date structure from julian day<br/>
-   !> optionaly create pseudo julian day with new origin<br/>
+   !-------------------------------------------------------------------
+   !> @brief This function initialized date structure from julian day.<br/>
+   !> @details
+   !> Optionaly create pseudo julian day with new origin.<br/>
    !> julian day origin is 17 Nov 1858 at 00:00:00
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] rd_jd : julian day
-   !> @param[in] td_dateo : new date origin for pseudo julian day
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] dd_jd     julian day
+   !> @param[in] td_dateo  new date origin for pseudo julian day
    !
    !> @return date structure of julian day
    !-------------------------------------------------------------------
-   ! @code
-   TYPE(TDATE) FUNCTION date__init_jd(rd_jd, td_dateo)
+   TYPE(TDATE) FUNCTION date__init_jd(dd_jd, td_dateo)
       IMPLICIT NONE
       !Argument
-      REAL(sp),    INTENT(IN)  :: rd_jd
+      REAL(dp),    INTENT(IN)  :: dd_jd
       TYPE(TDATE), INTENT(IN), OPTIONAL :: td_dateo
       !----------------------------------------------------------------
@@ -329,12 +389,12 @@
 
          ! pseudo julian day with origin dateo
-         date__init_jd%r_jc=rd_jd
-         date__init_jd%k_jcsec=date__jd2sec(rd_jd)
+         date__init_jd%d_jc=dd_jd
+         date__init_jd%k_jcsec=date__jd2sec(dd_jd)
 
          ! convert to truly julian day
          CALL date__jc2jd(date__init_jd, td_dateo)
       ELSE
-         date__init_jd%r_jd=rd_jd
-         date__init_jd%k_jdsec=date__jd2sec(rd_jd)
+         date__init_jd%d_jd=dd_jd
+         date__init_jd%k_jdsec=date__jd2sec(dd_jd)
 
          ! compute CNES julian day
@@ -355,19 +415,18 @@
 
    END FUNCTION date__init_jd
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initiazed date structure from number of 
-   !> second since julian day origin<br/>
-   !> optionaly create pseudo julian day with new origin
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] rd_jd : julian day
-   !> @param[in] td_dateo : new date origin for pseudo julian day
+   !-------------------------------------------------------------------
+   !> @brief This function initialized date structure from number of 
+   !> second since julian day origin.<br/>
+   !> @details
+   !> Optionaly create pseudo julian day with new origin.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] kd_nsec   number of second since julian day origin
+   !> @param[in] td_dateo  new date origin for pseudo julian day
    !
    !> @return date structure of julian day
    !-------------------------------------------------------------------
-   ! @code
    TYPE(TDATE) FUNCTION date__init_nsec(kd_nsec, td_dateo)
       IMPLICIT NONE
@@ -383,13 +442,13 @@
 
    END FUNCTION date__init_nsec
-   ! @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This function initiazed date structure form year month day
-   !> and optionnaly hour min sec<br/>
-   !> optionaly create pseudo julian day with new origin
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialized date structure form year month day
+   !> and optionnaly hour min sec.<br/>
+   !> @details
+   !> Optionaly create pseudo julian day with new origin.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !>
    !> @param[in] id_year
    !> @param[in] id_month
@@ -398,9 +457,8 @@
    !> @param[in] id_min
    !> @param[in] id_sec
-   !> @param[in] td_dateo : new date origin for pseudo julian day
+   !> @param[in] td_dateo  new date origin for pseudo julian day
    !
    !> @return date structure of year month day
    !-------------------------------------------------------------------
-   ! @code
    TYPE(TDATE) FUNCTION date__init_ymd(id_year, id_month, id_day,  &
    &                                   id_hour, id_min, id_sec, &
@@ -450,18 +508,16 @@
 
    END FUNCTION date__init_ymd
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function compute number of day between two dates<br/> 
+   !-------------------------------------------------------------------
+   !> @brief This function compute number of day between two dates: 
    !> nday= date1 - date2
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date1 : first date strutcutre
-   !> @param[in] td_date2 : second date strutcutre
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date1  first date strutcutre
+   !> @param[in] td_date2  second date strutcutre
    !> @return nday
    !-------------------------------------------------------------------
-   ! @code
-   REAL(sp) FUNCTION date__diffdate(td_date1, td_date2)
+   REAL(dp) FUNCTION date__diffdate(td_date1, td_date2)
       IMPLICIT NONE
        
@@ -475,25 +531,23 @@
       CALL date__check(td_date2)   
 
-      date__diffdate = td_date1%r_jd - td_date2%r_jd
+      date__diffdate = td_date1%d_jd - td_date2%d_jd
 
    END FUNCTION date__diffdate
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function substract nday to a date 
+   !-------------------------------------------------------------------
+   !> @brief This function substract nday to a date:
    !> date2 = date1 - nday
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
-   !> @param[in] rd_nday : number of day
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date   date strutcutre
+   !> @param[in] dd_nday   number of day
    !> @return date strutcutre of date - nday
    !-------------------------------------------------------------------
-   ! @code
-   TYPE(TDATE) FUNCTION date__subnday(td_date, rd_nday)
+   TYPE(TDATE) FUNCTION date__subnday(td_date, dd_nday)
       IMPLICIT NONE
       !Argument
       TYPE(TDATE), INTENT(IN) :: td_date
-      REAL(sp),    INTENT(IN) :: rd_nday
+      REAL(dp),    INTENT(IN) :: dd_nday
       !----------------------------------------------------------------
 
@@ -501,25 +555,23 @@
       CALL date__check(td_date)   
 
-      date__subnday=date__init_jd(td_date%r_jd-rd_nday)
+      date__subnday=date__init_jd(td_date%d_jd-dd_nday)
 
    END FUNCTION date__subnday
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function add nday to a date  
+   !-------------------------------------------------------------------
+   !> @brief This function add nday to a date:
    !> date2 = date1 + nday
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
-   !> @param[in] rd_nday : number of day
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date   date strutcutre
+   !> @param[in] dd_nday   number of day
    !> @return date strutcutre of date + nday
    !-------------------------------------------------------------------
-   ! @code
-   TYPE(TDATE) FUNCTION date__addnday(td_date, rd_nday)
+   TYPE(TDATE) FUNCTION date__addnday(td_date, dd_nday)
       IMPLICIT NONE
       !Argument
       TYPE(TDATE), INTENT(IN) :: td_date
-      REAL(sp),    INTENT(IN) :: rd_nday
+      REAL(dp),    INTENT(IN) :: dd_nday
       !----------------------------------------------------------------
 
@@ -527,17 +579,16 @@
       CALL date__check(td_date)   
 
-      date__addnday=date__init_jd(td_date%r_jd+rd_nday)
+      date__addnday=date__init_jd(td_date%d_jd+dd_nday)
 
    END FUNCTION date__addnday
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine compute last day of the month
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_date : date strutcutre
-   !-------------------------------------------------------------------
-   ! @code
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date   date strutcutre
+   !> @return last day of the month
+   !-------------------------------------------------------------------
    INTEGER(i4) FUNCTION date__lastday(td_date)
       IMPLICIT NONE
@@ -562,15 +613,13 @@
 
    END FUNCTION date__lastday
-   ! @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine compute julian day from year month day
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_date : date strutcutre
-   !> @return julian day in the date strutcutre
-   !-------------------------------------------------------------------
-   ! @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute julian day from year month day , and fill
+   !> input date strutcutre.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_date   date strutcutre
+   !-------------------------------------------------------------------
    SUBROUTINE date__ymd2jd(td_date)
       IMPLICIT NONE
@@ -579,34 +628,32 @@
 
       ! local variable
-      REAL(sp) :: rl_standard_jd
-      REAL(sp) :: rl_frac
-      !----------------------------------------------------------------
-
-      rl_standard_jd= td_date%i_day - 32075                               & 
+      REAL(dp) :: dl_standard_jd
+      REAL(dp) :: dl_frac
+      !----------------------------------------------------------------
+
+      dl_standard_jd= td_date%i_day - 32075                               & 
           & + 1461 * (td_date%i_year + 4800 - (14 - td_date%i_month)/12)/4  &
           & + 367 * (td_date%i_month - 2 + (14 - td_date%i_month)/12*12)/12 &
           & - 3 * ((td_date%i_year + 4900 - (14 - td_date%i_month)/12)/100)/4
       
-      td_date%r_jd = rl_standard_jd-2400001 ! origin : 17 nov 1858 h00m00s00
+      td_date%d_jd = dl_standard_jd-2400001 ! origin : 17 nov 1858 h00m00s00
 
       ! compute fraction of day
-      rl_frac=date__hms2jd(td_date)
-
-      td_date%r_jd = td_date%r_jd + rl_frac
-
-      td_date%k_jdsec = date__jd2sec( td_date%r_jd ) 
+      dl_frac=date__hms2jd(td_date)
+
+      td_date%d_jd = td_date%d_jd + dl_frac
+
+      td_date%k_jdsec = date__jd2sec( td_date%d_jd ) 
 
    END SUBROUTINE date__ymd2jd
-   ! @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine compute year month day from julian day
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_date : date strutcutre
-   !> @return year month day in the date strutcutre
-   !-------------------------------------------------------------------
-   ! @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute year month day from julian day, and fill
+   !> input date strutcutre.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_date   date strutcutre
+   !-------------------------------------------------------------------
    SUBROUTINE date__jd2ymd(td_date)
       IMPLICIT NONE
@@ -615,5 +662,4 @@
 
       ! local variable
-      REAL(sp) :: rl_frac
       INTEGER(i4) :: il_standard_jd
       INTEGER(i4) :: il_temp1
@@ -624,6 +670,5 @@
       CALL date__check(td_date)   
 
-      il_standard_jd=INT( td_date%r_jd+2400001, i4 )
-      rl_frac=(td_date%r_jd+2400001)-il_standard_jd
+      il_standard_jd=INT( td_date%d_jd+2400001, i4 )
 
       il_temp1=il_standard_jd + 68569
@@ -645,16 +690,14 @@
 
    END SUBROUTINE date__jd2ymd
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine compute julian day from pseudo julian day 
-   !> with new date origin<br/>
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_date : date
-   !> @return julian day inside input date structure
-   !-------------------------------------------------------------------
-   ! @code
+   !> with new date origin, and fill input date strutcutre.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_date   date
+   !> @param[in]    td_dateo  new date origin for pseudo julian day
+   !-------------------------------------------------------------------
    SUBROUTINE date__jc2jd(td_date, td_dateo)
       IMPLICIT NONE
@@ -665,30 +708,28 @@
       ! local variable
       TYPE(TDATE) :: tl_date
-      REAL(sp)    :: rl_nday
+      REAL(dp)    :: dl_nday
       !----------------------------------------------------------------
       ! origin julian day
       tl_date=date_init(1858,11,17)
 
-      rl_nday=td_dateo-tl_date
+      dl_nday=td_dateo-tl_date
 
       ! compute julian day
-      td_date%r_jd = td_date%r_jc + rl_nday
+      td_date%d_jd = td_date%d_jc + dl_nday
       ! compute number of second since julian day origin
-      td_date%k_jdsec = date__jd2sec(td_date%r_jd)
+      td_date%k_jdsec = date__jd2sec(td_date%d_jd)
 
    END SUBROUTINE date__jc2jd
-   ! @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine compute pseudo julian day with new date origin<br/>
-   !>  default new origin is CNES julian day origin: 1950/01/01
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_date : date
-   !> @param[in] td_dateo : new origin date
-   !> @return pseudo julian day inside input date structure
-   !-------------------------------------------------------------------
-   ! @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute pseudo julian day with new date origin, and
+   !> fill input date structure.<br/>
+   !>  default new origin is CNES julian day origin: 1950-01-01 00:00:00
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_date   date
+   !> @param[in] td_dateo     new origin date
+   !-------------------------------------------------------------------
    SUBROUTINE date__jd2jc(td_date, td_dateo)
       IMPLICIT NONE
@@ -701,5 +742,5 @@
       !----------------------------------------------------------------
       IF( PRESENT(td_dateo) )THEN
-         td_date%r_jc=td_date%r_jd-td_dateo%r_jd
+         td_date%d_jc=td_date%d_jd-td_dateo%d_jd
       ELSE
          ! CNES julian day origin
@@ -710,23 +751,21 @@
          CALL date__ymd2jd(tl_dateo)
 
-         td_date%r_jc = td_date%r_jd-tl_dateo%r_jd
-      ENDIF
-
-      td_date%k_jcsec = date__jd2sec(td_date%r_jc)
+         td_date%d_jc = td_date%d_jd-tl_dateo%d_jd
+      ENDIF
+
+      td_date%k_jcsec = date__jd2sec(td_date%d_jc)
 
    END SUBROUTINE date__jd2jc
-   ! @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine compute the day of week from julian day<br/>
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute the day of week from julian day, and fill
+   !> input date structure.<br/>
    !>  days   : Sunday Monday Tuesday Wednesday Thursday Friday Saturday<br/>
    !>  numday : 0      1      2       3         4        5      6<br/>
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_date : date strutcutre
-   !> @return day of week inside input date structure 
-   !-------------------------------------------------------------------
-   ! @code
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_date   date strutcutre
+   !-------------------------------------------------------------------
    SUBROUTINE date__jd2dow(td_date)
       IMPLICIT NONE
@@ -735,20 +774,18 @@
       !----------------------------------------------------------------
 
-      td_date%i_dow=MOD((INT(AINT(td_date%r_jd))+3),7)
+      td_date%i_dow=MOD((INT(AINT(td_date%d_jd))+3),7)
 
    END SUBROUTINE date__jd2dow
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This function compute fraction of a day from 
-   !> hour, minute, second 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
+   !> hour, minute, second. 
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date   date strutcutre
    !> @return fraction of the day
    !-------------------------------------------------------------------
-   ! @code
-   REAL(sp) FUNCTION date__hms2jd(td_date)
+   REAL(dp) FUNCTION date__hms2jd(td_date)
       IMPLICIT NONE
       ! Argument   
@@ -757,25 +794,22 @@
 
       !  compute real seconds
-      date__hms2jd = REAL( td_date%i_sec, sp )   
+      date__hms2jd = REAL( td_date%i_sec, dp )   
       !  compute real minutes
-      date__hms2jd = REAL( td_date%i_min, sp ) + date__hms2jd/60.0
+      date__hms2jd = REAL( td_date%i_min, dp ) + date__hms2jd/60.0
       !  compute real hours
-      date__hms2jd = REAL( td_date%i_hour, sp ) + date__hms2jd/60.0
+      date__hms2jd = REAL( td_date%i_hour, dp ) + date__hms2jd/60.0
       !  julian fraction of a day
       date__hms2jd = date__hms2jd/24.0
 
    END FUNCTION date__hms2jd
-   ! @endcode 
-   !-------------------------------------------------------------------
-   !> @brief This function compute hour, minute, second from julian 
-   !> fraction
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
-   !> @return date strutcutre
-   !-------------------------------------------------------------------
-   ! @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute hour, minute, second from julian 
+   !> fraction, and fill date structure.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_date   date strutcutre
+   !-------------------------------------------------------------------
    SUBROUTINE date__jd2hms(td_date)
       IMPLICIT NONE
@@ -784,28 +818,26 @@
 
       !local variable
-      REAL(sp) :: rl_fract
-      !----------------------------------------------------------------
-
-      rl_fract=(td_date%r_jd)-AINT(td_date%r_jd)
+      REAL(dp) :: dl_fract
+      !----------------------------------------------------------------
+
+      dl_fract=(td_date%d_jd)-AINT(td_date%d_jd)
       !  compute hour
-      td_date%i_hour = INT( rl_fract * 24.0, i4 )
-      rl_fract = ( rl_fract - REAL( td_date%i_hour, sp ) / 24.0) * 24.0
+      td_date%i_hour = INT( dl_fract * 24.0, i4 )
+      dl_fract = ( dl_fract - REAL( td_date%i_hour, dp ) / 24.0) * 24.0
       !  compute minute
-      td_date%i_min = INT( rl_fract * 60.0, i4 )
-      rl_fract = ( rl_fract - REAL( td_date%i_min, sp ) / 60.0) * 60.0
+      td_date%i_min = INT( dl_fract * 60.0, i4 )
+      dl_fract = ( dl_fract - REAL( td_date%i_min, dp ) / 60.0) * 60.0
       !  compute second
-      td_date%i_sec = NINT( rl_fract * 60.0, i4 )
+      td_date%i_sec = NINT( dl_fract * 60.0, i4 )
 
    END SUBROUTINE date__jd2hms
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine check date express in date structure
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
-   !-------------------------------------------------------------------
-   ! @code
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date   date strutcutre
+   !-------------------------------------------------------------------
    SUBROUTINE date__check(td_date)
       IMPLICIT NONE
@@ -819,60 +851,67 @@
       !----------------------------------------------------------------
 
+      ! init
+      il_status=0
+
       ! check year
       IF( td_date%i_year < 1858_i4 .OR. td_date%i_year > 39999_i4 )THEN
+         il_status=il_status+1
          WRITE(cl_msg,*) "year ",td_date%i_year," out of range"
          CALL logger_error(cl_msg)
-         CALL fct_err(il_status)
       ENDIF
       ! check month
       IF( td_date%i_month < 1_i4 .OR. td_date%i_month > 12_i4 )THEN
+         il_status=il_status+1
          WRITE(cl_msg,*) "month ",td_date%i_month," out of range"
          CALL logger_error(cl_msg)
-         CALL fct_err(il_status)
       ENDIF
       ! check day
       il_lastday=date__lastday(td_date)
       IF( td_date%i_day < 1_i4 .OR. td_date%i_day > il_lastday )THEN
+         il_status=il_status+1
          WRITE(cl_msg,*) "day ",td_date%i_day," out of range"
          CALL logger_error(cl_msg)
-         CALL fct_err(il_status)
       ENDIF
       ! check hour
       IF( td_date%i_hour < 0_i4 .OR. td_date%i_hour > 23_i4 )THEN
+         il_status=il_status+1
          WRITE(cl_msg,*) "hour ",td_date%i_hour," out of range"
          CALL logger_error(cl_msg)
-         CALL fct_err(il_status)
       ENDIF
       ! check minutes
       IF( td_date%i_min < 0_i4 .OR. td_date%i_min > 59_i4 )THEN
+         il_status=il_status+1
          WRITE(cl_msg,*) "minutes ",td_date%i_min," out of range"
          CALL logger_error(cl_msg)
-         CALL fct_err(il_status)
       ENDIF   
       ! check seconds
       IF( td_date%i_sec < 0_i4 .OR. td_date%i_sec > 59_i4 )THEN
+         il_status=il_status+1
          WRITE(cl_msg,*) "seconds ",td_date%i_sec," out of range"
          CALL logger_error(cl_msg)
-         CALL fct_err(il_status)
       ENDIF
 
       ! check julian day
-      IF( td_date%r_jd < 0_sp .OR. td_date%r_jd > 782028_sp )THEN
-         WRITE(cl_msg,*) "julian day ",td_date%r_jd," out of range"
+      IF( td_date%d_jd < 0_sp .OR. td_date%d_jd > 782028_sp )THEN
+         il_status=il_status+1
+         WRITE(cl_msg,*) "julian day ",td_date%d_jd," out of range"
          CALL logger_error(cl_msg)
-         CALL fct_err(il_status)
+      ENDIF
+
+      IF( il_status/= 0 )THEN
+         WRITE(cl_msg,*) " date error"
+         CALL logger_fatal(cl_msg)
       ENDIF
 
    END SUBROUTINE date__check
-   ! @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine adjust date
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_date : date strutcutre
-   !-------------------------------------------------------------------
-   ! @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine adjust date (correct hour, minutes, and seconds
+   !> value if need be)
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_date   date strutcutre
+   !-------------------------------------------------------------------
    SUBROUTINE date__adjust(td_date)
       IMPLICIT NONE
@@ -893,40 +932,36 @@
       IF( td_date%i_hour == 24 )THEN
          td_date%i_hour=0
-         td_date=date__addnday(td_date,1._sp)
+         td_date=date__addnday(td_date,1._dp)
       ENDIF
 
    END SUBROUTINE date__adjust
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This function convert julian day in seconds
-   !> since julian day origin
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
+   !> since julian day origin.
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_date   date strutcutre
    !> @return number of seconds since julian day origin
    !-------------------------------------------------------------------
-   ! @code
-   INTEGER(i8) FUNCTION date__jd2sec(rd_jul)
-      IMPLICIT NONE
-      ! Argument   
-      REAL(sp), INTENT(IN) :: rd_jul
-      !----------------------------------------------------------------
-
-      date__jd2sec = NINT( rd_jul * im_secbyday, i8 )
+   INTEGER(i8) FUNCTION date__jd2sec(dd_jul)
+      IMPLICIT NONE
+      ! Argument   
+      REAL(dp), INTENT(IN) :: dd_jul
+      !----------------------------------------------------------------
+
+      date__jd2sec = NINT( dd_jul * im_secbyday, i8 )
 
    END FUNCTION date__jd2sec
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This function convert seconds since julian day origin in 
-   !> julian day
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_date : date strutcutre
-   !> @return number of seconds since julian day origin
-   !-------------------------------------------------------------------
-   ! @code
-   REAL(sp) FUNCTION date__sec2jd(kd_nsec)
+   !> julian day.
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] kd_nsec   number of second since julian day origin
+   !> @return julian day
+   !-------------------------------------------------------------------
+   REAL(dp) FUNCTION date__sec2jd(kd_nsec)
       IMPLICIT NONE
       ! Argument   
@@ -934,8 +969,7 @@
       !----------------------------------------------------------------
 
-      date__sec2jd = REAL( REAL( kd_nsec , sp ) / im_secbyday, sp )
+      date__sec2jd = REAL( REAL( kd_nsec , dp ) / im_secbyday, dp )
 
    END FUNCTION date__sec2jd
-   ! @endcode   
 END MODULE date
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/dimension.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/dimension.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/dimension.f90	(revision 5075)
@@ -8,18 +8,35 @@
 !> @brief 
 !> This module manage dimension and how to change order of those dimension.
-!
+!>
 !> @details
 !>    define type TDIM:<br/>
-!>    TYPE(TDIM) :: tl_dim<br/>
-!>
-!>    to initialise a dimension structure:<br/>
-!>    - tl_dim=dim_init( cd_name, [id_len,] [ld_uld,] [cd_sname])
+!> @code
+!>    TYPE(TDIM) :: tl_dim
+!> @endcode
+!>
+!>    to initialize a dimension structure:<br/>
+!> @code
+!>    tl_dim=dim_init( cd_name, [id_len,] [ld_uld,] [cd_sname])
+!> @endcode
 !>       - cd_name is the dimension name
-!>       - id_len is the dimension size (optional)
-!>       - ld_uld is true if this dimension is the unlimited one (optional)
-!>       - cd_sname is the dimension short name (optional)
+!>       - id_len is the dimension size [optional]
+!>       - ld_uld is true if this dimension is the unlimited one [optional]
+!>       - cd_sname is the dimension short name ('x','y','z','t') [optional]
+!>
+!>    to clean dimension structure:<br/>
+!> @code
+!>    CALL dim_clean(tl_dim)
+!> @endcode
+!>       - tl_dim : dimension strucutre or array of dimension structure
 !>
 !>    to print information about dimension structure:<br/>
+!> @code
 !>    CALL dim_print(tl_dim)
+!> @endcode
+!>
+!>    to copy dimension structure in another one (using different memory cell):<br/>
+!> @code
+!>    tl_dim2=dim_copy(tl_dim1) 
+!> @endcode
 !>
 !>    to get dimension name:<br/>
@@ -35,8 +52,8 @@
 !>    - tl_dim\%l_uld
 !>
-!>    to get dimension id (use for variable or file dimension):<br/>
+!>    to get dimension id (for variable or file dimension):<br/>
 !>    - tl_dim\%i_id 
 !>
-!>    to know if dimension is used (use for variable or file dimension):<br/>
+!>    to know if dimension is used (for variable or file dimension):<br/>
 !>    - tl_dim\%l_use
 !>
@@ -44,55 +61,97 @@
 !>    variables as well as files use usually 4 dimensions.<br/>
 !>    To easily work with variable we want they will be all 4D and ordered as
-!>    follow: ('x','y','z','t').<br/>
+!>    following: ('x','y','z','t').<br/>
 !>    Functions and subroutines below, allow to reorder dimension of 
 !>    variable.<br/>
 !>    
-!>    Suppose we defined the table of dimension structure below:<br/>
-!>    TYPE(TDIM), DIMENSION(4) :: tl_dim
+!>    Suppose we defined the array of dimension structure below:<br/>
+!> @code
+!>    TYPE(TDIM), DIMENSION(4) :: tl_dim 
 !>    tl_dim(1)=dim_init( 'X', id_len=10)
 !>    tl_dim(2)=dim_init( 'T', id_len=3, ld_uld=.TRUE.)
-!>
-!>    to reorder dimension as we assume variable are defined
-!>    ('x','y','z','t'):<br/>
-!>    CALL dim_reorder(tl(dim(:))
+!> @endcode
+!>
+!>    to reorder dimension (default order: ('x','y','z','t')):<br/>
+!> @code
+!>    CALL dim_reorder(tl_dim(:))
+!> @endcode
 !>
 !>    This subroutine filled dimension structure with unused dimension, 
-!>    then switch from "unordered" dimension to "ordered" dimension
-!>    The dimension structure return will be:
-!>    tl_dim(1) => 'X', i_len=10, l_use=T, l_uld=F
-!>    tl_dim(2) => 'Y', i_len=0,  l_use=F, l_uld=F 
-!>    tl_dim(3) => 'Z', i_len=0,  l_use=F, l_uld=F
-!>    tl_dim(4) => 'T', i_len=3,  l_use=T, l_uld=T
-!>
-!>    After using dim_reorder subroutine you could use functions and subroutine
+!>    then switch from "unordered" dimension to "ordered" dimension.<br/>
+!>    The dimension structure return will be:<br/>
+!>    tl_dim(1) => 'X', i_len=10, l_use=T, l_uld=F<br/>
+!>    tl_dim(2) => 'Y', i_len=1,  l_use=F, l_uld=F<br/> 
+!>    tl_dim(3) => 'Z', i_len=1,  l_use=F, l_uld=F<br/>
+!>    tl_dim(4) => 'T', i_len=3,  l_use=T, l_uld=T<br/>
+!>
+!>    After using subroutine dim_reorder you could use functions and subroutine
 !>    below.<br/>
 !>
-!>    to reshape table of value in "ordered" dimension:<br/>
+!>    to use another dimension order.<br/>
+!> @code
+!>    CALL dim_reorder(tl(dim(:), cl_neworder)
+!> @endcode
+!>    - cl_neworder : character(len=4) (example: 'yxzt')
+!>
+!>    to switch dimension array from ordered dimension to unordered
+!> dimension:<br/>
+!> @code
+!>    CALL dim_unorder(tl_dim(:))
+!> @endcode
+!>
+!>    to fill unused dimension of an array of dimension structure.<br/>
+!> @code
+!>    tl_dimout(:)=dim_fill_unused(tl_dimin(:))
+!> @endcode
+!>    - tl_dimout(:) : 1D array (4elts) of dimension strcuture
+!>    - tl_dimin(:)  : 1D array (<=4elts) of dimension structure
+!>
+!>    to reshape array of value in "ordered" dimension:<br/>
+!> @code
 !>    CALL dim_reshape_2xyzt(tl_dim(:), value(:,:,:,:))
-!>       - value must be a 4D table of real(8) value "unordered"
-!>
-!>    to reshape table of value in "unordered" dimension:<br/>
+!> @endcode
+!>       - value must be a 4D array of real(8) value "unordered"
+!>
+!>    to reshape array of value in "unordered" dimension:<br/>
+!> @code
 !>    CALL dim_reshape_xyzt2(tl_dim(:), value(:,:,:,:))
-!>       - value must be a 4D table of real(8) value "ordered"
-!>
-!>    to reorder a 1D table of 4 elements in "ordered" dimension:<br/>
+!> @endcode
+!>       - value must be a 4D array of real(8) value "ordered"
+!>
+!>    to reorder a 1D array of 4 elements in "ordered" dimension:<br/>
+!> @code
 !>    CALL dim_reorder_2xyzt(tl_dim(:), tab(:))
-!>
-!>       - tab must be a 1D table with 4 elements "unordered".
+!> @endcode
+!>       - tab must be a 1D array with 4 elements "unordered".
 !>       It could be composed of character, integer(4), or logical
 !> 
-!>    to reorder a 1D table of 4 elements in "unordered" dimension:<br/>
+!>    to reorder a 1D array of 4 elements in "unordered" dimension:<br/>
+!> @code
 !>    CALL dim_reorder_2xyzt(tl_dim(:), tab(:))
-!>
-!>       - tab must be a 1D table with 4 elements "ordered".
+!> @endcode
+!>       - tab must be a 1D array with 4 elements "ordered".
 !>       It could be composed of character, integer(4), or logical
 !>
-!> @author
-!> J.Paul
+!>    to get dimension index from a array of dimension structure, 
+!>    given dimension name or short name :<br/>
+!> @code
+!>    index=dim_get_index( tl_dim(:), [cl_name, cl_sname] )
+!> @endcode
+!>       - tl_dim(:) : array of dimension structure
+!>       - cl_name : dimension name [optional]
+!>       - cl_sname: dimension short name [optional]
+!>
+!>    to get dimension id used in an array of dimension structure, 
+!>    given dimension name or short name :<br/>
+!> @code
+!>    id=dim_get_id( tl_dim(:), [cl_name, cl_sname] )
+!> @endcode
+!>       - tl_dim(:) : array of dimension structure
+!>       - cl_name : dimension name [optional]
+!>       - cl_sname: dimension short name [optional]
+!>
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
-!> @todo
-!> - add description generique de l'objet dim
+!> @date November, 2013 - Initial Version
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -104,11 +163,8 @@
    USE fct                             ! basic useful function
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
    PUBLIC :: TDIM              !< dimension structure
-   PUBLIC :: ip_maxdim         !< number of dimension to be used
-   PUBLIC :: cp_dimorder       !< dimension order
 
    ! function and subroutine
@@ -116,94 +172,164 @@
    PUBLIC :: dim_clean         !< clean dimension structuree
    PUBLIC :: dim_print         !< print dimension information
-   PUBLIC :: dim_get_id        !< get dimension id in table of dimension structure
-   PUBLIC :: dim_get_void_id   !< get unused dimension id in table of dimension structure
-   PUBLIC :: dim_order         !< check if dimension are ordered or not
+   PUBLIC :: dim_copy          !< copy dimension structure
    PUBLIC :: dim_reorder       !< filled dimension structure to switch from unordered to ordered dimension
-   PUBLIC :: dim_unorder       !< switch dimension table from ordered to unordered dimension
-   PUBLIC :: dim_reshape_2xyzt !< reshape table dimension to ('x','y','z','t')
-   PUBLIC :: dim_reshape_xyzt2 !< reshape table dimension from ('x','y','z','t')
-   PUBLIC :: dim_reorder_2xyzt !< reorder 1D table to ('x','y','z','t')
-   PUBLIC :: dim_reorder_xyzt2 !< reorder 1D table from ('x','y','z','t')
-
-   PRIVATE :: dim__fill_unused      !< filled dimension structure with unused dimension 
-   PRIVATE :: dim__reshape_2xyzt_dp !< reshape real(8) 4D table to ('x','y','z','t')
-   PRIVATE :: dim__reshape_xyzt2_dp !< reshape real(8) 4D table from ('x','y','z','t')
-   PRIVATE :: dim__reorder_2xyzt_i4 !< reorder integer(4) 1D table to ('x','y','z','t')
-   PRIVATE :: dim__reorder_xyzt2_i4 !< reorder integer(4) 1D table from ('x','y','z','t')
-   PRIVATE :: dim__reorder_2xyzt_l  !< reorder logical 1D table to ('x','y','z','t')
-   PRIVATE :: dim__reorder_xyzt2_l  !< reorder logical 1D table from ('x','y','z','t')
-   PRIVATE :: dim__reorder_2xyzt_c  !< reorder string 1D table to ('x','y','z','t')
-   PRIVATE :: dim__reorder_xyzt2_c  !< reorder string 1D table from ('x','y','z','t')
-   PRIVATE :: dim__clean_unit       !< clean one dimension structure
-   PRIVATE :: dim__clean_tab        !< clean a table of dimension structure
-   PRIVATE :: dim__print_unit       !< print information on one dimension structure
-   PRIVATE :: dim__print_tab        !< print information on a table of dimension structure
-
-   !> @struct TDIM
-   TYPE TDIM
-      CHARACTER(LEN=lc) :: c_name = ''!< dimension name
+   PUBLIC :: dim_unorder       !< switch dimension array from ordered to unordered dimension
+   PUBLIC :: dim_fill_unused   !< filled dimension structure with unused dimension 
+   PUBLIC :: dim_reshape_2xyzt !< reshape array dimension to ('x','y','z','t')
+   PUBLIC :: dim_reshape_xyzt2 !< reshape array dimension from ('x','y','z','t')
+   PUBLIC :: dim_reorder_2xyzt !< reorder 1D array to ('x','y','z','t')
+   PUBLIC :: dim_reorder_xyzt2 !< reorder 1D array from ('x','y','z','t')
+   PUBLIC :: dim_get_index     !< get dimension index in array of dimension structure
+   PUBLIC :: dim_get_id        !< get dimension id in array of dimension structure
+
+   PRIVATE :: dim__reshape_2xyzt_dp ! reshape real(8) 4D array to ('x','y','z','t')
+   PRIVATE :: dim__reshape_xyzt2_dp ! reshape real(8) 4D array from ('x','y','z','t')
+   PRIVATE :: dim__reorder_2xyzt_i4 ! reorder integer(4) 1D array to ('x','y','z','t')
+   PRIVATE :: dim__reorder_xyzt2_i4 ! reorder integer(4) 1D array from ('x','y','z','t')
+   PRIVATE :: dim__reorder_2xyzt_l  ! reorder logical 1D array to ('x','y','z','t')
+   PRIVATE :: dim__reorder_xyzt2_l  ! reorder logical 1D array from ('x','y','z','t')
+   PRIVATE :: dim__reorder_2xyzt_c  ! reorder string 1D array to ('x','y','z','t')
+   PRIVATE :: dim__reorder_xyzt2_c  ! reorder string 1D array from ('x','y','z','t')
+   PRIVATE :: dim__clean_unit       ! clean one dimension structure
+   PRIVATE :: dim__clean_arr        ! clean a array of dimension structure
+   PRIVATE :: dim__print_unit       ! print information on one dimension structure
+   PRIVATE :: dim__print_arr        ! print information on a array of dimension structure
+   PRIVATE :: dim__copy_unit        ! copy dimension structure
+   PRIVATE :: dim__copy_arr         ! copy array of dimension structure
+
+   TYPE TDIM !< dimension structure
+      CHARACTER(LEN=lc) :: c_name = ''       !< dimension name
       CHARACTER(LEN=lc) :: c_sname = 'u'     !< dimension short name
-      INTEGER(i4)       :: i_id = 0          !< dimension id
+      INTEGER(i4)       :: i_id  = 0         !< dimension id
       INTEGER(i4)       :: i_len = 1         !< dimension length
       LOGICAL           :: l_uld = .FALSE.   !< dimension unlimited or not
       LOGICAL           :: l_use = .FALSE.   !< dimension used or not
-      INTEGER(i4)       :: i_2xyzt = 0       !< indices to reshape table to ('x','y','z','t')
-      INTEGER(i4)       :: i_xyzt2 = 0       !< indices to reshape table from ('x','y','z','t')
+      INTEGER(i4)       :: i_2xyzt = 0       !< indices to reshape array to ('x','y','z','t')
+      INTEGER(i4)       :: i_xyzt2 = 0       !< indices to reshape array from ('x','y','z','t')
    END TYPE
-
-   INTEGER(i4), PARAMETER :: ip_maxdim = 4  !< number of dimension to be used
-
-   !  module variable
-   CHARACTER(LEN=lc), PARAMETER :: cp_dimorder = 'xyzt' !< dimension order to output
 
    INTERFACE dim_print
       MODULE PROCEDURE dim__print_unit ! print information on one dimension
-      MODULE PROCEDURE dim__print_tab  ! print information on a table of dimension
+      MODULE PROCEDURE dim__print_arr  ! print information on a array of dimension
    END INTERFACE dim_print
 
    INTERFACE dim_clean
       MODULE PROCEDURE dim__clean_unit ! clean one dimension
-      MODULE PROCEDURE dim__clean_tab  ! clean a table of dimension
+      MODULE PROCEDURE dim__clean_arr  ! clean a array of dimension
    END INTERFACE dim_clean
 
+   INTERFACE dim_copy
+      MODULE PROCEDURE dim__copy_unit  ! copy dimension structure
+      MODULE PROCEDURE dim__copy_arr   ! copy array of dimension structure
+   END INTERFACE
+
    INTERFACE dim_reshape_2xyzt
-      MODULE PROCEDURE dim__reshape_2xyzt_dp   ! reshape real(8) 4D table to ('x','y','z','t')
+      MODULE PROCEDURE dim__reshape_2xyzt_dp   ! reshape real(8) 4D array to ('x','y','z','t')
    END INTERFACE dim_reshape_2xyzt
 
    INTERFACE dim_reshape_xyzt2
-      MODULE PROCEDURE dim__reshape_xyzt2_dp   ! reshape real(8) 4D table from ('x','y','z','t')
+      MODULE PROCEDURE dim__reshape_xyzt2_dp   ! reshape real(8) 4D array from ('x','y','z','t')
    END INTERFACE dim_reshape_xyzt2
 
    INTERFACE dim_reorder_2xyzt
-      MODULE PROCEDURE dim__reorder_2xyzt_i4   ! reorder integer(4) 1D table to ('x','y','z','t')
-      MODULE PROCEDURE dim__reorder_2xyzt_c    ! reorder string 1D table to ('x','y','z','t')
-      MODULE PROCEDURE dim__reorder_2xyzt_l    ! reorder logical 1D table to ('x','y','z','t')
+      MODULE PROCEDURE dim__reorder_2xyzt_i4   ! reorder integer(4) 1D array to ('x','y','z','t')
+      MODULE PROCEDURE dim__reorder_2xyzt_c    ! reorder string 1D array to ('x','y','z','t')
+      MODULE PROCEDURE dim__reorder_2xyzt_l    ! reorder logical 1D array to ('x','y','z','t')
    END INTERFACE dim_reorder_2xyzt
 
    INTERFACE dim_reorder_xyzt2
-      MODULE PROCEDURE dim__reorder_xyzt2_i4   ! reorder integer(4) 1D table from ('x','y','z','t')
-      MODULE PROCEDURE dim__reorder_xyzt2_c    ! reorder string 1D table from ('x','y','z','t')
-      MODULE PROCEDURE dim__reorder_xyzt2_l    ! reorder logical 1D table from ('x','y','z','t')  
+      MODULE PROCEDURE dim__reorder_xyzt2_i4   ! reorder integer(4) 1D array from ('x','y','z','t')
+      MODULE PROCEDURE dim__reorder_xyzt2_c    ! reorder string 1D array from ('x','y','z','t')
+      MODULE PROCEDURE dim__reorder_xyzt2_l    ! reorder logical 1D array from ('x','y','z','t')  
    END INTERFACE dim_reorder_xyzt2
 
 CONTAINS
    !-------------------------------------------------------------------
-   !> @brief This function returns dimension id, in a table of dimension structure,
-   !> given dimension name, or short name.
-   !> only dimension used are checked.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim   : dimension structure
-   !> @param[in] cd_name  : dimension name or short name
-   !> @param[in] cd_sname : dimension short name
-   !> @return dimension id
-   !-------------------------------------------------------------------
-   !> @code
-   INTEGER(i4) FUNCTION dim_get_id( td_dim, cd_name, cd_sname )
+   !> @brief
+   !> This subroutine copy a array of dimension structure in another one
+   !> @details 
+   !> see dim__copy_unit
+   !>
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_dim=dim_copy(dim_init()) is forbidden).
+   !> This will create memory leaks.
+   !> @warning to avoid infinite loop, do not use any function inside 
+   !> this subroutine
+   !>
+   !> @author J.Paul
+   !> @date November, 2014 - Initial Version
+   !
+   !> @param[in] td_dim   array of dimension structure
+   !> @return copy of input array of dimension structure
+   !-------------------------------------------------------------------
+   FUNCTION dim__copy_arr( td_dim )
       IMPLICIT NONE
       ! Argument
-      TYPE(TDIM),       DIMENSION(:), INTENT(IN) :: td_dim
+      TYPE(TDIM), DIMENSION(:), INTENT(IN) :: td_dim
+      ! function
+      TYPE(TDIM), DIMENSION(SIZE(td_dim(:))) :: dim__copy_arr
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      DO ji=1,SIZE(td_dim(:))
+         dim__copy_arr(ji)=dim_copy(td_dim(ji))
+      ENDDO
+
+   END FUNCTION dim__copy_arr
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine copy an dimension structure in another one
+   !> @details 
+   !> dummy function to get the same use for all structure
+   !>
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_dim=dim_copy(dim_init()) is forbidden).
+   !> This will create memory leaks.
+   !> @warning to avoid infinite loop, do not use any function inside 
+   !> this subroutine
+   !>
+   !> @author J.Paul
+   !> @date November, 2014 - Initial Version
+   !>
+   !> @param[in] td_dim   dimension structure
+   !> @return copy of input dimension structure
+   !-------------------------------------------------------------------
+   FUNCTION dim__copy_unit( td_dim )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TDIM), INTENT(IN)  :: td_dim
+      ! function
+      TYPE(TDIM) :: dim__copy_unit
+
+      ! local variable
+      !----------------------------------------------------------------
+
+      dim__copy_unit=td_dim
+
+   END FUNCTION dim__copy_unit
+   !-------------------------------------------------------------------
+   !> @brief This function returns dimension index,
+   !> given dimension name or short name.
+   !>
+   !> @details
+   !> the function check dimension name, in the array of dimension structure.
+   !> dimension could be used or not.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !> @date September, 2014 - do not check if dimension used
+   !>
+   !> @param[in] td_dim    array of dimension structure
+   !> @param[in] cd_name   dimension name
+   !> @param[in] cd_sname  dimension short name
+   !> @return dimension index
+   !-------------------------------------------------------------------
+   INTEGER(i4) FUNCTION dim_get_index( td_dim, cd_name, cd_sname )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TDIM)      , DIMENSION(:), INTENT(IN) :: td_dim
       CHARACTER(LEN=*),               INTENT(IN) :: cd_name
       CHARACTER(LEN=*),               INTENT(IN), OPTIONAL :: cd_sname
@@ -222,5 +348,5 @@
       !----------------------------------------------------------------
       ! init
-      dim_get_id=0
+      dim_get_index=0
 
       il_ndim=SIZE(td_dim(:))
@@ -228,82 +354,71 @@
       ! look for dimension name
       cl_name=fct_lower(cd_name)
-      ! check if dimension is in table of dimension structure and used
+      ! check if dimension is in array of dimension structure
       jj=0
       DO ji=1,il_ndim
-         !IF( td_dim(ji)%l_use ) jj=jj+1
-
          cl_dim_name=fct_lower(td_dim(ji)%c_name)
-         IF( TRIM(cl_dim_name) == TRIM(cl_name) .AND. &
-         &   td_dim(ji)%l_use )THEN
-            dim_get_id=ji !jj
-            CALL logger_debug("GET ID: variable name "//&
-            &  TRIM(ADJUSTL(cd_name))//" already in file " )
-            EXIT
+         IF( TRIM(cl_dim_name) == TRIM(cl_name) )THEN
+             dim_get_index=ji
+             EXIT
          ENDIF
       ENDDO
 
       ! look for dimension short name
-      IF(  dim_get_id == 0 )THEN
+      IF(  dim_get_index == 0 )THEN
 
          cl_sname=fct_lower(cd_name)
-         ! check if dimension is in table of dimension structure and used
+         ! check if dimension is in array of dimension structure
          jj=0
          DO ji=1,il_ndim
-            IF( td_dim(ji)%l_use ) jj=jj+1
-            
             cl_dim_sname=fct_lower(td_dim(ji)%c_sname)
-            IF( (TRIM(cl_dim_sname) == TRIM(cl_sname) ).AND.&
-            &   td_dim(ji)%l_use )THEN
-               CALL logger_debug("GET ID: variable short name "//&
+            IF( (TRIM(cl_dim_sname) == TRIM(cl_sname) ) )THEN
+               CALL logger_debug("DIM GET INDEX: variable short name "//&
                &  TRIM(ADJUSTL(cd_name))//" already in file")
-               dim_get_id=jj
+               dim_get_index=ji
                EXIT
             ENDIF
          ENDDO
+
       ENDIF
 
       ! look for dimension short name
       IF( PRESENT(cd_sname) )THEN
-         IF(  dim_get_id == 0 )THEN
+         IF(  dim_get_index == 0 )THEN
 
             cl_sname=fct_lower(cd_sname)
-            ! check if dimension is in table of dimension structure and used
+            ! check if dimension is in array of dimension structure
             jj=0
             DO ji=1,il_ndim
-               IF( td_dim(ji)%l_use ) jj=jj+1
-               
                cl_dim_sname=fct_lower(td_dim(ji)%c_sname)
-               IF( (TRIM(cl_dim_sname) == TRIM(cl_sname) ).AND.&
-               &   td_dim(ji)%l_use )THEN
-                  CALL logger_debug("GET ID: variable short name "//&
+               IF( (TRIM(cl_dim_sname) == TRIM(cl_sname) ) )THEN
+                  CALL logger_debug("DIM GET INDEX: variable short name "//&
                   &  TRIM(ADJUSTL(cd_sname))//" already in file")
-                  dim_get_id=jj
+                  dim_get_index=ji
                   EXIT
                ENDIF
             ENDDO
+
          ENDIF
       ENDIF
 
-   END FUNCTION dim_get_id
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function returns dimension id, in a table of dimension structure,
-   !> given dimension name, or short name.
-   !> only dimension used are checked.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim   : dimension structure
-   !> @param[in] cd_name  : dimension name or short name
-   !> @param[in] cd_sname : dimension short name
+   END FUNCTION dim_get_index
+   !-------------------------------------------------------------------
+   !> @brief This function returns dimension id, in a array of dimension structure,
+   !> given dimension name, or short name. 
+   !> @note only dimension used are checked.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim    dimension structure
+   !> @param[in] cd_name   dimension name or short name
+   !> @param[in] cd_sname  dimension short name
    !> @return dimension id
    !-------------------------------------------------------------------
-   !> @code
-   INTEGER(i4) FUNCTION dim_get_void_id( td_dim, cd_name, cd_sname )
+   INTEGER(i4) FUNCTION dim_get_id( td_dim, cd_name, cd_sname )
       IMPLICIT NONE
       ! Argument
       TYPE(TDIM),       DIMENSION(:), INTENT(IN) :: td_dim
-      CHARACTER(LEN=*),               INTENT(IN), OPTIONAL :: cd_name
+      CHARACTER(LEN=*),               INTENT(IN) :: cd_name
       CHARACTER(LEN=*),               INTENT(IN), OPTIONAL :: cd_sname
 
@@ -318,7 +433,8 @@
       ! loop indices
       INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
       !----------------------------------------------------------------
       ! init
-      dim_get_void_id=0
+      dim_get_id=0
 
       il_ndim=SIZE(td_dim(:))
@@ -326,72 +442,75 @@
       ! look for dimension name
       cl_name=fct_lower(cd_name)
-      ! check if dimension is in table of dimension structure and used
+      ! check if dimension is in array of dimension structure and used
+      jj=0
       DO ji=1,il_ndim
-
          cl_dim_name=fct_lower(td_dim(ji)%c_name)
          IF( TRIM(cl_dim_name) == TRIM(cl_name) .AND. &
-         &   .NOT. td_dim(ji)%l_use )THEN
-            dim_get_void_id=ji
-            EXIT
+         &   td_dim(ji)%l_use )THEN
+            IF( td_dim(ji)%i_id /= 0 )THEN
+               dim_get_id=td_dim(ji)%i_id
+               EXIT
+            ENDIF
          ENDIF
       ENDDO
 
       ! look for dimension short name
-      IF(  dim_get_void_id == 0 )THEN
+      IF(  dim_get_id == 0 )THEN
 
          cl_sname=fct_lower(cd_name)
-         ! check if dimension is in table of dimension structure and used
+         ! check if dimension is in array of dimension structure and used
+         jj=0
          DO ji=1,il_ndim
-            
             cl_dim_sname=fct_lower(td_dim(ji)%c_sname)
             IF( (TRIM(cl_dim_sname) == TRIM(cl_sname) ).AND.&
-            &   .NOT. td_dim(ji)%l_use )THEN
-               dim_get_void_id=ji
-               EXIT
+            &   td_dim(ji)%l_use )THEN
+               IF( td_dim(ji)%i_id /= 0 )THEN
+                  dim_get_id=td_dim(ji)%i_id
+                  EXIT
+               ENDIF
             ENDIF
          ENDDO
+
       ENDIF
 
       ! look for dimension short name
       IF( PRESENT(cd_sname) )THEN
-         IF(  dim_get_void_id == 0 )THEN
+         IF(  dim_get_id == 0 )THEN
 
             cl_sname=fct_lower(cd_sname)
-            ! check if dimension is in table of dimension structure and used
+            ! check if dimension is in array of dimension structure and used
+            jj=0
             DO ji=1,il_ndim
-               
                cl_dim_sname=fct_lower(td_dim(ji)%c_sname)
                IF( (TRIM(cl_dim_sname) == TRIM(cl_sname) ).AND.&
-               &   .NOT. td_dim(ji)%l_use )THEN
-                  dim_get_void_id=ji
-                  EXIT
+               &   td_dim(ji)%l_use )THEN
+                  IF( td_dim(ji)%i_id /= 0 )THEN
+                     dim_get_id=td_dim(ji)%i_id
+                     EXIT
+                  ENDIF
                ENDIF
             ENDDO
+
          ENDIF
       ENDIF
 
-      IF( dim_get_void_id == 0 )THEN
-         DO ji=1,il_ndim
-            IF( .NOT. td_dim(ji)%l_use ) dim_get_void_id=ji
-         ENDDO
-      ENDIF
-
-   END FUNCTION dim_get_void_id
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This routine initialise a dimension structure with given 
-   !> arguments (name, length, etc).<br/> 
+   END FUNCTION dim_get_id
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a dimension structure with given
+   !> name.<br/>
+   !> @details
+   !> Optionally length could be inform, as well as short name and if dimension
+   !> is unlimited or not.<br/>
    !> define dimension is supposed to be used.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : dimension name
-   !> @param[in] id_len : dimension length
-   !> @param[in] ld_uld : dimension unlimited
-   !> @param[in] cd_sname : dimension short name
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] cd_name   dimension name
+   !> @param[in] id_len    dimension length
+   !> @param[in] ld_uld    dimension unlimited
+   !> @param[in] cd_sname  dimension short name
    !> @return dimension structure
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TDIM) FUNCTION dim_init( cd_name, id_len, ld_uld, cd_sname)
       IMPLICIT NONE
@@ -413,10 +532,10 @@
       cl_name=fct_upper(cd_name)
 
-      CALL logger_info( &
+      CALL logger_debug( &
       &  " DIM INIT: dimension name: "//TRIM(cl_name) )
       dim_init%c_name=TRIM(ADJUSTL(cd_name))
 
       IF( PRESENT(id_len) )THEN
-         CALL logger_info( &
+         CALL logger_debug( &
          &  " DIM INIT: dimension length: "//fct_str(id_len) )
          dim_init%i_len=id_len
@@ -434,5 +553,5 @@
          &   TRIM(cl_sname) == 'z' .OR. & 
          &   TRIM(cl_sname) == 't' )THEN
-            CALL logger_info( &
+            CALL logger_debug( &
             &  " DIM INIT: dimension short name: "//TRIM(cd_sname) )
             dim_init%c_sname=TRIM(cd_sname)
@@ -452,8 +571,8 @@
             dim_init%c_sname='y'
          ELSEIF( TRIM(cl_name)== 'z' .OR. &
-         &   INDEX(cl_name,'depth')/=0 )THEN
+         &       INDEX(cl_name,'depth')/=0 )THEN
             dim_init%c_sname='z'
          ELSEIF( TRIM(cl_name)== 't' .OR. &
-         &   INDEX(cl_name,'time')/=0 )THEN
+         &       INDEX(cl_name,'time')/=0 )THEN
             dim_init%c_sname='t'
          ENDIF      
@@ -462,5 +581,5 @@
 
       IF( PRESENT(ld_uld) )THEN
-         CALL logger_info( &
+         CALL logger_debug( &
          &  " DIM INIT: unlimited dimension: "//fct_str(ld_uld) )
          dim_init%l_uld=ld_uld
@@ -471,16 +590,17 @@
       ENDIF
       
+      ! get dimension orderer index
+      dim_init%i_2xyzt=SCAN(TRIM(cp_dimorder),TRIM(dim_init%c_sname))
+
    END FUNCTION dim_init
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subrtoutine print dimension information 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE dim__print_tab(td_dim)
+   !-------------------------------------------------------------------
+   !> @brief This subroutine print informations of an array of dimension. 
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim array of dimension structure
+   !-------------------------------------------------------------------
+   SUBROUTINE dim__print_arr(td_dim)
       IMPLICIT NONE
 
@@ -496,15 +616,13 @@
       ENDDO
 
-   END SUBROUTINE dim__print_tab
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subrtoutine print dimension information 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : dimension structure
-   !-------------------------------------------------------------------
-   !> @code
+   END SUBROUTINE dim__print_arr
+   !-------------------------------------------------------------------
+   !> @brief This subrtoutine print dimension information. 
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE dim__print_unit(td_dim)
       IMPLICIT NONE
@@ -512,5 +630,4 @@
       ! Argument      
       TYPE(TDIM), INTENT(IN) :: td_dim
-
       !----------------------------------------------------------------
 
@@ -526,100 +643,124 @@
 
    END SUBROUTINE dim__print_unit
-   !> @endcode
+   !-------------------------------------------------------------------
+   !> @brief This function fill unused dimension of an array of dimension
+   !> and return a 4 elts array of dimension structure. 
+   !> @details
+   !> output dimensions 'x','y','z' and 't' are all informed.
+   !>
+   !> @note without input array of dimension, return 
+   !> a 4 elts array of dimension structure all unused
+   !> (case variable 0d)
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !>
+   !> @param[in] td_dim array of dimension structure
+   !> @return  4elts array of dimension structure
+   !-------------------------------------------------------------------
+   FUNCTION dim_fill_unused(td_dim)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TDIM), DIMENSION(:), INTENT(IN), OPTIONAL :: td_dim
+
+      ! function
+      TYPE(TDIM), DIMENSION(ip_maxdim) :: dim_fill_unused
+
+      ! local variable
+      CHARACTER(LEN=lc)                       :: cl_dimin
+      INTEGER(i4)      , DIMENSION(1)         :: il_ind  ! index
+      
+      TYPE(TDIM),        DIMENSION(ip_maxdim) :: tl_dim
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      IF( PRESENT(td_dim) )THEN
+         tl_dim(1:SIZE(td_dim(:)))=td_dim(:)
+      ENDIF
+      ! concatenate short nem dimension in a character string
+      cl_dimin=fct_lower(fct_concat(tl_dim(:)%c_sname))
+      DO ji = 1, ip_maxdim
+
+         ! search missing dimension
+         IF( INDEX(cl_dimin,TRIM(fct_lower(cp_dimorder(ji:ji)))) == 0 )THEN
+            ! search first empty dimension
+            il_ind(:)=MINLOC( tl_dim(:)%i_2xyzt, tl_dim(:)%i_2xyzt == 0 )
+
+            ! put missing dimension instead of empty one
+            tl_dim(il_ind(1))%c_sname=fct_lower(cp_dimorder(ji:ji))
+            ! update output structure
+            tl_dim(il_ind(1))%c_name=fct_lower(cp_dimorder(ji:ji))
+            tl_dim(il_ind(1))%i_2xyzt=ji
+            tl_dim(il_ind(1))%i_len=1
+            tl_dim(il_ind(1))%l_use=.FALSE.
+         ENDIF
+
+      ENDDO
+         
+      ! save result
+      dim_fill_unused(:)=tl_dim(:)
+
+      ! clean
+      CALL dim_clean(tl_dim(:))
+
+   END FUNCTION dim_fill_unused
    !-------------------------------------------------------------------
    !> @brief 
-   !> This subroutine check if dimension are ordered or not 
-   !
-   !> @author J.Paul
-   !> - 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @return dimension are ordered or not 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION dim_order(td_dim)
+   !> This subroutine switch element of an array (4 elts) of dimension 
+   !> structure 
+   !> from unordered dimension to ordered dimension <br/>
+   !>
+   !> @details
+   !> Optionally you could specify dimension order to output
+   !> (default 'xyzt')
+   !> Example: (/'z','x','t','y'/) => (/'x','y','z','t'/)
+   !>
+   !> @warning this subroutine change dimension order 
+   !
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !> @date September, 2014 - allow to choose ordered dimension to be output
+   !>
+   !> @param[inout] td_dim    array of dimension structure
+   !> @param[in] cd_dimorder  dimension order to be output 
+   !-------------------------------------------------------------------
+   SUBROUTINE dim_reorder(td_dim, cd_dimorder)
       IMPLICIT NONE
       ! Argument      
-      TYPE(TDIM), DIMENSION(:), INTENT(IN) :: td_dim
-
-      ! function
-      LOGICAL :: dim_order
+      TYPE(TDIM)              , DIMENSION(:), INTENT(INOUT) :: td_dim
+      CHARACTER(LEN=ip_maxdim)              , INTENT(IN   ), OPTIONAL :: cd_dimorder
 
       ! local variable
-      CHARACTER(LEN=lc) :: cl_dimin
-
-      ! loop indices
-      !----------------------------------------------------------------
-      ! init
-      dim_order=.FALSE.
+      INTEGER(i4)                             :: il_ind
+
+      CHARACTER(LEN=lc)                       :: cl_dimin
+      CHARACTER(LEN=lc)                       :: cl_dimorder
+
+      TYPE(TDIM)       , DIMENSION(ip_maxdim) :: tl_dim
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
 
       IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension.")
+         CALL logger_error("DIM REORDER: invalid dimension of array dimension.")
       ELSE
 
-         cl_dimin=fct_concat(td_dim(:)%c_sname)
-
-         IF( TRIM(cp_dimorder) == TRIM(cl_dimin) )THEN
-            dim_order=.TRUE.
-         ENDIF
-
-      ENDIF
-   END FUNCTION dim_order
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief 
-   !> This subroutine switch element of a table (4 elts) of dimension 
-   !> structure 
-   !> from unordered dimension to ordered dimension ('x','y','z','t')
-   !> Example: (/'z','x','t','y'/) => (/'x','y','z','t'/)
-   !> @warning this subroutine change dimension order 
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_dim : table of dimension structure
-   !> @return dimension structure completed and reordered 
-   !>
-   !> @todo
-   !> -check input dimension order and stop if already ordered
-   !> - 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE dim_reorder(td_dim)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TDIM), DIMENSION(:), INTENT(INOUT) :: td_dim
-
-      ! local variable
-      INTEGER(i4)                             :: il_id
-      CHARACTER(LEN=lc)                       :: cl_dimin
-      TYPE(TDIM)       , DIMENSION(ip_maxdim) :: tl_dim
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jj
-      !----------------------------------------------------------------
-
-      IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension.")
-      ELSE
-
-         ! copy and rename dimension in local variable
-         tl_dim(:)=td_dim(:)
-         jj=0
+         cl_dimorder=TRIM(cp_dimorder)
+         IF( PRESENT(cd_dimorder) ) cl_dimorder=TRIM(ADJUSTL(cd_dimorder))
+
+         ! add id if dimension used and no id
          DO ji=1, ip_maxdim
 
-         CALL logger_debug( "DIM REORDER : jj "//TRIM(fct_str(jj))//&
-         &  " "//TRIM(fct_str(td_dim(ji)%l_use)))
             IF( td_dim(ji)%l_use )THEN
-               jj=jj+1
-            !IF( td_dim(ji)%l_use .AND. td_dim(ji)%i_id == 0 )THEN
-               ! add id if dimension used and no id
-               CALL logger_debug( "DIM REORDER : add id "//TRIM(fct_str(jj))//&
-               &  " to dimension "//TRIM(td_dim(ji)%c_name) )
-               tl_dim(ji)%i_id=jj
+               IF( td_dim(ji)%i_id == 0 )THEN
+                  td_dim(ji)%i_id=MAXVAL(td_dim(:)%i_id)+1
+               ENDIF
             ELSE
                td_dim(ji)%i_id=0
                td_dim(ji)%i_xyzt2=0
+               td_dim(ji)%i_2xyzt=0
                td_dim(ji)%c_sname='u'
                td_dim(ji)%c_name=''
@@ -629,20 +770,14 @@
          ENDDO
 
-         print *,">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
-         CALL dim_print(tl_dim(:))
-
-
          ! fill unused dimension
-         CALL dim__fill_unused(tl_dim(:))
+         tl_dim(:)=dim_fill_unused(td_dim(:))
          cl_dimin=fct_lower(fct_concat(tl_dim(:)%c_sname))
 
-         print *,">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
-         CALL dim_print(tl_dim(:))
          ! compute input id from output id (xyzt) 
          DO ji = 1, ip_maxdim
              
-            il_id=SCAN(TRIM(cp_dimorder),TRIM(cl_dimin(ji:ji)))
-            IF( il_id /= 0 )THEN
-               tl_dim(ji)%i_xyzt2=il_id
+            il_ind=SCAN(TRIM(cl_dimorder),TRIM(cl_dimin(ji:ji)))
+            IF( il_ind /= 0 )THEN
+               tl_dim(ji)%i_xyzt2=il_ind
             ENDIF
             
@@ -652,7 +787,7 @@
          DO ji = 1, ip_maxdim
              
-            il_id=SCAN(TRIM(cl_dimin),TRIM(cp_dimorder(ji:ji)))
-            IF( il_id /= 0 )THEN
-               tl_dim(ji)%i_2xyzt=il_id
+            il_ind=SCAN(TRIM(cl_dimin),TRIM(cl_dimorder(ji:ji)))
+            IF( il_ind /= 0 )THEN
+               tl_dim(ji)%i_2xyzt=il_ind
             ENDIF
             
@@ -669,24 +804,22 @@
          td_dim(:)%i_xyzt2 = tl_dim(:)%i_xyzt2
 
+         ! clean
+         CALL dim_clean(tl_dim(:))
       ENDIF
 
    END SUBROUTINE dim_reorder
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief 
-   !> This subroutine switch dimension table from ordered dimension ('x','y','z','t')
-   !> to unordered dimension.<br/>
+   !-------------------------------------------------------------------
+   !> @brief This subroutine switch dimension array from ordered dimension ('x','y','z','t')
+   !> to unordered dimension. <br/>
+   !> @details
    !> Example: (/'x','y','z','t'/) => (/'z','x','t','y'/)<br/>
-   !> This is useful to add dimension in a variable or file
-   !
+   !  This is useful to add dimension in a variable or file.
    !> @warning this subroutine change dimension order 
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_dim : table of dimension structure
-   !> @return dimension structure unordered 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[inout] td_dim array of dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE dim_unorder(td_dim)
       IMPLICIT NONE
@@ -702,7 +835,7 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension.")
+         CALL logger_error("DIM UNORDER: invalid dimension of array dimension.")
       ELSE      
-         ! add dummy xyzt2 id to removed dimension
+         ! add dummy xyzt2 id to unused dimension
          jj=1
          DO ji = 1, ip_maxdim
@@ -729,6 +862,4 @@
                td_dim(ji)%i_xyzt2=0
                td_dim(ji)%c_sname='u'
-               !td_dim(ji)%c_name='unknown'
-               !td_dim(ji)%c_sname=''
                td_dim(ji)%c_name=''
                td_dim(ji)%l_uld=.FALSE.
@@ -738,79 +869,21 @@
 
    END SUBROUTINE dim_unorder
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine filled dimension structure with unused 
-   !> dimension in order that all dimensions 'x','y','z' and 't' be
-   !> informed, even if void 
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_dim : table of dimension structure
-   !> @return td_dim with unused dimension
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE dim__fill_unused(td_dim)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TDIM), DIMENSION(:), INTENT(INOUT) :: td_dim
-
-      ! local variable
-      CHARACTER(LEN=lc)               :: cl_dimin
-      INTEGER(i4)      , DIMENSION(1) :: il_ind  ! index
-      
-      ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-
-      IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension.")
-      ELSE      
-         ! concatenate dimension used in a character string
-         cl_dimin=fct_lower(fct_concat(td_dim(:)%c_sname))
-         DO ji = 1, ip_maxdim
-
-            ! search missing dimension
-            IF( INDEX(cl_dimin,TRIM(fct_lower(cp_dimorder(ji:ji)))) == 0 )THEN
-               ! search first empty dimension
-               il_ind(:)=MINLOC( td_dim(:)%i_id, td_dim(:)%i_id == 0 )
-
-               ! put missing dimension instead of empty one
-               td_dim(il_ind(1))%c_sname=fct_lower(cp_dimorder(ji:ji))
-               ! update output structure
-               td_dim(il_ind(1))%c_name=fct_lower(cp_dimorder(ji:ji))
-               td_dim(il_ind(1))%i_id=il_ind(1)
-               td_dim(il_ind(1))%i_len=1
-               td_dim(il_ind(1))%l_use=.FALSE.
-
-            ENDIF
-
-         ENDDO
-
-         ! remove id of unused dimension
-         DO ji = 1, ip_maxdim
-            IF( .NOT. td_dim(ji)%l_use ) td_dim(ji)%i_id=0
-         ENDDO
-      ENDIF
-
-   END SUBROUTINE dim__fill_unused
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine reshape real(8) 4D table   
-   !> to an ordered table with dimension (/'x','y','z','t'/).<br/>
+   !-------------------------------------------------------------------
+   !> @brief This function reshape real(8) 4D array   
+   !> to an ordered array, as defined by dim_reorder.<br/>
+   !> @details
    !> Example: (/'z','x','t','y'/) => (/'x','y','z','t'/)
    !
    !> @note you must have run dim_reorder before use this subroutine
    !
-   !> @warning output table dimension differ from input table dimension
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @param[in] dd_value : table of value to reshape
-   !> @return table of value reshaped 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @warning output array dimension differ from input array dimension
+   !
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim    array of dimension structure
+   !> @param[in] dd_value  array of value to reshape
+   !> @return array of value reshaped 
+   !-------------------------------------------------------------------
    FUNCTION dim__reshape_2xyzt_dp(td_dim, dd_value)
       IMPLICIT NONE
@@ -835,5 +908,5 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension.")
+         CALL logger_error("DIM RESHAPE 2 XYZT: invalid dimension of array dimension.")
       ELSE      
 
@@ -841,5 +914,5 @@
 
             CALL logger_fatal( &
-            &  "  RESHAPE to XYZT: you should have run dim_reorder &
+            &  "  DIM RESHAPE 2 XYZT: you should have run dim_reorder &
             &     before running RESHAPE" )
 
@@ -854,10 +927,10 @@
 
             DO ji=1,ip_maxdim
-               CALL logger_debug(" RESHAPE to XYZT: dim "//&
+               CALL logger_debug(" DIM RESHAPE 2 XYZT: dim "//&
                &     TRIM(td_dim(td_dim(ji)%i_xyzt2)%c_name)//" "//&
                &     TRIM(fct_str(td_dim(td_dim(ji)%i_xyzt2)%i_len))//" vs "//&
                &     TRIM(fct_str(il_shape(ji))) )
             ENDDO
-            CALL logger_fatal(" RESHAPE to XYZT: wrong input dimensions " )
+            CALL logger_fatal(" DIM RESHAPE 2 XYZT: wrong input dimensions " )
 
          ELSE
@@ -870,5 +943,5 @@
             cl_dim=TRIM(cl_dim)//TRIM(fct_str(il_shape(ip_maxdim)))//"/)"
 
-            CALL logger_info(" RESHAPE to XYZT: input dimensions are "//&
+            CALL logger_debug(" DIM RESHAPE 2 XYZT: input dimensions are "//&
             &  TRIM(cl_dim) )
 
@@ -879,5 +952,5 @@
             cl_dim=TRIM(cl_dim)//TRIM(fct_str(td_dim(ip_maxdim)%i_len))//"/)"
 
-            CALL logger_info(" RESHAPE to XYZT: ouput dimensions should be "//&
+            CALL logger_debug(" DIM RESHAPE 2 XYZT: ouput dimensions should be "//&
             &  TRIM(cl_dim) )
 
@@ -897,22 +970,21 @@
 
    END FUNCTION dim__reshape_2xyzt_dp
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine reshape ordered real(8) 4D table with dimension 
-   !> (/'x','y','z','t'/) to a table ordered as file variable.<br/>
+   !-------------------------------------------------------------------
+   !> @brief This function reshape ordered real(8) 4D array with dimension 
+   !> (/'x','y','z','t'/) to an "unordered" array.<br/>
+   !> @details
    !> Example: (/'x','y','z','t'/) => (/'z','x','t','y'/)
    !
    !> @note you must have run dim_reorder before use this subroutine
    !
-   !> @warning output table dimension differ from input table dimension
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @param[in] dd_value : table of value to reshape
-   !> @return table of value reshaped 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @warning output array dimension differ from input array dimension
+   !
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim    array of dimension structure
+   !> @param[in] dd_value  array of value to reshape
+   !> @return array of value reshaped 
+   !-------------------------------------------------------------------
    FUNCTION dim__reshape_xyzt2_dp(td_dim, dd_value)
       IMPLICIT NONE
@@ -937,5 +1009,5 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension.")
+         CALL logger_error("DIM RESHAPE XYZT 2: invalid dimension of array dimension.")
       ELSE
 
@@ -943,5 +1015,5 @@
 
             CALL logger_fatal( &
-            &  "  RESHAPE from XYZT: you should have run dim_reorder &
+            &  "  DIM RESHAPE XYZT 2: you should have run dim_reorder &
             &     before running RESHAPE" )
 
@@ -953,10 +1025,10 @@
 
             DO ji=1,ip_maxdim
-               CALL logger_debug(" RESHAPE from XYZT: dim "//&
+               CALL logger_trace(" DIM RESHAPE XYZT 2: dim "//&
                &              TRIM(td_dim(ji)%c_name)//" "//&
                &              TRIM(fct_str(td_dim(ji)%i_len))//" vs "//&
                &              TRIM(fct_str(il_shape(ji))) )
             ENDDO
-            CALL logger_fatal( "RESHAPE from XYZT: wrong input dimensions ")
+            CALL logger_fatal( "DIM RESHAPE XYZT 2: wrong input dimensions ")
 
          ELSE      
@@ -969,5 +1041,5 @@
             cl_dim=TRIM(cl_dim)//TRIM(fct_str(il_shape(ip_maxdim)))//"/)"
 
-            CALL logger_info(" RESHAPE from XYZT: input dimensions are "//&
+            CALL logger_debug(" DIM RESHAPE XYZT 2: input dimensions are "//&
             &  TRIM(cl_dim) )
 
@@ -980,8 +1052,8 @@
             &      TRIM(fct_str(td_dim(td_dim(ip_maxdim)%i_xyzt2)%i_len))//"/)"
 
-            CALL logger_info(" RESHAPE from XYZT: ouput dimensions should be "//&
+            CALL logger_debug(" DIM RESHAPE XYZT 2: ouput dimensions should be "//&
             &  TRIM(cl_dim) )
 
-            ! reshape table
+            ! reshape array
             dim__reshape_xyzt2_dp(:,:,:,:)=RESHAPE(SOURCE=dd_value,  &
             &           SHAPE = (/ td_dim(td_dim(1)%i_xyzt2)%i_len,   &
@@ -994,29 +1066,26 @@
             &                             td_dim(4)%i_xyzt2        /))
 
-
          ENDIF      
       ENDIF      
 
    END FUNCTION dim__reshape_xyzt2_dp
-   !> @endcode    
-   !-------------------------------------------------------------------
-   !> @brief  This subroutine reordered integer(4) 1D table to be suitable 
-   !> with dimension ordered as (/'x','y','z','t'/)
+   !-------------------------------------------------------------------
+   !> @brief  This function reordered integer(4) 1D array to be suitable 
+   !> with dimension ordered as defined in dim_reorder.
    !> @note you must have run dim_reorder before use this subroutine
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @param[in] id_tab : table of value to reshape
-   !> @return table of value reshaped 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION dim__reorder_2xyzt_i4(td_dim, id_tab)
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim array of dimension structure
+   !> @param[in] id_arr array of value to reshape
+   !> @return array of value reshaped 
+   !-------------------------------------------------------------------
+   FUNCTION dim__reorder_2xyzt_i4(td_dim, id_arr)
       IMPLICIT NONE
 
       ! Argument      
       TYPE(TDIM) , DIMENSION(:), INTENT(IN) :: td_dim
-      INTEGER(i4), DIMENSION(:), INTENT(IN) :: id_tab
+      INTEGER(i4), DIMENSION(:), INTENT(IN) :: id_arr
       
       ! function
@@ -1028,12 +1097,12 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim .OR. &
-      &   SIZE(id_tab(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension"//&
-         &              " or of table of value.")
+      &   SIZE(id_arr(:)) /= ip_maxdim )THEN
+         CALL logger_error("DIM REORDER 2 XYZT: invalid dimension of array dimension"//&
+         &              " or of array of value.")
       ELSE      
          IF( ANY(td_dim(:)%i_2xyzt==0) )THEN
 
             CALL logger_error( &
-            &  "  REORDER to XYZT: you should have run dim_reorder &
+            &  "  DIM REORDER 2 XYZT: you should have run dim_reorder &
             &     before running REORDER" )
 
@@ -1041,29 +1110,27 @@
 
          DO ji=1,ip_maxdim
-            dim__reorder_2xyzt_i4(ji)=id_tab(td_dim(ji)%i_2xyzt)
+            dim__reorder_2xyzt_i4(ji)=id_arr(td_dim(ji)%i_2xyzt)
          ENDDO
       ENDIF
 
    END FUNCTION dim__reorder_2xyzt_i4
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine reordered integer(4) 1D table to be suitable with
-   !> dimension read in the file.
+   !-------------------------------------------------------------------
+   !> @brief This function unordered integer(4) 1D array to be suitable with
+   !> initial dimension order (ex: dimension read in file).
    !> @note you must have run dim_reorder before use this subroutine
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @param[in] id_tab : table of value to reshape
-   !> @return table of value reshaped 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION dim__reorder_xyzt2_i4(td_dim, id_tab)
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim array of dimension structure
+   !> @param[in] id_arr array of value to reshape
+   !> @return array of value reshaped 
+   !-------------------------------------------------------------------
+   FUNCTION dim__reorder_xyzt2_i4(td_dim, id_arr)
       IMPLICIT NONE
 
       ! Argument      
       TYPE(TDIM) , DIMENSION(:), INTENT(IN) :: td_dim
-      INTEGER(i4), DIMENSION(:), INTENT(IN) :: id_tab
+      INTEGER(i4), DIMENSION(:), INTENT(IN) :: id_arr
       
       ! function
@@ -1075,12 +1142,12 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim .OR. &
-      &   SIZE(id_tab(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension"//&
-         &              " or of table of value.")
+      &   SIZE(id_arr(:)) /= ip_maxdim )THEN
+         CALL logger_error("DIM REORDER XYZT 2: invalid dimension of array dimension"//&
+         &              " or of array of value.")
       ELSE      
          IF( ANY(td_dim(:)%i_xyzt2==0) )THEN
 
             CALL logger_error( &
-            &  "  REORDER from XYZT: you should have run dim_reorder &
+            &  "  DIM REORDER XYZT 2: you should have run dim_reorder &
             &     before running REORDER" )
 
@@ -1088,28 +1155,26 @@
 
          DO ji=1,ip_maxdim
-            dim__reorder_xyzt2_i4(ji)=id_tab(td_dim(ji)%i_xyzt2)
+            dim__reorder_xyzt2_i4(ji)=id_arr(td_dim(ji)%i_xyzt2)
          ENDDO
       ENDIF
 
    END FUNCTION dim__reorder_xyzt2_i4
-   !> @endcode    
-   !-------------------------------------------------------------------
-   !> @brief  This subroutine reordered logical 1D table to be suitable 
-   !> with dimension ordered as (/'x','y','z','t'/)
+   !-------------------------------------------------------------------
+   !> @brief  This function reordered logical 1D array to be suitable 
+   !> with dimension ordered as defined in dim_reorder.
    !> @note you must have run dim_reorder before use this subroutine
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @param[in] ld_tab : table of value to reordered
-   !> @return table of value reordered 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION dim__reorder_2xyzt_l(td_dim, ld_tab)
+   !> @date Nov, 2013 - Initial Version
+   !
+   !> @param[in] td_dim array of dimension structure
+   !> @param[in] ld_arr array of value to reordered
+   !> @return array of value reordered 
+   !-------------------------------------------------------------------
+   FUNCTION dim__reorder_2xyzt_l(td_dim, ld_arr)
       IMPLICIT NONE
       ! Argument      
       TYPE(TDIM) , DIMENSION(:), INTENT(IN) :: td_dim
-      LOGICAL    , DIMENSION(:), INTENT(IN) :: ld_tab
+      LOGICAL    , DIMENSION(:), INTENT(IN) :: ld_arr
       
       ! function
@@ -1121,12 +1186,12 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim .OR. &
-      &   SIZE(ld_tab(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension"//&
-         &              " or of table of value.")
+      &   SIZE(ld_arr(:)) /= ip_maxdim )THEN
+         CALL logger_error("DIM REORDER 2 XYZT: invalid dimension of array dimension"//&
+         &              " or of array of value.")
       ELSE      
          IF( ANY(td_dim(:)%i_2xyzt==0) )THEN
 
             CALL logger_error( &
-            &  "  REORDER to XYZT: you should have run dim_reorder &
+            &  "  DIM REORDER 2 XYZT: you should have run dim_reorder &
             &     before running REORDER" )
 
@@ -1134,29 +1199,27 @@
 
          DO ji=1,ip_maxdim
-            dim__reorder_2xyzt_l(ji)=ld_tab(td_dim(ji)%i_2xyzt)
+            dim__reorder_2xyzt_l(ji)=ld_arr(td_dim(ji)%i_2xyzt)
          ENDDO
       ENDIF
 
    END FUNCTION dim__reorder_2xyzt_l
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine reordered logical 1D table to be suitable with
-   !> dimension read in the file.
+   !-------------------------------------------------------------------
+   !> @brief This function unordered logical 1D array to be suitable with
+   !> initial dimension order (ex: dimension read in file).
    !> @note you must have run dim_reorder before use this subroutine
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @param[in] ld_tab : table of value to reordered
-   !> @return table of value reordered 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION dim__reorder_xyzt2_l(td_dim, ld_tab)
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim array of dimension structure
+   !> @param[in] ld_arr array of value to reordered
+   !> @return array of value reordered 
+   !-------------------------------------------------------------------
+   FUNCTION dim__reorder_xyzt2_l(td_dim, ld_arr)
       IMPLICIT NONE
 
       ! Argument      
       TYPE(TDIM) , DIMENSION(:), INTENT(IN) :: td_dim
-      LOGICAL    , DIMENSION(:), INTENT(IN) :: ld_tab
+      LOGICAL    , DIMENSION(:), INTENT(IN) :: ld_arr
       
       ! function
@@ -1168,12 +1231,12 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim .OR. &
-      &   SIZE(ld_tab(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension"//&
-         &              " or of table of value.")
+      &   SIZE(ld_arr(:)) /= ip_maxdim )THEN
+         CALL logger_error("DIM REORDER XYZT 2: invalid dimension of array dimension"//&
+         &              " or of array of value.")
       ELSE
          IF( ANY(td_dim(:)%i_xyzt2==0) )THEN
 
             CALL logger_error( &
-            &  "  REORDER from XYZT: you should have run dim_reorder &
+            &  "  DIM REORDER XYZT 2: you should have run dim_reorder &
             &     before running REORDER" )
 
@@ -1181,28 +1244,26 @@
 
          DO ji=1,ip_maxdim
-            dim__reorder_xyzt2_l(ji)=ld_tab(td_dim(ji)%i_xyzt2)
+            dim__reorder_xyzt2_l(ji)=ld_arr(td_dim(ji)%i_xyzt2)
          ENDDO
       ENDIF
 
    END FUNCTION dim__reorder_xyzt2_l
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief  This subroutine reordered string 1D table to be suitable 
-   !> with dimension ordered as (/'x','y','z','t'/)
+   !-------------------------------------------------------------------
+   !> @brief  This function reordered string 1D array to be suitable 
+   !> with dimension ordered as defined in dim_reorder.
    !> @note you must have run dim_reorder before use this subroutine
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @param[in] cd_tab : table of value to reordered
-   !> @return table of value reordered 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION dim__reorder_2xyzt_c(td_dim, cd_tab)
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim array of dimension structure
+   !> @param[in] cd_arr array of value to reordered
+   !> @return array of value reordered 
+   !-------------------------------------------------------------------
+   FUNCTION dim__reorder_2xyzt_c(td_dim, cd_arr)
       IMPLICIT NONE
       ! Argument      
       TYPE(TDIM),       DIMENSION(:), INTENT(IN) :: td_dim
-      CHARACTER(LEN=*), DIMENSION(:), INTENT(IN) :: cd_tab
+      CHARACTER(LEN=*), DIMENSION(:), INTENT(IN) :: cd_arr
       
       ! function
@@ -1214,12 +1275,12 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim .OR. &
-      &   SIZE(cd_tab(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension"//&
-         &              " or of table of value.")
+      &   SIZE(cd_arr(:)) /= ip_maxdim )THEN
+         CALL logger_error("DIM REORDER 2 XYZT: invalid dimension of array dimension"//&
+         &              " or of array of value.")
       ELSE      
          IF( ANY(td_dim(:)%i_2xyzt==0) )THEN
 
             CALL logger_error( &
-            &  "  REORDER to XYZT: you should have run dim_reorder"//&
+            &  "  DIM REORDER 2 XYZT: you should have run dim_reorder"//&
             &  " before running REORDER" )
 
@@ -1227,29 +1288,27 @@
 
          DO ji=1,ip_maxdim
-            dim__reorder_2xyzt_c(ji)=TRIM(cd_tab(td_dim(ji)%i_2xyzt))
+            dim__reorder_2xyzt_c(ji)=TRIM(cd_arr(td_dim(ji)%i_2xyzt))
          ENDDO
       ENDIF
 
    END FUNCTION dim__reorder_2xyzt_c
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine reordered string 1D table to be suitable with
-   !> dimension read in the file.
+   !-------------------------------------------------------------------
+   !> @brief This function unordered string 1D array to be suitable with
+   !> initial dimension order (ex: dimension read in file).
    !> @note you must have run dim_reorder before use this subroutine
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension structure
-   !> @param[in] cd_tab : table of value to reordered
-   !> @return table of value reordered 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION dim__reorder_xyzt2_c(td_dim, cd_tab)
+   !> @date Nov, 2013 - Initial Version
+   !
+   !> @param[in] td_dim array of dimension structure
+   !> @param[in] cd_arr array of value to reordered
+   !> @return array of value reordered 
+   !-------------------------------------------------------------------
+   FUNCTION dim__reorder_xyzt2_c(td_dim, cd_arr)
       IMPLICIT NONE
 
       ! Argument      
       TYPE(TDIM),       DIMENSION(:), INTENT(IN) :: td_dim
-      CHARACTER(LEN=*), DIMENSION(:), INTENT(IN) :: cd_tab
+      CHARACTER(LEN=*), DIMENSION(:), INTENT(IN) :: cd_arr
       
       ! function
@@ -1261,11 +1320,11 @@
 
       IF( SIZE(td_dim(:)) /= ip_maxdim .OR. &
-      &   SIZE(cd_tab(:)) /= ip_maxdim )THEN
-         CALL logger_error("DIM ORDER: invalid dimension of table dimension"//&
-         &              " or of table of value.")
+      &   SIZE(cd_arr(:)) /= ip_maxdim )THEN
+         CALL logger_error("DIM REORDER XYZT 2: invalid dimension of array dimension"//&
+         &              " or of array of value.")
       ELSE
          IF( ANY(td_dim(:)%i_xyzt2==0) )THEN
             CALL logger_error( &
-            &  "  REORDER from XYZT: you should have run dim_reorder &
+            &  "  DIM REORDER XYZT 2: you should have run dim_reorder &
             &     before running REORDER" )
 
@@ -1273,19 +1332,17 @@
 
          DO ji=1,ip_maxdim
-            dim__reorder_xyzt2_c(ji)=TRIM(cd_tab(td_dim(ji)%i_xyzt2))
+            dim__reorder_xyzt2_c(ji)=TRIM(cd_arr(td_dim(ji)%i_xyzt2))
          ENDDO
       ENDIF
 
    END FUNCTION dim__reorder_xyzt2_c
-   !> @endcode    
-   !-------------------------------------------------------------------
-   !> @brief This subroutine clean dimension structure
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : dimension strucutre
-   !-------------------------------------------------------------------
-   !> @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine clean dimension structure.
+   !
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim dimension strucutre
+   !-------------------------------------------------------------------
    SUBROUTINE dim__clean_unit( td_dim )
       IMPLICIT NONE
@@ -1297,6 +1354,6 @@
       !----------------------------------------------------------------
 
-      CALL logger_info( &
-      &  " CLEAN: reset dimension "//TRIM(td_dim%c_name) )
+      CALL logger_trace( &
+      &  " DIM CLEAN: reset dimension "//TRIM(td_dim%c_name) )
 
       ! replace by empty structure
@@ -1304,15 +1361,13 @@
 
    END SUBROUTINE dim__clean_unit
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine clean table of dimension structure
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_dim : table of dimension strucutre
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE dim__clean_tab( td_dim )
+   !-------------------------------------------------------------------
+   !> @brief This subroutine clean array of dimension structure
+   !
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
+   !
+   !> @param[in] td_dim array of dimension strucutre
+   !-------------------------------------------------------------------
+   SUBROUTINE dim__clean_arr( td_dim )
       IMPLICIT NONE
       ! Argument
@@ -1327,6 +1382,5 @@
       ENDDO
 
-   END SUBROUTINE dim__clean_tab
-   !> @endcode
+   END SUBROUTINE dim__clean_arr
 END MODULE dim
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/1_install.md
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/1_install.md	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/1_install.md	(revision 5075)
@@ -0,0 +1,25 @@
+# How to Install
+
+# Install NEMO
+to install SIREN, you should first install NEMO.
+see [here](http://www.nemo-ocean.eu/Using-NEMO/User-Guides/Basics/NEMO-Quick-Start-Guide)
+
+# Compile SIREN
+when NEMO is installed, you just have to compile SIREN codes:
+1. go to ./NEMOGCM/TOOLS
+2. use maketools <br/>
+   to get help: maketools -h 
+
+# Fortran Compiler
+   SIREN codes were succesfully tested with :
+   - ifort (version 12.0.4)
+   - gfortran (version 4.7.2 20121109)
+<!--   - pgf95 (version 13.9-0) -->
+
+ <HR>
+   <b>
+   - @ref index
+   - @ref md_docsrc_3_codingRules
+   - @ref md_docsrc_4_changeLog
+   - @ref todo
+   </b>
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/3_codingRules.md
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/3_codingRules.md	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/3_codingRules.md	(revision 5075)
@@ -0,0 +1,98 @@
+# Coding Rules
+
+The conventions used in SIREN coding are based on the NEMO coding rules
+(see [NEMO coding
+conventions](http://www.nemo-ocean.eu/content/download/15483/73221/file/NEMO_coding.conv_v3.pdf)).<br/>
+However some modifications were added to improve readibility of the code.<br/>
+Some of the NEMO coding rules are reminded here, and extensions are described.
+
+@tableofcontents
+
+# Fortran Standard {#std}
+
+SIREN software adhere to strict __FORTRAN 95__ standard.<br/>
+There is only one exception. The use of functions _COMMAND_ARGUMENT_COUNT_ and
+_GET_COMMAND_ARGUMENT_.<br/>
+There exist no equivalent for those Fortran 03 intrinsec functions in Fortran
+95.<br/> At least none convenient for compilers tested (see @ref md_docsrc_1_install). 
+
+#  Free Form Source {#free}
+Free Form Source will be used, however a self imposed limit of 80 should
+enhance readibility.
+
+#  Indentation {#indent}
+Code as well as comments lines will be indented 3 characters for readibility.<br/>
+__Indentation should be write without hard tabs__.
+
+Example for vi  :
+~~~~~~~~~~~~~~~~~~~~~
+:set expandtab tabstop=3 shiftwidth=3
+~~~~~~~~~~~~~~~~~~~~~
+
+#  Naming conventions : variable {#namvar}
+All variables should be named as explicitly as possible.<br/>
+The naming conventions concerns prefix letters of these name, in order to
+identify the variable type and status.<br/> It must be composed of two
+letters defining type and status follow by an underscore.<br/>
+table below list the starting letters to be used for variable naming,
+depending on their type and status.
+
+ | Type / Status     | byte (integer(1)) <br/> __b__ | short (integer(2)) <br/> __s__ | integer(4) <br/> __i__  | integer(8) <br/> __k__ | real(4) <br/> __r__ | real(8) <br/> __d__ | logical <br/> __l__ | character <br/> __c__ | complex <br/> __y__ | structure <br/> __t__  |
+ | :----:            | :----: | :----: | :----: | :----: | :----: | :----: | :----: | :----: | :----: | :----: |
+ |global <br/> __g__           | bg_  | sg_  | ig_  | kg_  | rg_  | dg_  | lg_  | cg_  | yg_  | tg_  |
+ |global parameter <br/> __p__ | bp_  | sp_  | ip_  | kp_  | rp_  | dp_  | lp_  | cp_  | yp_  | tp_  |
+ |module <br/> __m__           | bm_  | sm_  | im_  | km_  | rm_  | dm_  | lm_  | cm_  | ym_  | tm_  |
+ |namelist <br/> __n__         | bn_  | sn_  | in_  | kn_  | rn_  | dn_  | ln_  | cn_  | yn_  | tn_  |
+ |dummy argument <br/> __d__   | bd_  | sd_  | id_  | kd_  | rd_  | dd_  | ld_  | cd_  | yd_  | td_  |
+ |local <br/> __l__            | bl_  | sl_  | il_  | kl_  | rl_  | dl_  | ll_  | cl_  | yl_  | tl_  |
+ |loop control       |      |      | j?   |      |      |      |      |      |      |      |
+
+# Naming conventions : structure {#namstr}
+The structure name should be written in capital letter, and start with
+__T__<br/> Example: TTRACER <br/>
+Variables inside the structure should be named as explicitly as possible.<br/>
+For those variables, the prefix naming conventions only concern the type of variable.<br/>
+It must be composed of one letter defining type follows by an
+underscore.<br/>
+see table of variable conventions.<br/>
+
+Example: __tl\_type\%i\_year__<br/> _year_ is an integer(4) variable in a local strucure
+named _type_. <br/>
+
+# Naming conventions : function-subroutine {#namsub}
+Functions or Subroutines are defined in a module.<br/>
+Their name should start with the module name then with their "functional" name. So it will be
+easy to find it.<br/>
+Example:<br/> a function to realise addition written in a module
+__math__ should be called __math\_add__.<br/>
+
+__PUBLIC__  function or subroutine should used one undescrore: _math_add_<br/>
+__PRIVATE__ function or subroutine should used two undescrores: _math__add_<br/>
+
+# Precision {#precision}
+__All variables should make use of kinds__.<br/>
+Numerical constant need to have a suffix of __kindvalue__
+
+# Declaration for global variable and constants {#global}
+All global data must be accompanied with a comment field on the same
+line.<br/>
+_Note that using doxygen (see [header](#header)), we will use symbol !< instead of !: as separator_
+
+# Implicit none {#implicit}
+All subroutines and functions will include an IMPLICTI NONE statement.
+
+# Header {#header}
+
+SIREN use __doxigen auto documentation__ tool.<br/>
+Information could be find on
+[doxygen](http://www.stack.nl/~dimitri/doxygen/index.html) web page.<br/>
+Some basic tag are described
+[here](http://www.msg.chem.iastate.edu/gamess/DoxygenRules.oct10.pdf).
+
+ <HR>
+   <b>
+   - @ref index
+   - @ref md_docsrc_1_install
+   - @ref md_docsrc_4_changeLog
+   - @ref todo
+   </b>
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/4_changeLog.md
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/4_changeLog.md	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/4_changeLog.md	(revision 5075)
@@ -0,0 +1,18 @@
+# Change log
+
+@tableofcontents
+
+# Release 3.6
+Initial release (release date )
+
+## Changes
+## New Features
+## Bug fixes
+
+ <HR>
+   <b>
+   - @ref index
+   - @ref md_docsrc_1_install
+   - @ref md_docsrc_3_codingRules
+   - @ref todo
+   </b>
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/main.dox
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/main.dox	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/docsrc/main.dox	(revision 5075)
@@ -0,0 +1,42 @@
+/*!
+ @mainpage Main Page
+ @section descr Generic Description
+ SIREN is a software to create regional configuration with
+ [NEMO](http://www.nemo-ocean.eu).<br/> 
+ Actually SIREN create input files needed for a basic NEMO configuration.<br/>
+ 
+ SIREN is composed of a set of 5 Fortran programs :
+   - create_coord.f90 to create fine grid coordinate file from coarse grid coordinate file.
+   - create_bathy.f90 to create fine grid bathymetry file over domain.
+   - merge_bathy.f90 to merge fine grid bathymetry with coarse grid bathymetry at boundaries.
+   - create_restart.f90 to create initial state file from coarse grid restart or standard outputs.
+   - create_boundary.f90 to create boundary condition from coarse grid standard outputs.
+
+To install those programs see @ref md_docsrc_1_install.
+
+ @note SIREN can not:
+ - create global configuration
+ - create configuarion around or close to north pole
+ - change number of vertical level
+ - change grid (horizontal or vertical)
+
+ @section howto How to use
+   @subsection howto_coord to create fine grid coordinate file
+   see create_coord.f90
+   @subsection howto_bathy to create fine grid bathymetry
+   see create_bathy.f90
+   @subsection howto_merge to merge fine grid bathymetry
+   see merge_bathy.f90
+   @subsection howto_restart to create initial state file
+   see create_restart.f90
+   @subsection howto_boundary to create boundary condition
+   see create_boundary.f90
+
+<HR>
+   <b>
+   - @ref md_docsrc_1_install
+   - @ref md_docsrc_3_codingRules
+   - @ref md_docsrc_4_changeLog
+   - @ref todo
+   </b>
+*/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/domain.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/domain.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/domain.f90	(revision 5075)
@@ -8,17 +8,122 @@
 !> @brief
 !> This module manage domain computation.
-!
+!>
 !> @details
-!>
-!>
-!>
-!>
+!>    define type TDOM:<br/>
+!> @code
+!>    TYPE(TDOM) :: tl_dom
+!> @endcode
+!>
+!>    to initialize domain structure:<br/>
+!> @code
+!>    tl_dom=dom_init(td_mpp, [id_imin,] [id_imax,] [id_jmin,] [id_jmax],[cd_card])
+!> @endcode
+!>       - td_mpp  is mpp structure of an opened file.
+!>       - id_imin is i-direction sub-domain lower left  point indice
+!>       - id_imax is i-direction sub-domain upper right point indice 
+!>       - id_jmin is j-direction sub-domain lower left  point indice
+!>       - id_jmax is j-direction sub-domain upper right point indice
+!>       - cd_card is the cardinal name (for boundary case) 
+!> 
+!>    to get global domain dimension:<br/>
+!>    - tl_dom\%t_dim0
+!>
+!>    to get NEMO periodicity index of global domain:<br/>
+!>    - tl_dom\%i_perio0
+!>
+!>    to get NEMO pivot point index F(0),T(1):<br/>
+!>    - tl_dom\%i_pivot
+!>
+!>    to get East-West overlap of global domain:<br/>
+!>    - tl_dom\%i_ew0
+!>
+!>    to get selected sub domain dimension:<br/>
+!>    - tl_dom\%t_dim
+!>
+!>    to get NEMO periodicity index of sub domain:<br/>
+!>    - tl_dom\%i_perio
+!>
+!>    to get East-West overlap of sub domain:<br/>
+!>    - tl_dom\%i_ew
+!>
+!>    to get i-direction sub-domain lower left  point indice:<br/>
+!>    - tl_dom\%i_imin
+!>
+!>    to get i-direction sub-domain upper right point indice:<br/>
+!>    - tl_dom\%i_imax
+!>
+!>    to get j-direction sub-domain lower left  point indice:<br/>
+!>    - tl_dom\%i_jmin
+!>
+!>    to get j-direction sub-domain upper right point indice:<br/>
+!>    - tl_dom\%i_jmax
+!>
+!>    to get size of i-direction extra band:<br/>
+!>    - tl_dom\%i_iextra
+!>
+!>    to get size of j-direction extra band:<br/>
+!>    - tl_dom\%i_jextra
+!>
+!>    to get i-direction ghost cell number:<br/>
+!>    - tl_dom\%i_ighost
+!>
+!>    to get j-direction ghost cell number:<br/>
+!>    - tl_dom\%i_jghost
+!>
+!>    to get boundary index:<br/>
+!>    - tl_dom\%i_bdy
+!>       - 0 = no boundary
+!>       - 1 = north
+!>       - 2 = south 
+!>       - 3 = east 
+!>       - 4 = west
+!>
+!>    to clean domain structure:<br/>
+!> @code
+!>    CALL dom_clean(td_dom)
+!> @endcode
+!>       - td_dom is domain structure
+!>
+!>    to print information about domain structure:<br/>
+!> @code
+!>    CALL dom_print(td_dom)
+!> @endcode
+!>
+!>    to get East-West overlap (if any):<br/>
+!> @code
+!>    il_ew=dom_get_ew_overlap(td_lon)
+!> @endcode
+!>       - td_lon : longitude variable structure
+!>
+!>    to add extra bands to coarse grid domain (for interpolation):<br/>
+!> @code
+!>    CALL dom_add_extra( td_dom, id_iext, id_jext ) 
+!> @endcode
+!>       - td_dom is domain structure
+!>       - id_iext is i-direction size of extra bands
+!>       - id_jext is j-direction size of extra bands
+!> 
+!>    to remove extra bands from fine grid (after interpolation):<br/>
+!> @code
+!>    CALL dom_del_extra( td_var, td_dom, id_rho )
+!> @endcode
+!>       - td_var is variable structure to be changed
+!>       - td_dom is domain structure
+!>       - id_rho is a array of refinement factor following i- and j-direction
+!>    
+!>    to reset coarse grid domain witouht extra bands:<br/>
+!> @code
+!>    CALL dom_clean_extra( td_dom )
+!> @endcode
 !>
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!> @todo
-!> - check use of id_pivot
+!> @date November, 2013 - Initial Version
+!> @date September, 2014
+!> - add header
+!> - use zero indice to defined cyclic or global domain
+!> @date October, 2014
+!> - use mpp file structure instead of file
 !> 
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -28,10 +133,9 @@
    USE global                          ! global parameter
    USE fct                             ! basic useful function
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE dim                             ! dimension manager
    USE var                             ! variable manager
-   USE file                            ! file manager
+   USE mpp                             ! mpp file manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
@@ -39,51 +143,57 @@
    PUBLIC :: TDOM     !< domain structure
 
+   PRIVATE :: im_minext !< default minumum number of extraband
+
    ! function and subroutine
-   PUBLIc :: dom_clean     !< clean domain structure
-   PUBLIC :: dom_init      !< initialise domain structure
-   PUBLIC :: dom_print     !< print information about domain
-   PUBLIC :: dom_get_ew_overlap !< get east west overlap
-   PUBLIC :: dom_add_extra   !< add useful extra point to coarse grid for interpolation
-   PUBLIC :: dom_clean_extra  !< reset domain without extra point
-   PUBLIC :: dom_del_extra   !< remove extra point from fine grid after interpolation
+   PUBLIC :: dom_copy            !< copy domain structure
+   PUBLIc :: dom_clean           !< clean domain structure
+   PUBLIC :: dom_init            !< initialise domain structure
+   PUBLIC :: dom_print           !< print information about domain
+   PUBLIC :: dom_add_extra       !< add useful extra bands to coarse grid for interpolation
+   PUBLIC :: dom_clean_extra     !< reset domain without extra bands
+   PUBLIC :: dom_del_extra       !< remove extra point from fine grid after interpolation
     
-   PRIVATE :: dom__define    !< define extract domain indices
-                                            !< define extract domain indices for input domain with
-   PRIVATE :: dom__define_cyclic_north_fold !< - cyclic east-west boundary and north fold boundary condition.
-   PRIVATE :: dom__define_north_fold        !< - north fold boundary condition.
-   PRIVATE :: dom__define_symmetric         !< - symmetric boundary condition across the equator.
-   PRIVATE :: dom__define_cyclic            !< - cyclic east-west boundary.
-   PRIVATE :: dom__define_closed            !< - cyclic east-west boundary.
-   PRIVATE :: dom__check_EW_index           !< check East-West indices
-                                            !< compute size of an extract domain
-   PRIVATE :: dom__size_no_pole             !< - without north fold condition
-   PRIVATE :: dom__size_no_pole_overlap     !< - without north fold condition, and which overlap east-west boundary
-   PRIVATE :: dom__size_no_pole_no_overlap  !< - without north fold condition, and which do not overlap east-west boundary
-   PRIVATE :: dom__size_pole                !< - with north fold condition
-   PRIVATE :: dom__size_pole_overlap        !< - with north fold condition, and which overlap east-west boundary
-   PRIVATE :: dom__size_pole_no_overlap     !< - with north fold condition, and which do not overlap east-west boundary
-
-   !> @struct
-   TYPE TDOM
-      TYPE(TDIM), DIMENSION(ip_maxdim)  :: t_dim0           !< global domain dimension
-      TYPE(TDIM), DIMENSION(ip_maxdim)  :: t_dim              !< sub domain dimension
-      INTEGER(i4) :: i_perio0   !< NEMO periodicity index
-      INTEGER(i4) :: i_ew0      !< East-West overlap
-      INTEGER(i4) :: i_perio    !< NEMO periodicity index
-      INTEGER(i4) :: i_pivot    !< NEMO pivot point index F(0),T(1)
-      INTEGER(i4) :: i_imin = 1 !< i-direction sub-domain lower left  point indice
-      INTEGER(i4) :: i_imax = 1 !< i-direction sub-domain upper right point indice
-      INTEGER(i4) :: i_jmin = 1 !< j-direction sub-domain lower left  point indice
-      INTEGER(i4) :: i_jmax = 1 !< j-direction sub-domain upper right point indice
-      INTEGER(i4) :: i_kmin = 1 !< k-direction sub-domain lower level indice
-      INTEGER(i4) :: i_kmax = 1 !< k-direction sub-domain upper level indice
-      INTEGER(i4) :: i_lmin = 1 !< l-direction sub-domain lower time indice
-      INTEGER(i4) :: i_lmax = 1 !< l-direction sub-domain upper time indice
-
-      INTEGER(i4) :: i_ighost = 0 !< i-direction ghost cell factor
-      INTEGER(i4) :: i_jghost = 0 !< j-direction ghost cell factor
-
-      INTEGER(i4), DIMENSION(2) :: i_iextra = 0 !< i-direction extra point
-      INTEGER(i4), DIMENSION(2) :: i_jextra = 0 !< j-direction extra point
+   PRIVATE :: dom__init_mpp                 ! initialise domain structure, given mpp file structure
+   PRIVATE :: dom__define                   ! define sub domain indices
+                                            ! define sub domain indices for input domain with
+   PRIVATE :: dom__define_cyclic_north_fold ! - cyclic east-west boundary and north fold boundary condition.
+   PRIVATE :: dom__define_north_fold        ! - north fold boundary condition.
+   PRIVATE :: dom__define_symmetric         ! - symmetric boundary condition across the equator.
+   PRIVATE :: dom__define_cyclic            ! - cyclic east-west boundary.
+   PRIVATE :: dom__define_closed            ! - cyclic east-west boundary.
+                                            ! compute size of sub domain
+   PRIVATE :: dom__size_no_pole             ! - without north fold condition
+   PRIVATE :: dom__size_no_pole_overlap     ! - without north fold condition, and which overlap east-west boundary
+   PRIVATE :: dom__size_no_pole_no_overlap  ! - without north fold condition, and which do not overlap east-west boundary
+   PRIVATE :: dom__size_pole                ! - with north fold condition
+   PRIVATE :: dom__size_pole_overlap        ! - with north fold condition, and which overlap east-west boundary
+   PRIVATE :: dom__size_pole_no_overlap     ! - with north fold condition, and which do not overlap east-west boundary
+                                            ! compute size of
+   PRIVATE :: dom__size_global              ! - global domain
+   PRIVATE :: dom__size_semi_global         ! - semi global domain 
+   PRIVATE :: dom__copy_unit                ! copy attribute structure
+
+   TYPE TDOM !< domain structure
+      TYPE(TDIM), DIMENSION(ip_maxdim)  :: t_dim0  !< global domain dimension
+      TYPE(TDIM), DIMENSION(ip_maxdim)  :: t_dim   !< sub domain dimension
+      INTEGER(i4) :: i_perio0                      !< NEMO periodicity index of global domain
+      INTEGER(i4) :: i_ew0                         !< East-West overlap of global domain
+      INTEGER(i4) :: i_perio                       !< NEMO periodicity index of sub domain
+      INTEGER(i4) :: i_pivot                       !< NEMO pivot point index F(0),T(1)
+      INTEGER(i4) :: i_imin = 0                    !< i-direction sub-domain lower left  point indice
+      INTEGER(i4) :: i_imax = 0                    !< i-direction sub-domain upper right point indice
+      INTEGER(i4) :: i_jmin = 0                    !< j-direction sub-domain lower left  point indice
+      INTEGER(i4) :: i_jmax = 0                    !< j-direction sub-domain upper right point indice
+
+      INTEGER(i4) :: i_bdy = 0                     !< boundary index : 0 = no boundary
+                                                   !<                  1 = north
+                                                   !<                  2 = south 
+                                                   !<                  3 = east 
+                                                   !<                  4 = west 
+      INTEGER(i4), DIMENSION(2,2) :: i_ghost0 = 0   !< array of ghost cell factor of global domain
+      INTEGER(i4), DIMENSION(2,2) :: i_ghost  = 0   !< array of ghost cell factor of sub domain
+
+      INTEGER(i4), DIMENSION(2) :: i_iextra = 0    !< i-direction extra point
+      INTEGER(i4), DIMENSION(2) :: i_jextra = 0    !< j-direction extra point
 
    END TYPE TDOM
@@ -92,10 +202,45 @@
 
    INTERFACE dom_init
-      MODULE PROCEDURE dom_init_file
-!      MODULE PROCEDURE dom_init_mpp
+      MODULE PROCEDURE dom__init_file
+      MODULE PROCEDURE dom__init_mpp
    END INTERFACE dom_init
 
+   INTERFACE dom_copy
+      MODULE PROCEDURE dom__copy_unit  ! copy attribute structure
+   END INTERFACE
+
 CONTAINS
    !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine copy an domain structure in another one
+   !> @details 
+   !> dummy function to get the same use for all structure
+   !>
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_dom=dom_copy(dom_init()) is forbidden).
+   !> This will create memory leaks.
+   !> @warning to avoid infinite loop, do not use any function inside 
+   !> this subroutine
+   !>
+   !> @author J.Paul
+   !> @date November, 2014 - Initial Version
+   !>
+   !> @param[in] td_dom   domain structure
+   !> @return copy of input domain structure
+   !-------------------------------------------------------------------
+   FUNCTION dom__copy_unit( td_dom )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TDOM), INTENT(IN)  :: td_dom
+      ! function
+      TYPE(TDOM) :: dom__copy_unit
+
+      ! local variable
+      !----------------------------------------------------------------
+
+      dom__copy_unit=td_dom
+      
+      END FUNCTION dom__copy_unit
+   !-------------------------------------------------------------------
    !> @brief This subroutine print some information about domain strucutre.
    !
@@ -103,7 +248,6 @@
    !> - Nov, 2013- Initial Version
    !
-   !> @param[inout] td_dom : dom structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[inout] td_dom dom structure
+   !-------------------------------------------------------------------
    SUBROUTINE dom_print(td_dom)
       IMPLICIT NONE
@@ -123,7 +267,10 @@
       END SELECT
 
-      WRITE(*,'((a,4(i0,1x)),(/a,i2,a,a),(/a,4(i0,1x)),(/a,i2/),10(/a,i0))') &
+      WRITE(*,'((a,4(i0,1x)),(/a,i2,a,a),2(/a,2(i0,1x)),(/a,4(i0,1x)),(/a,i2/),&
+      &          4(/a,i0),4(/a,2(i0,1x)))') &
       &  " global domain size ",td_dom%t_dim0(:)%i_len, &
       &  " domain periodicity ",td_dom%i_perio0,", pivot: ",TRIM(cl_pivot),   &
+      &  " i-direction ghost cell factor of global domain  ",td_dom%i_ghost0(jp_I,:), &
+      &  " j-direction ghost cell factor of global domain  ",td_dom%i_ghost0(jp_J,:), &
       &  " sub-domain size : ",td_dom%t_dim(:)%i_len,                         &
       &  " sub domain periodicity ",td_dom%i_perio,                           &
@@ -132,58 +279,181 @@
       &  " j-direction sub-domain lower left  point indice ",td_dom%i_jmin,   &
       &  " j-direction sub-domain upper right point indice ",td_dom%i_jmax,   &
-!      &  " k-direction sub-domain lower level indice       ",td_dom%i_kmin,   &
-!      &  " k-direction sub-domain upper level indice       ",td_dom%i_kmax,   &
-!      &  " l-direction sub-domain lower time indice        ",td_dom%i_lmin,   &
-!      &  " l-direction sub-domain upper time indice        ",td_dom%i_lmax,   &
-      &  " i-direction ghost cell factor                   ",td_dom%i_ighost, &
-      &  " j-direction ghost cell factor                   ",td_dom%i_jghost
+      &  " i-direction ghost cell factor                   ",td_dom%i_ghost(jp_I,:), &
+      &  " j-direction ghost cell factor                   ",td_dom%i_ghost(jp_J,:), &
+      &  " i-direction extra point for interpolation       ",td_dom%i_iextra(:), &
+      &  " j-direction extra point for interpolation       ",td_dom%i_jextra(:)
 
       END SUBROUTINE dom_print
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
    !> This function intialise domain structure, given open file structure,
-   !> and grid periodicity. 
+   !> and sub domain indices. 
+   !> @details
+   !> sub domain indices are computed, taking into account coarse grid
+   !> periodicity, pivot point, and East-West overlap.
    !
    !> @author J.Paul
    !> - June, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_perio : grid periodicity
-   !> @param[in] id_imin : i-direction sub-domain lower left  point indice
-   !> @param[in] id_imax : i-direction sub-domain upper right point indice
-   !> @param[in] id_jmin : j-direction sub-domain lower left  point indice
-   !> @param[in] id_jmax : j-direction sub-domain upper right point indice
-   !> @param[in] id_kmin : k-direction sub-domain lower level indice
-   !> @param[in] id_kmax : k-direction sub-domain upper level indice
-   !> @param[in] id_lmin : l-direction sub-domain lower time indice
-   !> @param[in] id_lmax : l-direction sub-domain upper time indice
+   !> @date September, 2014
+   !> - add boundary index
+   !> - add ghost cell factor
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !>
+   !> @param[in] td_mpp    mpp structure
+   !> @param[in] id_perio  grid periodicity
+   !> @param[in] id_imin   i-direction sub-domain lower left  point indice
+   !> @param[in] id_imax   i-direction sub-domain upper right point indice
+   !> @param[in] id_jmin   j-direction sub-domain lower left  point indice
+   !> @param[in] id_jmax   j-direction sub-domain upper right point indice
+   !> @param[in] cd_card   name of cardinal (for boundary)
    !> @return domain structure
-   !>
-   !> @todo
-   !> - initialiser domain
-   !> - add info new perio.. dans sortie
-   !-------------------------------------------------------------------
-   !> @code
-   TYPE(TDOM) FUNCTION dom_init_file( td_file, &
-   &                                  id_imin, id_imax, id_jmin, id_jmax )
-!   &                                  id_kmin, id_kmax, id_lmin, id_lmax )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TFILE), INTENT(IN) :: td_file 
-      INTEGER(i4), INTENT(IN), OPTIONAL :: id_imin
-      INTEGER(i4), INTENT(IN), OPTIONAL :: id_imax
-      INTEGER(i4), INTENT(IN), OPTIONAL :: id_jmin
-      INTEGER(i4), INTENT(IN), OPTIONAL :: id_jmax
-!      INTEGER(i4), INTENT(IN), OPTIONAL :: id_kmin
-!      INTEGER(i4), INTENT(IN), OPTIONAL :: id_kmax
-!      INTEGER(i4), INTENT(IN), OPTIONAL :: id_lmin
-!      INTEGER(i4), INTENT(IN), OPTIONAL :: id_lmax
-
+   !-------------------------------------------------------------------
+   TYPE(TDOM) FUNCTION dom__init_mpp( td_mpp, &
+   &                                  id_imin, id_imax, id_jmin, id_jmax, &
+   &                                  cd_card )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TMPP)      , INTENT(IN) :: td_mpp 
+
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_imin
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_imax
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_jmin
+      INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_jmax
+
+      CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: cd_card
       !local variable
       !----------------------------------------------------------------
 
       ! clean domain structure
-      CALL dom_clean(dom_init_file)
+      CALL dom_clean(dom__init_mpp)
+
+      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
+
+         CALL logger_error( &
+         &  " DOM INIT: no processor file associated to mpp "//&
+         &  TRIM(td_mpp%c_name))
+
+      ELSE
+         ! global domain define by file
+
+         ! look for boundary index
+         IF( PRESENT(cd_card) )THEN
+            SELECT CASE(TRIM(cd_card))
+               CASE('north')
+                  dom__init_mpp%i_bdy=jp_north
+               CASE('south')
+                  dom__init_mpp%i_bdy=jp_south
+               CASE('east')
+                  dom__init_mpp%i_bdy=jp_east
+               CASE('west')
+                  dom__init_mpp%i_bdy=jp_west
+               CASE DEFAULT
+                  ! no boundary
+                  dom__init_mpp%i_bdy=0
+            END SELECT
+         ELSE
+            ! no boundary
+            dom__init_mpp%i_bdy=0
+         ENDIF
+
+         ! use global dimension define by mpp file
+         dom__init_mpp%t_dim0(:) = dim_copy(td_mpp%t_dim(:))
+
+         IF( td_mpp%i_perio < 0 .OR. td_mpp%i_perio > 6 )THEN
+            CALL logger_error("DOM INIT: invalid grid periodicity. "//&
+            &  "you should use grid_get_perio to compute it")
+         ELSE
+            dom__init_mpp%i_perio0=td_mpp%i_perio
+         ENDIF
+
+         ! global domain pivot point
+         SELECT CASE(dom__init_mpp%i_perio0)
+            CASE(3,4)
+               dom__init_mpp%i_pivot = 0
+            CASE(5,6)
+               dom__init_mpp%i_pivot = 1
+            CASE DEFAULT
+               dom__init_mpp%i_pivot = 0
+         END SELECT
+
+         ! add ghost cell factor of global domain
+         dom__init_mpp%i_ghost0(:,:)=0
+         SELECT CASE(dom__init_mpp%i_perio0)
+            CASE(0)
+               dom__init_mpp%i_ghost0(:,:)=1
+            CASE(1)
+               dom__init_mpp%i_ghost0(jp_J,:)=1
+            CASE(2)
+               dom__init_mpp%i_ghost0(jp_I,:)=1
+               dom__init_mpp%i_ghost0(jp_J,2)=1
+            CASE(3,5)
+               dom__init_mpp%i_ghost0(jp_I,:)=1
+               dom__init_mpp%i_ghost0(jp_J,1)=1
+            CASE(4,6)
+               dom__init_mpp%i_ghost0(jp_J,1)=1
+         END SELECT
+
+         ! look for EW overlap
+         dom__init_mpp%i_ew0=td_mpp%i_ew
+
+         ! initialise domain as global
+         dom__init_mpp%i_imin = 1 
+         dom__init_mpp%i_imax = dom__init_mpp%t_dim0(1)%i_len
+
+         dom__init_mpp%i_jmin = 1 
+         dom__init_mpp%i_jmax = dom__init_mpp%t_dim0(2)%i_len
+
+         ! sub domain dimension
+         dom__init_mpp%t_dim(:) = dim_copy(td_mpp%t_dim(:))
+
+         ! define sub domain indices 
+         CALL dom__define( dom__init_mpp, &
+         &                 id_imin, id_imax, id_jmin, id_jmax )
+
+      ENDIF
+
+   END FUNCTION dom__init_mpp
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This function intialise domain structure, given open file structure,
+   !> and sub domain indices. 
+   !> @details
+   !> sub domain indices are computed, taking into account coarse grid
+   !> periodicity, pivot point, and East-West overlap.
+   !
+   !> @author J.Paul
+   !> - June, 2013- Initial Version
+   !> @date September, 2014
+   !> - add boundary index
+   !> - add ghost cell factor
+   !>
+   !> @param[in] td_file   file structure
+   !> @param[in] id_perio  grid periodicity
+   !> @param[in] id_imin   i-direction sub-domain lower left  point indice
+   !> @param[in] id_imax   i-direction sub-domain upper right point indice
+   !> @param[in] id_jmin   j-direction sub-domain lower left  point indice
+   !> @param[in] id_jmax   j-direction sub-domain upper right point indice
+   !> @param[in] cd_card   name of cardinal (for boundary)
+   !> @return domain structure
+   !-------------------------------------------------------------------
+   TYPE(TDOM) FUNCTION dom__init_file( td_file, &
+   &                                   id_imin, id_imax, id_jmin, id_jmax, &
+   &                                   cd_card )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TFILE)      , INTENT(IN) :: td_file 
+
+      INTEGER(i4)      , INTENT(IN), OPTIONAL :: id_imin
+      INTEGER(i4)      , INTENT(IN), OPTIONAL :: id_imax
+      INTEGER(i4)      , INTENT(IN), OPTIONAL :: id_jmin
+      INTEGER(i4)      , INTENT(IN), OPTIONAL :: id_jmax
+
+      CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: cd_card
+      !local variable
+      !----------------------------------------------------------------
+
+      ! clean domain structure
+      CALL dom_clean(dom__init_file)
 
       IF( td_file%i_id == 0 )THEN
@@ -195,144 +465,97 @@
          ! global domain define by file
 
+         ! look for boundary index
+         IF( PRESENT(cd_card) )THEN
+            SELECT CASE(TRIM(cd_card))
+               CASE('north')
+                  dom__init_file%i_bdy=jp_north
+               CASE('south')
+                  dom__init_file%i_bdy=jp_south
+               CASE('east')
+                  dom__init_file%i_bdy=jp_east
+               CASE('west')
+                  dom__init_file%i_bdy=jp_west
+               CASE DEFAULT
+                  ! no boundary
+                  dom__init_file%i_bdy=0
+            END SELECT
+         ELSE
+            ! no boundary
+            dom__init_file%i_bdy=0
+         ENDIF
+
          ! use global dimension define by file
-         dom_init_file%t_dim0(:) = td_file%t_dim(:)
+         dom__init_file%t_dim0(:) = dim_copy(td_file%t_dim(:))
 
          IF( td_file%i_perio < 0 .OR. td_file%i_perio > 6 )THEN
             CALL logger_error("DOM INIT: invalid grid periodicity. "//&
-            &  "you should use dom_get_perio to compute it")
+            &  "you should use grid_get_perio to compute it")
          ELSE
-            dom_init_file%i_perio0=td_file%i_perio
+            dom__init_file%i_perio0=td_file%i_perio
          ENDIF
 
          ! global domain pivot point
-         SELECT CASE(dom_init_file%i_perio0)
+         SELECT CASE(dom__init_file%i_perio0)
             CASE(3,4)
-               dom_init_file%i_pivot = 0
+               dom__init_file%i_pivot = 0
             CASE(5,6)
-               dom_init_file%i_pivot = 1
+               dom__init_file%i_pivot = 1
             CASE DEFAULT
-               dom_init_file%i_pivot = 0
+               dom__init_file%i_pivot = 0
          END SELECT
 
+         ! add ghost cell factor of global domain
+         dom__init_file%i_ghost0(:,:)=0
+         SELECT CASE(dom__init_file%i_perio0)
+            CASE(0)
+               dom__init_file%i_ghost0(:,:)=1
+            CASE(1)
+               dom__init_file%i_ghost0(jp_J,:)=1
+            CASE(2)
+               dom__init_file%i_ghost0(jp_I,:)=1
+               dom__init_file%i_ghost0(jp_J,2)=1
+            CASE(3,5)
+               dom__init_file%i_ghost0(jp_I,:)=1
+               dom__init_file%i_ghost0(jp_J,1)=1
+            CASE(4,6)
+               dom__init_file%i_ghost0(jp_J,1)=1
+         END SELECT
+
          ! look for EW overlap
-         dom_init_file%i_ew0=td_file%i_ew
+         dom__init_file%i_ew0=td_file%i_ew
 
          ! initialise domain as global
-         dom_init_file%i_imin = 1 
-         dom_init_file%i_imax = dom_init_file%t_dim0(1)%i_len
-
-         dom_init_file%i_jmin = 1 
-         dom_init_file%i_jmax = dom_init_file%t_dim0(2)%i_len
-
-!         dom_init_file%i_kmin = 1 
-!         dom_init_file%i_kmax = dom_init_file%t_dim(3)%i_len
-!
-!         dom_init_file%i_lmin = 1 
-!         dom_init_file%i_lmax = dom_init_file%t_dim(4)%i_len
-
-         ! extract domain dimension
-         dom_init_file%t_dim(:) = td_file%t_dim(:)
-
-         ! define extract domain indices 
-         CALL dom__define( dom_init_file, &
-   &                       id_imin, id_imax, id_jmin, id_jmax )
-!   &                       id_kmin, id_kmax, id_lmin, id_lmax )
-
-      ENDIF
-
-   END FUNCTION dom_init_file
-   !> @endcode
- !  !-------------------------------------------------------------------
- !  !> @brief 
- !  !> This function intialise domain structure, given mpp structure,
- !  !> and variable name. domain indices could be specify.
- !  !
- !  !> @details
- !  !> 
- !  !
- !  !> @author J.Paul
- !  !> - Nov, 2013- Initial Version
- !  !
- !  !> @param[in] td_mpp : mpp structure
- !  !> @param[in] cd_varname : variable name
- !  !> @return domain structure
- !  !>
- !  !> @todo
- !  !> - initialiser domain
- !  !-------------------------------------------------------------------
- !  !> @code
- !  TYPE(TDOM) FUNCTION dom_init_mpp( td_mpp, cd_varname )
- !     IMPLICIT NONE
- !     ! Argument      
- !     TYPE(TMPP),       INTENT(IN) :: td_mpp 
- !     CHARACTER(LEN=*), INTENT(IN) :: cd_varname
- !     !----------------------------------------------------------------
-
- !     ! clean domain structure
- !     CALL dom_clean(dom_init_mpp)
-
- !     IF( ASSOCIATED(td_mpp%t_proc) )THEN
-
- !        CALL logger_error( " INIT: mpp strcuture "//TRIM(td_mpp%c_name)//&
- !        &               " not define" )
-
- !     ELSE
- !        ! global domain define by mpp
-
- !        ! use global dimension define by mpp
- !        dom_init_mpp%t_dim(:) = td_mpp%t_dim(:)
-
- !        ! get global domain periodicity ??
- !        dom_init_mpp%i_perio =  dom_get_perio(td_mpp, cd_varname)
-
- !        ! global domain pivot point
- !        SELECT CASE(dom_init%i_perio)
- !           CASE(3,4)
- !              dom_init%i_pivot = 0
- !           CASE(5,6)
- !              dom_init%i_pivot = 1
- !           CASE DEFAULT
- !              dom_init%i_pivot = 0
- !        END SELECT
-
- !        ! initialise domain as global
- !        dom_init_mpp%i_imin = 1 
- !        dom_init_mpp%i_imax = dom_init_mpp%t_dim(1)%i_len
-
- !        dom_init_mpp%i_jmin = 1 
- !        dom_init_mpp%i_jmax = dom_init_mpp%t_dim(2)%i_len
-
- !        dom_init_mpp%i_kmin = 1 
- !        dom_init_mpp%i_kmax = dom_init_mpp%t_dim(3)%i_len
-
- !        dom_init_mpp%i_lmin = 1 
- !        dom_init_mpp%i_lmax = dom_init_mpp%t_dim(4)%i_len
-
- !     ENDIF
-
- !  END FUNCTION dom_init_mpp
- !  !> @endcode
+         dom__init_file%i_imin = 1 
+         dom__init_file%i_imax = dom__init_file%t_dim0(1)%i_len
+
+         dom__init_file%i_jmin = 1 
+         dom__init_file%i_jmax = dom__init_file%t_dim0(2)%i_len
+
+         ! sub domain dimension
+         dom__init_file%t_dim(:) = dim_copy(td_file%t_dim(:))
+
+         ! define sub domain indices 
+         CALL dom__define( dom__init_file, &
+         &                 id_imin, id_imax, id_jmin, id_jmax )
+
+      ENDIF
+
+   END FUNCTION dom__init_file
    !-------------------------------------------------------------------
    !> @brief 
-   !> This subroutine define extract domain indices, and compute the size 
-   !> of the domain.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain structure
-   !> @param[in] id_imin : i-direction sub-domain lower left  point indice
-   !> @param[in] id_imax : i-direction sub-domain upper right point indice
-   !> @param[in] id_jmin : j-direction sub-domain lower left  point indice
-   !> @param[in] id_jmax : j-direction sub-domain upper right point indice
-   !> @param[in] id_kmin : k-direction sub-domain lower level indice
-   !> @param[in] id_kmax : k-direction sub-domain upper level indice
-   !> @param[in] id_lmin : l-direction sub-domain lower time indice
-   !> @param[in] id_lmax : l-direction sub-domain upper time indice
-   !-------------------------------------------------------------------
-   !> @code
+   !> This subroutine define sub domain indices, and compute the size 
+   !> of the sub domain.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain structure
+   !> @param[in] id_imin   i-direction sub-domain lower left  point indice
+   !> @param[in] id_imax   i-direction sub-domain upper right point indice
+   !> @param[in] id_jmin   j-direction sub-domain lower left  point indice
+   !> @param[in] id_jmax   j-direction sub-domain upper right point indice
+   !-------------------------------------------------------------------
    SUBROUTINE dom__define(td_dom, &
    &                      id_imin, id_imax, id_jmin, id_jmax )
-!   &                      id_kmin, id_kmax, id_lmin, id_lmax )
       IMPLICIT NONE
       ! Argument      
@@ -342,8 +565,4 @@
       INTEGER(i4), INTENT(IN), OPTIONAL :: id_jmin
       INTEGER(i4), INTENT(IN), OPTIONAL :: id_jmax
-!      INTEGER(i4), INTENT(IN), OPTIONAL :: id_kmin
-!      INTEGER(i4), INTENT(IN), OPTIONAL :: id_kmax
-!      INTEGER(i4), INTENT(IN), OPTIONAL :: id_lmin
-!      INTEGER(i4), INTENT(IN), OPTIONAL :: id_lmax
       !----------------------------------------------------------------
 
@@ -354,64 +573,62 @@
       IF( PRESENT(id_jmax) ) td_dom%i_jmax = id_jmax
 
-!      IF( PRESENT(id_kmin) ) td_dom%i_kmin = id_kmin
-!      IF( PRESENT(id_kmax) ) td_dom%i_kmax = id_kmax
-!
-!      IF( PRESENT(id_lmin) ) td_dom%i_lmin = id_lmin
-!      IF( PRESENT(id_lmax) ) td_dom%i_lmax = id_lmax
-
       ! check indices
-      IF(( td_dom%i_imin < 0 .OR. td_dom%i_imin > td_dom%t_dim0(1)%i_len ).OR. &
-      &  ( td_dom%i_imax < 0 .OR. td_dom%i_imax > td_dom%t_dim0(1)%i_len ).OR. &
-      &  ( td_dom%i_jmin < 0 .OR. td_dom%i_jmin > td_dom%t_dim0(2)%i_len ).OR. &
-      &  ( td_dom%i_jmax < 0 .OR. td_dom%i_jmax > td_dom%t_dim0(2)%i_len ))THEN
-!      &  ( td_dom%i_kmin < 0 .OR. td_dom%i_kmin > td_dom%t_dim0(3)%i_len ).OR. &
-!      &  ( td_dom%i_kmax < 0 .OR. td_dom%i_kmax > td_dom%t_dim0(3)%i_len ).OR. &
-!      &  ( td_dom%i_lmin < 0 .OR. td_dom%i_lmin > td_dom%t_dim0(4)%i_len ).OR. &
-!      &  ( td_dom%i_lmax < 0 .OR. td_dom%i_lmax > td_dom%t_dim0(4)%i_len ))THEN
-         CALL logger_error( "DOM INIT DEFINE: invalid grid definition."// &
+      IF(( td_dom%i_imin < -1 .OR. td_dom%i_imin > td_dom%t_dim0(1)%i_len ).OR. &
+      &  ( td_dom%i_imax < -1 .OR. td_dom%i_imax > td_dom%t_dim0(1)%i_len ).OR. &
+      &  ( td_dom%i_jmin < -1 .OR. td_dom%i_jmin > td_dom%t_dim0(2)%i_len ).OR. &
+      &  ( td_dom%i_jmax < -1 .OR. td_dom%i_jmax > td_dom%t_dim0(2)%i_len ))THEN
+         CALL logger_debug("0 <= imin ("//TRIM(fct_str(id_imin))//") < "//&
+         &              TRIM(fct_str(td_dom%t_dim0(1)%i_len)))
+         CALL logger_debug("0 <= imax ("//TRIM(fct_str(id_imax))//") < "//&
+         &              TRIM(fct_str(td_dom%t_dim0(1)%i_len)))
+         CALL logger_debug("0 <= jmin ("//TRIM(fct_str(id_jmin))//") < "//&
+         &              TRIM(fct_str(td_dom%t_dim0(2)%i_len)))
+         CALL logger_debug("0 <= jmax ("//TRIM(fct_str(id_jmax))//") < "//&
+         &              TRIM(fct_str(td_dom%t_dim0(2)%i_len)))
+         CALL logger_fatal( "DOM INIT DEFINE: invalid grid definition."// &
          &               " check min and max indices")
-         CALL logger_debug("0 < imin ("//TRIM(fct_str(id_imin))//") < "//&
-         &              TRIM(fct_str(td_dom%t_dim0(1)%i_len)))
-         CALL logger_debug("0 < imax ("//TRIM(fct_str(id_imax))//") < "//&
-         &              TRIM(fct_str(td_dom%t_dim0(1)%i_len)))
-         CALL logger_debug("0 < jmin ("//TRIM(fct_str(id_jmin))//") < "//&
-         &              TRIM(fct_str(td_dom%t_dim0(2)%i_len)))
-         CALL logger_debug("0 < jmax ("//TRIM(fct_str(id_jmax))//") < "//&
-         &              TRIM(fct_str(td_dom%t_dim0(2)%i_len)))
-!         CALL logger_debug("0 < kmin ("//TRIM(fct_str(id_kmin))//") < "//&
-!         &              TRIM(fct_str(td_dom%t_dim0(3)%i_len)))
-!         CALL logger_debug("0 < kmax ("//TRIM(fct_str(id_kmax))//") < "//&
-!         &              TRIM(fct_str(td_dom%t_dim0(3)%i_len)))
-!         CALL logger_debug("0 < lmin ("//TRIM(fct_str(id_lmin))//") < "//&
-!         &              TRIM(fct_str(td_dom%t_dim0(4)%i_len)))
-!         CALL logger_debug("0 < lmax ("//TRIM(fct_str(id_lmax))//") < "//&
-!         &              TRIM(fct_str(td_dom%t_dim0(4)%i_len)))
       ELSE
 
-!         td_dom%t_dim(3)%i_len=td_dom%i_kmax-td_dom%i_kmin+1
-!         td_dom%t_dim(4)%i_len=td_dom%i_lmax-td_dom%i_lmin+1
+         ! force to select north fold
+         IF( td_dom%i_perio0 > 2 .AND. &
+         &   ( td_dom%i_jmax >= td_dom%t_dim0(2)%i_len-1 .OR. &
+         &     td_dom%i_jmax < td_dom%i_jmin .OR. &
+         &     td_dom%i_jmin == 0 ) )THEN
+            td_dom%i_jmax=0
+         ENDIF
+
+         ! force to use cyclic boundary
+         IF( ( td_dom%i_perio0 == 1 .OR. &
+         &     td_dom%i_perio0 == 4 .OR. &
+         &     td_dom%i_perio0 == 6 ) .AND. &
+         &   ( td_dom%i_imin == 0 .OR. td_dom%i_imax == 0 .OR. &
+         &     ABS(td_dom%i_imax-td_dom%i_imin)+1 == td_dom%t_dim0(1)%i_len ) &
+         &  )THEN
+            td_dom%i_imin = 0
+            td_dom%i_imax = 0
+         ENDIF
 
          SELECT CASE(td_dom%i_perio0)
             CASE(0) ! closed boundary
-               CALL logger_trace("DEFINE: closed boundary")
+               CALL logger_trace("DOM INIT DEFINE: closed boundary")
                CALL dom__define_closed( td_dom )
             CASE(1) ! cyclic east-west boundary
-               CALL logger_trace("DEFINE: cyclic east-west boundary")
+               CALL logger_trace("DOM INIT DEFINE: cyclic east-west boundary")
                CALL dom__define_cyclic( td_dom )
             CASE(2) ! symmetric boundary condition across the equator
-               CALL logger_trace("DEFINE: symmetric boundary condition "//&
+               CALL logger_trace("DOM INIT DEFINE: symmetric boundary condition "//&
                &                 " across the equator")
                CALL dom__define_symmetric( td_dom )
             CASE(3) ! North fold boundary (with a F-point pivot)  
-               CALL logger_trace("DEFINE: North fold boundary "//&
+               CALL logger_trace("DOM INIT DEFINE: North fold boundary "//&
                &                 "(with a F-point pivot)")
                CALL dom__define_north_fold( td_dom )
             CASE(5) ! North fold boundary (with a T-point pivot)
-               CALL logger_trace("DEFINE: North fold boundary "//&
+               CALL logger_trace("DOM INIT DEFINE: North fold boundary "//&
                &                 "(with a T-point pivot)")
                CALL dom__define_north_fold( td_dom )
             CASE(4) ! North fold boundary (with a F-point pivot) 
                     ! and cyclic east-west boundary
-               CALL logger_trace("DEFINE:  North fold boundary "//&
+               CALL logger_trace("DOM INIT DEFINE:  North fold boundary "//&
                &                 "(with a F-point pivot) and cyclic "//&
                &                 "east-west boundary")
@@ -419,10 +636,10 @@
             CASE(6) ! North fold boundary (with a T-point pivot) 
                     ! and cyclic east-west boundary
-               CALL logger_trace("DEFINE: North fold boundary "//&
+               CALL logger_trace("DOM INIT DEFINE: North fold boundary "//&
                &                 "(with a T-point pivot) and cyclic "//&
                &                 "east-west boundary")
                CALL dom__define_cyclic_north_fold( td_dom )
             CASE DEFAULT
-               CALL logger_error("DEFINE: invalid grid periodicity index")
+               CALL logger_error("DOM INIT DEFINE: invalid grid periodicity index")
          END SELECT
 
@@ -430,16 +647,16 @@
 
    END SUBROUTINE dom__define
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !> This subroutine define domain indices from global domain with
+   !> This subroutine define sub domain indices from global domain with
    !> cyclic east-west boundary and north fold boundary condition.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !> @date September, 2014
+   !> - use zero indice to defined cyclic or global domain
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__define_cyclic_north_fold( td_dom )
       IMPLICIT NONE
@@ -448,10 +665,10 @@
       !----------------------------------------------------------------
 
-      CALL dom__check_EW_index( td_dom )
-
-      IF( td_dom%i_imin == td_dom%i_imax .AND. &
-      &   td_dom%i_jmin == td_dom%i_jmax )THEN
-
-         CALL logger_trace("DEFINE CYCLIC NORTH FOLD: "//&
+      !CALL dom__check_EW_index( td_dom )
+
+      IF( td_dom%i_imin == 0 .AND. td_dom%i_imax == 0 .AND. &
+      &   td_dom%i_jmin == 0 .AND. td_dom%i_jmax == 0 )THEN
+
+         CALL logger_trace("DOM DEFINE CYCLIC NORTH FOLD: "//&
          &  "domain to extract is global" )
          ! coarse domain is global domain
@@ -459,52 +676,38 @@
          CALL dom__size_global( td_dom )
 
-      ELSEIF( td_dom%i_imin == td_dom%i_imax .AND. &
-      &       td_dom%i_jmin >= td_dom%i_jmax )THEN
-
-         CALL logger_trace("DEFINE CYCLIC NORTH FOLD: "//&
+      ELSEIF( td_dom%i_imin == 0 .AND. td_dom%i_imax == 0 .AND. &
+      &       td_dom%i_jmax == 0 )THEN
+
+         CALL logger_trace("DOM DEFINE CYCLIC NORTH FOLD: "//&
          &  "domain to extract is semi-global" )
 
          CALL dom__size_semi_global( td_dom )
 
-      ELSEIF( td_dom%i_imin == td_dom%i_imax .AND. &
-      &       td_dom%i_jmin < td_dom%i_jmax )THEN
-
-         CALL logger_trace("DEFINE CYCLIC NORTH FOLD: "//&
+      ELSEIF( td_dom%i_imin == 0 .AND. td_dom%i_imax == 0 .AND. &
+      &       td_dom%i_jmax /= 0 )THEN
+
+         CALL logger_trace("DOM DEFINE CYCLIC NORTH FOLD: "//&
          &  "domain to extract is band of latidue" )
 
          CALL dom__size_no_pole( td_dom )
 
-      ELSEIF( td_dom%i_imin /= td_dom%i_imax .AND. &
-      &       td_dom%i_jmin == td_dom%i_jmax )THEN
-
-         CALL logger_trace("DEFINE CYCLIC NORTH FOLD: "//&
-         &  "domain to extract has north boundary" )
+      ELSEIF( td_dom%i_jmax == 0 )THEN
+
+         CALL logger_trace("DOM DEFINE CYCLIC NORTH FOLD: "//&
+         &  "domain to extract use north fold" )
 
          CALL dom__size_pole( td_dom )
 
-      ELSEIF( td_dom%i_imin /= td_dom%i_imax .AND. &
-      &       td_dom%i_jmin /= td_dom%i_jmax )THEN
-
-         IF( td_dom%i_jmax < td_dom%t_dim0(2)%i_len-1 .AND. &
-         &   td_dom%i_jmax > td_dom%i_jmin )THEN
-
-            CALL logger_trace("DEFINE CYCLIC NORTH FOLD: "//&
-            &  "domain to extract has no north boundary" )
-            ! no North Pole
-            
-            CALL dom__size_no_pole( td_dom )
-
-         ELSE
-
-            CALL logger_trace("DEFINE CYCLIC NORTH FOLD: "//&
-            &  "domain to extract has north boundary" )
-
-            CALL dom__size_pole( td_dom )
-
-         ENDIF
+      ELSEIF( td_dom%i_jmax /= 0 )THEN
+
+         CALL logger_trace("DOM DEFINE CYCLIC NORTH FOLD: "//&
+         &  "domain to extract do not use north fold" )
+         ! no North Pole
+         
+         CALL dom__size_no_pole( td_dom )
 
       ELSE
 
-         CALL logger_error("DEFINE CYCLIC NORTH FOLD: "//&
+         CALL logger_error("DOM DEFINE CYCLIC NORTH FOLD: "//&
          &  "should have been an impossible case" )
 
@@ -512,16 +715,14 @@
       
    END SUBROUTINE dom__define_cyclic_north_fold
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !> This subroutine define extract domain indices from global domain 
+   !> This subroutine define sub domain indices from global domain 
    !> with north fold boundary condition.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__define_north_fold( td_dom )
       IMPLICIT NONE
@@ -530,8 +731,7 @@
       !----------------------------------------------------------------
 
-      IF( td_dom%i_jmax < td_dom%t_dim0(2)%i_len-1 .AND. &
-      &   td_dom%i_jmax > td_dom%i_jmin )THEN
-
-         CALL logger_trace("DEFINE NORTH FOLD: "//&
+      IF( td_dom%i_jmax /= 0 )THEN
+
+         CALL logger_trace("DOM DEFINE NORTH FOLD: "//&
          &  "domain to extract has no north boundary" )
          ! no North Pole
@@ -541,6 +741,6 @@
       ELSE
 
-         CALL logger_trace("DEFINE NORTH FOLD: "//&
-         &  "domain to extract has north boundary" )
+         CALL logger_trace("DOM DEFINE NORTH FOLD: "//&
+         &  "sub domain has north boundary" )
 
          CALL dom__size_pole_no_overlap( td_dom )
@@ -549,16 +749,14 @@
 
    END SUBROUTINE dom__define_north_fold
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !> This subroutine define extract domain indices from global domain 
+   !> This subroutine define sub domain indices from global domain 
    !> with symmetric boundary condition across the equator.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__define_symmetric( td_dom )
       IMPLICIT NONE
@@ -570,16 +768,14 @@
 
    END SUBROUTINE dom__define_symmetric
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !> This subroutine define extract domain indices from global domain
+   !> This subroutine define sub domain indices from global domain
    !> with cyclic east-west boundary.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__define_cyclic( td_dom )
       IMPLICIT NONE
@@ -587,8 +783,7 @@
       TYPE(TDOM), INTENT(INOUT) :: td_dom
       !----------------------------------------------------------------
-      CALL dom__check_EW_index( td_dom )
       
       IF( td_dom%i_imin >= td_dom%i_imax )THEN
-         CALL logger_trace("DEFINE CYCLIC: "//&
+         CALL logger_trace("DOM DEFINE CYCLIC: "//&
          &  "domain to extract overlap east-west boundary")
 
@@ -597,5 +792,5 @@
       ELSE
          ! id_imin < id_imax
-         CALL logger_trace("DEFINE CYCLIC: "//&
+         CALL logger_trace("DOM DEFINE CYCLIC: "//&
          &  "domain to extract do not overlap east-west boundary")
 
@@ -605,16 +800,14 @@
 
    END SUBROUTINE dom__define_cyclic
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !> This subroutine define extract domain indices from global domain
+   !> This subroutine define sub domain indices from global domain
    !> with closed boundaries.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__define_closed( td_dom )
       IMPLICIT NONE
@@ -626,35 +819,4 @@
 
    END SUBROUTINE dom__define_closed
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief 
-   !> This subroutine check East-West indices, use inside a cyclic domain,
-   !> and redefine it in some particular cases.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE dom__check_EW_index( td_dom )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TDOM), INTENT(INOUT) :: td_dom
-      !----------------------------------------------------------------
-
-      IF( td_dom%i_imin /= td_dom%i_imax )THEN
-
-         IF((ABS(td_dom%i_imax-td_dom%i_imin) >= td_dom%t_dim0(1)%i_len-1).OR.&
-            (ABS(td_dom%i_imax-td_dom%i_imin) <= td_dom%i_ew0 ) )THEN
-
-            td_dom%i_imin = td_dom%i_imax
-
-         ENDIF
-
-      ENDIF
-
-   END SUBROUTINE dom__check_EW_index
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -662,9 +824,8 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__size_global( td_dom )
       IMPLICIT NONE
@@ -684,8 +845,7 @@
 
       ! no ghost cell to add
-      td_dom%i_ighost=0
-      td_dom%i_jghost=0
-
-      ! peiordicity
+      td_dom%i_ghost(:,:)=0
+
+      ! periodicity
       IF( td_dom%i_pivot == 0 )THEN ! 0-F
          td_dom%i_perio=4
@@ -697,5 +857,4 @@
 
    END SUBROUTINE dom__size_global
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -703,10 +862,9 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
    !> @note never tested
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE dom__size_semi_global( td_dom )
       IMPLICIT NONE
@@ -715,5 +873,5 @@
 
       ! local variable
-      INTEGER(i4) :: il_imid   ! cananadian bipole index (middle of global domain) 
+      INTEGER(i4) :: il_imid   ! canadian bipole index (middle of global domain) 
       !----------------------------------------------------------------
 
@@ -723,23 +881,18 @@
       td_dom%i_imax = il_imid !td_dom%t_dim0(1)%i_len
 
-      IF( td_dom%i_jmax >= td_dom%t_dim0(2)%i_len-1 )THEN
-         td_dom%i_jmax=MIN( td_dom%i_jmin, & 
-         &                  td_dom%t_dim0(2)%i_len-td_dom%i_jmax )
-      ELSE
-         td_dom%i_jmin=td_dom%i_jmax
-      ENDIF
+      IF( td_dom%i_jmin == 0 ) td_dom%i_jmin=1
+      td_dom%i_jmax = td_dom%t_dim0(2)%i_len
 
       ! domain size
-      td_dom%t_dim(1)%i_len = (td_dom%i_imax ) - &
-      &                         (td_dom%i_imin ) + 1
+      td_dom%t_dim(1)%i_len = td_dom%i_imax - &
+      &                       td_dom%i_imin + 1
 
       td_dom%t_dim(2)%i_len = ( td_dom%t_dim0(2)%i_len - &
-      &                         ( td_dom%i_jmin ) + 1 ) +      &
+      &                         td_dom%i_jmin + 1 ) +      &
       &                         ( td_dom%t_dim0(2)%i_len - &
-      &                         ( td_dom%i_jmax ) + 1 ) - 2    ! remove north fold condition ?
+      &                           td_dom%i_jmin + 1 ) - 2    ! remove north fold condition ?
 
       ! ghost cell to add
-      td_dom%i_ighost=1
-      td_dom%i_jghost=1
+      td_dom%i_ghost(:,:)=1
 
       ! periodicity
@@ -753,16 +906,14 @@
 
    END SUBROUTINE dom__size_semi_global
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine compute size of an extract domain without north fold
+   !> This subroutine compute size of sub domain without north fold
    !> condition
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__size_no_pole( td_dom )
       IMPLICIT NONE
@@ -771,12 +922,13 @@
       !----------------------------------------------------------------
 
-      IF( td_dom%i_jmin >= td_dom%i_jmax )THEN
-         CALL logger_fatal("DOM INIT: invalid domain. "//&
+      IF( td_dom%i_jmax == 0 )THEN
+         CALL logger_fatal("DOM SIZE NO POLE: invalid domain. "//&
          &  "can not get north pole from this coarse grid. "//&
          &  "check namelist and coarse grid periodicity." )
       ENDIF
 
-      IF( td_dom%i_imin >= td_dom%i_imax )THEN
-         CALL logger_trace("DEFINE NO POLE: "// &
+      IF( td_dom%i_imin == 0 .AND. td_dom%i_imax == 0 .OR. &
+      &   td_dom%i_imin > td_dom%i_imax )THEN
+         CALL logger_trace("DOM SIZE NO POLE: "// &
          &  "domain to extract overlap east-west boundary")
 
@@ -785,5 +937,5 @@
       ELSE
          ! id_imin < id_imax
-         CALL logger_trace("DEFINE NO POLE: "// &
+         CALL logger_trace("DOM SIZE NO POLE: "// &
          &  "domain to extract do not overlap east-west boundary")
 
@@ -793,16 +945,15 @@
 
    END SUBROUTINE dom__size_no_pole
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine compute size of an extract domain with north fold
-   !> condition
+   !> This subroutine compute size of sub domain with north fold
+   !> condition.
    !>
    !> @author J.Paul
    !> - April, 2013- Subroutine written
    !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[inout] td_dom domain strcuture
+   !> @note never tested
+   !-------------------------------------------------------------------
    SUBROUTINE dom__size_pole( td_dom )
       IMPLICIT NONE
@@ -811,10 +962,10 @@
       !----------------------------------------------------------------
 
-      IF( td_dom%i_imin > td_dom%i_imax )THEN
-         CALL logger_trace("DEFINE POLE: "//&
+      IF( td_dom%i_imin >= td_dom%i_imax )THEN
+         CALL logger_trace("DOM SIZE POLE: "//&
          &  "domain to extract overlap east-west boundary")
          CALL dom__size_pole_overlap( td_dom )
       ELSEIF( td_dom%i_imin < td_dom%i_imax )THEN
-         CALL logger_trace("DEFINE POLE: "//&
+         CALL logger_trace("DOM SIZE POLE: "//&
          &  "domain to extract do not overlap east-west boundary")
          CALL dom__size_pole_no_overlap( td_dom )
@@ -822,16 +973,14 @@
 
    END SUBROUTINE dom__size_pole
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine compute size of an extract domain without north fold
+   !> This subroutine compute size of sub domain without north fold
    !> condition, and which overlap east-west boundary
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__size_no_pole_overlap( td_dom )
       IMPLICIT NONE
@@ -840,13 +989,13 @@
       !----------------------------------------------------------------
 
-      IF( td_dom%i_jmin >= td_dom%i_jmax )THEN
-         CALL logger_fatal("DOM INIT: invalid domain. "//&
+      IF( td_dom%i_jmax == 0 )THEN
+         CALL logger_fatal("DOM SIZE NO POLE OVERLAP: invalid domain. "//&
          &  "can not get north pole from this coarse grid. "//&
          &  "check namelist and coarse grid periodicity." )
       ENDIF
 
-      IF( td_dom%i_imin == td_dom%i_imax )THEN
+      IF( td_dom%i_imin == 0 .AND. td_dom%i_imax == 0 )THEN
          ! domain to extract with east west cyclic boundary
-         CALL logger_trace("DEFINE NO POLE OVERLAP: "//&
+         CALL logger_trace("DOM SIZE NO POLE OVERLAP: "//&
          &  "domain to extract has cyclic east-west boundary")
 
@@ -857,5 +1006,5 @@
 
          ! no ghost cell
-         td_dom%i_ighost=0
+         td_dom%i_ghost(jp_I,:)=0
 
          ! periodicity
@@ -867,10 +1016,10 @@
          ! extract domain overlap east-west boundary
 
-         td_dom%t_dim(1)%i_len = td_dom%t_dim0(1)%i_len -             &
-         &                       (td_dom%i_imin ) + 1 + & 
-         &                       (td_dom%i_imax ) - 2     ! remove cyclic boundary
+         td_dom%t_dim(1)%i_len = td_dom%i_imax + &
+         &                       td_dom%t_dim0(1)%i_len - td_dom%i_imin + 1 - & 
+         &                       td_dom%i_ew0     ! remove cyclic boundary
 
          ! add ghost cell
-         td_dom%i_ighost=1
+         td_dom%i_ghost(jp_I,:)=1
 
          ! periodicity
@@ -879,23 +1028,21 @@
       ENDIF
 
-      td_dom%t_dim(2)%i_len = (td_dom%i_jmax ) - &
-      &                       (td_dom%i_jmin ) + 1
+      td_dom%t_dim(2)%i_len = td_dom%i_jmax - &
+      &                       td_dom%i_jmin + 1
 
       ! add ghost cell
-      td_dom%i_jghost=1
+      td_dom%i_ghost(jp_J,:)=1
 
    END SUBROUTINE dom__size_no_pole_overlap
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine compute size of an extract domain without north fold
+   !> This subroutine compute size of sub domain without north fold
    !> condition, and which do not overlap east-west boundary
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom__size_no_pole_no_overlap( td_dom )
       IMPLICIT NONE
@@ -904,25 +1051,24 @@
       !----------------------------------------------------------------
 
-      IF( td_dom%i_jmin >= td_dom%i_jmax )THEN
-         CALL logger_fatal("DOM INIT: invalid domain. "//&
+      IF( td_dom%i_jmax == 0 )THEN
+         CALL logger_fatal("DOM SIZE NO POLE NO OVERLAP: invalid domain. "//&
          &  "can not get north pole from this coarse grid. "//&
-         &  "check namelist and coarse grid periodicity." )
-      ENDIF
-
-      IF( td_dom%i_imin >= td_dom%i_imax )THEN
-         CALL logger_fatal("DOM INIT: invalid domain. "//&
+         &  "check domain indices and grid periodicity." )
+      ENDIF
+
+      IF( td_dom%i_imin == 0 .OR. td_dom%i_imax == 0 )THEN
+         CALL logger_fatal("DOM SIZE NO POLE NO OVERLAP: invalid domain. "//&
          &  "can not overlap East-West boundary with this coarse grid. "//&
-         &  "check namelist and coarse grid periodicity." )
-      ENDIF
-
-      td_dom%t_dim(1)%i_len = ( td_dom%i_imax ) - & 
-      &                       ( td_dom%i_imin ) + 1 
-
-      td_dom%t_dim(2)%i_len = ( td_dom%i_jmax ) - &
-      &                       ( td_dom%i_jmin ) + 1
+         &  "check domain indices and grid periodicity." )
+      ENDIF
+
+      td_dom%t_dim(1)%i_len = td_dom%i_imax - & 
+      &                       td_dom%i_imin + 1 
+
+      td_dom%t_dim(2)%i_len = td_dom%i_jmax - &
+      &                       td_dom%i_jmin + 1
       
       ! add ghost cell
-      td_dom%i_ighost=1
-      td_dom%i_jghost=1
+      td_dom%i_ghost(:,:)=1
 
       ! periodicity
@@ -930,17 +1076,15 @@
 
    END SUBROUTINE dom__size_no_pole_no_overlap
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine compute size of an extract domain with north fold
+   !> This subroutine compute size of sub domain with north fold
    !> condition, and which overlap east-west boundary
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
    !> @note never tested
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE dom__size_pole_overlap( td_dom )
       IMPLICIT NONE
@@ -954,5 +1098,5 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace("DEFINE POLE OVERLAP: "//&
+      CALL logger_trace("DOM SIZE POLE OVERLAP: "//&
       &  "asian bipole inside domain to extract")
 
@@ -964,9 +1108,10 @@
       IF( il_idom1 > il_imid .OR. il_idom2 > il_imid )THEN
 
-         CALL logger_trace("DEFINE POLE OVERLAP: "//&
+         CALL logger_trace("DOM SIZE POLE OVERLAP: "//&
          &  "canadian bipole inside domain to extract")
-         td_dom%i_imin = td_dom%i_imax
-
-         IF( td_dom%i_jmin == td_dom%i_jmax )THEN
+         td_dom%i_imin = 0
+         td_dom%i_imax = 0
+
+         IF( td_dom%i_jmin == 0 .AND. td_dom%i_jmax == 0 )THEN
             CALL dom__size_global( td_dom )
          ELSE
@@ -980,27 +1125,21 @@
 
          ! east part bigger than west part
-         CALL logger_trace("DEFINE POLE OVERLAP: east part bigger than west part ")
+         CALL logger_trace("DOM SIZE POLE OVERLAP: east part bigger than west part ")
          ! to respect symmetry around asian bipole
          td_dom%i_imax = il_idom1
 
+         IF( td_dom%i_jmin == 0 ) td_dom%i_jmin = 1 
          ! north pole
-         IF( td_dom%i_jmax >= td_dom%t_dim0(2)%i_len-1 )THEN
-            td_dom%i_jmax=MIN( td_dom%i_jmin, & 
-            &                  td_dom%t_dim0(2)%i_len-td_dom%i_jmax )
-         ELSE
-            td_dom%i_jmax=MIN( td_dom%i_jmin, td_dom%i_jmax )
-         ENDIF
-         td_dom%i_jmin=td_dom%i_jmax
+         td_dom%i_jmax = td_dom%t_dim0(2)%i_len
 
          ! compute size
          td_dom%t_dim(1)%i_len = il_idom1  !! no ghost cell ??
          td_dom%t_dim(2)%i_len = ( td_dom%t_dim0(2)%i_len - &
-         &                         ( td_dom%i_jmin ) + 1 ) + &   
+         &                         td_dom%i_jmin + 1 ) + &   
          &                         ( td_dom%t_dim0(2)%i_len - &
-         &                         ( td_dom%i_jmax ) + 1 ) - 2   ! remove north fold condition ?
+         &                         td_dom%i_jmin + 1 ) - 2   ! remove north fold condition ?
 
          ! add ghost cell
-         td_dom%i_ighost=1
-         td_dom%i_jghost=1
+         td_dom%i_ghost(:,:)=1
 
          ! periodicity
@@ -1010,28 +1149,22 @@
 
          ! west part bigger than east part
-         CALL logger_trace("DEFINE POLE OVERLAP: west part bigger than east part ")
+         CALL logger_trace("DOM SIZE POLE OVERLAP: west part bigger than east part ")
 
          ! to respect symmetry around asian bipole
          td_dom%i_imin = td_dom%t_dim0(1)%i_len - il_idom2 + 1
 
+         IF( td_dom%i_jmin == 0 ) td_dom%i_jmin = 1 
          ! north pole
-         IF( td_dom%i_jmax >= td_dom%t_dim0(2)%i_len-1 )THEN
-            td_dom%i_jmax=MIN( td_dom%i_jmin, & 
-            &                  td_dom%t_dim0(2)%i_len-td_dom%i_jmax )
-         ELSE
-            td_dom%i_jmax=MIN( td_dom%i_jmin, td_dom%i_jmax )
-         ENDIF
-         td_dom%i_jmin=td_dom%i_jmax
+         td_dom%i_jmax=td_dom%t_dim0(2)%i_len
 
          ! compute size
          td_dom%t_dim(1)%i_len = il_idom2
          td_dom%t_dim(2)%i_len = ( td_dom%t_dim0(2)%i_len - &
-         &                         ( td_dom%i_jmin ) + 1 ) + &
+         &                         td_dom%i_jmin + 1 ) + &
          &                         ( td_dom%t_dim0(2)%i_len - &
-         &                         ( td_dom%i_jmax ) + 1 ) - 2
+         &                         td_dom%i_jmin + 1 ) - 2
 
          ! add ghost cell
-         td_dom%i_ighost=1
-         td_dom%i_jghost=1
+         td_dom%i_ghost(:,:)=1
          
          ! periodicity
@@ -1041,17 +1174,15 @@
 
    END SUBROUTINE dom__size_pole_overlap
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine compute size of an extract domain with north fold
+   !> This subroutine compute size of sub domain with north fold
    !> condition, and which do not overlap east-west boundary
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @param[inout] td_dom : domain strcuture
+   !> - November, 2013- Subroutine written
+   !
+   !> @param[inout] td_dom domain strcuture
    !> @note never tested
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE dom__size_pole_no_overlap( td_dom )
       IMPLICIT NONE
@@ -1065,21 +1196,16 @@
       !----------------------------------------------------------------
 
-      IF( td_dom%i_imin >= td_dom%i_imax )THEN
-         CALL logger_fatal("DOM INIT: invalid domain. "//&
+      IF( td_dom%i_imin == 0 .OR. td_dom%i_imax == 0 .OR. &
+      &   td_dom%i_imin > td_dom%i_imax )THEN
+         CALL logger_fatal("DOM SIZE POLE NO OVERLAP: invalid domain. "//&
          &  "can not overlap East-West boundary with this coarse grid. "//&
          &  "check namelist and coarse grid periodicity." )
       ENDIF
 
-      CALL logger_trace("DEFINE POLE NO OVERLAP: "//&
+      CALL logger_trace("DOM SIZE POLE NO OVERLAP: "//&
       &  "no asian bipole inside domain to extract")
 
-      ! north pole
-      IF( td_dom%i_jmax >= td_dom%t_dim0(2)%i_len-1 )THEN
-         td_dom%i_jmax=MIN( td_dom%i_jmin, & 
-         &                  td_dom%t_dim0(2)%i_len-td_dom%i_jmax )
-      ELSE
-         td_dom%i_jmax=MIN( td_dom%i_jmin, td_dom%i_jmax )
-      ENDIF
-      td_dom%i_jmin=td_dom%i_jmax
+      IF( td_dom%i_jmin==0 ) td_dom%i_jmin = 1
+      IF( td_dom%i_jmax==0 ) td_dom%i_jmax = td_dom%t_dim0(2)%i_len
 
       ! 
@@ -1088,18 +1214,17 @@
       IF( (td_dom%i_imin < il_mid .AND. td_dom%i_imax < il_mid) .OR. &
       &   (td_dom%i_imin > il_mid .AND. td_dom%i_imax > il_mid) )THEN
-         CALL logger_trace("DEFINE POLE NO OVERLAP: "//&
+         CALL logger_trace("DOM SIZE POLE NO OVERLAP: "//&
          &  "no canadian bipole inside domain to extract")
 
-         td_dom%t_dim(1)%i_len = ( td_dom%i_imax ) - &
-         &                       ( td_dom%i_imin ) + 1
+         td_dom%t_dim(1)%i_len = td_dom%i_imax - &
+         &                       td_dom%i_imin + 1
 
          td_dom%t_dim(2)%i_len = ( td_dom%t_dim0(2)%i_len - &
-         &                       ( td_dom%i_jmin ) + 1 ) + &
+         &                       td_dom%i_jmin + 1 ) + &
          &                       ( td_dom%t_dim0(2)%i_len - &
-         &                       ( td_dom%i_jmax ) + 1 ) - 2 ! remove north fold condition ?
+         &                       td_dom%i_jmin + 1 ) - 2 ! remove north fold condition ?
 
          ! add ghost cell
-         td_dom%i_ighost=1
-         td_dom%i_jghost=1
+         td_dom%i_ghost(:,:)=1
 
          ! periodicity
@@ -1107,5 +1232,5 @@
 
       ELSE ! id_imin < il_mid .AND. id_imax > il_mid
-         CALL logger_trace("DEFINE POLE NO OVERLAP: "//&
+         CALL logger_trace("DOM SIZE POLE NO OVERLAP: "//&
          &  "canadian bipole inside domain to extract")
 
@@ -1114,5 +1239,5 @@
          IF( il_idom1 > il_idom2 )THEN
             ! east part bigger than west part
-            CALL logger_trace("DEFINE POLE NO OVERLAP: east part bigger than west part ")
+            CALL logger_trace("DOM SIZE POLE NO OVERLAP: east part bigger than west part ")
             ! to respect symmetry around canadian bipole
             td_dom%i_imin = il_mid - il_idom1
@@ -1120,12 +1245,11 @@
             td_dom%t_dim(1)%i_len = il_idom1 + 1
             td_dom%t_dim(2)%i_len = ( td_dom%t_dim0(2)%i_len - &
-            &                         ( td_dom%i_jmin ) + 1 ) + & 
+            &                         td_dom%i_jmin + 1 ) + & 
             &                         ( td_dom%t_dim0(2)%i_len - &
-            &                         ( td_dom%i_jmax ) + 1 ) &   
+            &                         td_dom%i_jmin + 1 ) &   
             &                         - 2 - 2 * td_dom%i_pivot    ! remove north fold condition ?
 
             ! add ghost cell
-            td_dom%i_ighost=1
-            td_dom%i_jghost=1
+            td_dom%i_ghost(:,:)=1
 
             ! periodicity
@@ -1134,5 +1258,5 @@
          ELSE ! il_idom2 >= il_idom1
             ! west part bigger than east part
-            CALL logger_trace("DEFINE POLE NO OVERLAP: west part bigger than east part ")
+            CALL logger_trace("DOM SIZE POLE NO OVERLAP: west part bigger than east part ")
             ! to respect symmetry around canadian bipole
 
@@ -1141,12 +1265,11 @@
             td_dom%t_dim(1)%i_len = il_idom2 + 1
             td_dom%t_dim(2)%i_len = ( td_dom%t_dim0(2)%i_len -  &
-            &                         ( td_dom%i_jmin ) + 1 ) +     & 
+            &                         td_dom%i_jmin + 1 ) +     & 
             &                         ( td_dom%t_dim0(2)%i_len -  &
-            &                         ( td_dom%i_jmax ) + 1 )       & 
+            &                         td_dom%i_jmax + 1 )       & 
             &                         - 2 - 2 * td_dom%i_pivot  !  remove north fold condition ?
 
             ! add ghost cell
-            td_dom%i_ighost=1
-            td_dom%i_jghost=1
+            td_dom%i_ghost(:,:)=1
 
             ! periodicity
@@ -1157,121 +1280,24 @@
 
    END SUBROUTINE dom__size_pole_no_overlap
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function get east west overlap.
-   !
+   !-------------------------------------------------------------------
+   !> @brief 
+   !>  This subroutine add extra bands to coarse domain to get enough point for
+   !>  interpolation...
+   !>
    !> @details
-   !> If no east -west wrap return -1, 
-   !> else return the size of the ovarlap band 
-   !
-   !> @author J.Paul
-   !> - 2013- Initial Version
-   !
-   !> @param[in] 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION dom_get_ew_overlap(td_lon)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TVAR), INTENT(IN) :: td_lon
-
-      ! function
-      INTEGER(i4) :: dom_get_ew_overlap
-
-      ! local variable
-      REAL(dp), DIMENSION(:,:,:,:), ALLOCATABLE :: dl_value
-      REAL(dp), DIMENSION(:)      , ALLOCATABLE :: dl_lone
-      REAL(dp), DIMENSION(:)      , ALLOCATABLE :: dl_lonw
-
-      REAL(dp)    :: dl_delta
-      REAL(dp)    :: dl_lonmax
-      REAL(dp)    :: dl_lonmin
-
-      INTEGER(i4) :: il_east
-      INTEGER(i4) :: il_west
-      INTEGER(i4) :: il_jmin
-      INTEGER(i4) :: il_jmax
-
-      INTEGER(i4), PARAMETER :: ip_max_overlap = 5
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-      ! init 
-      dom_get_ew_overlap=-1
-
-      il_west=1
-      il_east=td_lon%t_dim(1)%i_len
-
-      ALLOCATE( dl_value(td_lon%t_dim(1)%i_len, &
-      &                  td_lon%t_dim(2)%i_len, &
-      &                  td_lon%t_dim(3)%i_len, &
-      &                  td_lon%t_dim(4)%i_len) )
-
-      dl_value(:,:,:,:)=td_lon%d_value(:,:,:,:)
-      WHERE( dl_value(:,:,:,:) > 180._dp .AND. &
-      &      dl_value(:,:,:,:) /= td_lon%d_fill ) 
-         dl_value(:,:,:,:)=360.-dl_value(:,:,:,:)
-      END WHERE
-
-      ! we do not use jmax as dimension length due to north fold boundary
-      il_jmin=1+ig_ghost
-      il_jmax=(td_lon%t_dim(2)%i_len-ig_ghost)/2
-
-      ALLOCATE( dl_lone(il_jmax-il_jmin+1) )
-      ALLOCATE( dl_lonw(il_jmax-il_jmin+1) )
-
-      dl_lone(:)=dl_value(il_east,il_jmin:il_jmax,1,1)
-      dl_lonw(:)=dl_value(il_west,il_jmin:il_jmax,1,1)
-
-      IF( .NOT.(  ALL(dl_lone(:)==td_lon%d_fill) .AND. &
-      &           ALL(dl_lonw(:)==td_lon%d_fill) ) )THEN
-
-         dl_lonmax=MAXVAL(dl_value(:,il_jmin:il_jmax,:,:))
-         dl_lonmin=MINVAL(dl_value(:,il_jmin:il_jmax,:,:))
-
-         dl_delta=(dl_lonmax-dl_lonmin)/td_lon%t_dim(1)%i_len
-
-         IF( ALL(ABS(dl_lone(:)) - ABS(dl_lonw(:)) == dl_delta) )THEN
-
-            dom_get_ew_overlap=0
-
-         ELSE IF( ALL( ABS(dl_lone(:)) - ABS(dl_lonw(:)) < &
-         &             ip_max_overlap*dl_delta             ) )THEN
-            DO ji=0,ip_max_overlap
-
-               IF( il_east-ji == il_west )THEN
-                  ! case of small domain
-                  EXIT
-               ELSE
-                  dl_lone(:)=dl_value(il_east-ji,il_jmin:il_jmax,1,1)
-                  
-                  IF( ALL( dl_lonw(:) == dl_lone(:) ) )THEN
-                     dom_get_ew_overlap=ji+1
-                     EXIT
-                  ENDIF
-               ENDIF
-
-            ENDDO
-         ENDIF
-
-      ENDIF
-
-      DEALLOCATE( dl_value )
-
-   END FUNCTION dom_get_ew_overlap
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief 
-   !>  This subroutine add extra point to domain
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !> @param [in] id_iext : i-direction size of extra bands (default=im_minext)
-   !> @param [in] id_jext : j-direction size of extra bands (default=im_minext)
-   !-------------------------------------------------------------------
-   !> @code
+   !>  - domain periodicity is take into account.<br/>
+   !>  - domain indices are changed, and size of extra bands are saved.<br/>
+   !>  - optionaly, i- and j- direction size of extra bands could be specify 
+   !> (default=im_minext)
+   !>
+   !> @author J.Paul
+   !> @date November, 2013
+   !> @date September, 2014
+   !> - take into account number of ghost cell
+   !
+   !> @param[inout] td_dom domain strcuture
+   !> @param [in] id_iext  i-direction size of extra bands (default=im_minext)
+   !> @param [in] id_jext  j-direction size of extra bands (default=im_minext)
+   !-------------------------------------------------------------------
    SUBROUTINE dom_add_extra( td_dom, id_iext, id_jext )
       IMPLICIT NONE
@@ -1288,5 +1314,4 @@
       !----------------------------------------------------------------
       ! init
-      !WARNING: two extrabands are required for cubic interpolation
       il_iext=im_minext
       IF( PRESENT(id_iext) ) il_iext=id_iext
@@ -1305,4 +1330,5 @@
          ! nothing to be done
       ELSE
+
          IF( td_dom%i_imin == 1                       .AND. &
          &   td_dom%i_imax == td_dom%t_dim0(1)%i_len )THEN
@@ -1310,71 +1336,105 @@
             ! nothing to be done
          ELSE
-            IF( td_dom%i_imin /= 1 )THEN
-               td_dom%i_iextra(1)=il_iext
-
-            ELSE
-               IF( td_dom%i_ew0 > 0 )THEN
-                  td_dom%i_iextra(1)=il_iext
-
+            IF( td_dom%i_ew0 < 0 )THEN
+               ! EW not cyclic
+               IF( td_dom%i_imin - il_iext > td_dom%i_ghost0(jp_I,1)*ip_ghost )THEN
+                  td_dom%i_iextra(1) = il_iext
+                  td_dom%i_imin      = td_dom%i_imin - td_dom%i_iextra(1)
+               ELSE ! td_dom%i_imin - il_iext <= td_dom%i_ghost0(jp_I,1)*ip_ghost
+                  td_dom%i_iextra(1) = MIN(0, &
+                  &                         td_dom%i_imin - &
+                  &                         td_dom%i_ghost0(jp_I,1)*ip_ghost -1)
+                  td_dom%i_imin      = td_dom%i_imin - td_dom%i_iextra(1)
                ENDIF
+
+               IF( td_dom%i_imax + il_iext < &
+               &   td_dom%t_dim0(1)%i_len - td_dom%i_ghost0(jp_I,2)*ip_ghost )THEN
+                  td_dom%i_iextra(2) = il_iext
+                  td_dom%i_imax      = td_dom%i_imax + td_dom%i_iextra(2)
+               ELSE ! td_dom%i_imax + il_iext >= &
+                    !  td_dom%t_dim0(1)%i_len - td_dom%i_ghost0(jp_I,2)*ip_ghost
+                  td_dom%i_iextra(2) = MIN(0, &
+                  &                         td_dom%t_dim0(1)%i_len - &
+                  &                         td_dom%i_ghost0(jp_I,2)*ip_ghost - &
+                  &                         td_dom%i_imax )
+                  td_dom%i_imax      = td_dom%i_imax + td_dom%i_iextra(2)
+               ENDIF
+
+            ELSE ! td_dom%i_ew0 >= 0
+               ! EW cyclic
+               IF( td_dom%i_imin - il_iext > 0 )THEN
+                  td_dom%i_iextra(1) = il_iext
+                  td_dom%i_imin      = td_dom%i_imin - td_dom%i_iextra(1)
+               ELSE ! td_dom%i_imin - il_iext <= 0
+                  td_dom%i_iextra(1) = il_iext
+                  td_dom%i_imin      = td_dom%t_dim0(1)%i_len + &
+                  &                     td_dom%i_imin - td_dom%i_iextra(1) -&
+                  &                     td_dom%i_ew0
+               ENDIF
+
+               IF( td_dom%i_imax + il_iext <= td_dom%t_dim0(1)%i_len )THEN
+                  td_dom%i_iextra(2) = il_iext
+                  td_dom%i_imax      = td_dom%i_imax + td_dom%i_iextra(2)
+               ELSE ! td_dom%i_imax + il_iext > td_dom%t_dim0(1)%i_len
+                  td_dom%i_iextra(2) = il_iext
+                  td_dom%i_imax      = td_dom%i_imax + td_dom%i_iextra(2) - &
+                  &                     (td_dom%t_dim0(1)%i_len-td_dom%i_ew0) 
+               ENDIF               
             ENDIF
 
-            IF( td_dom%i_imax /= td_dom%t_dim(1)%i_len )THEN
-               td_dom%i_iextra(2)=1
-
-            ELSE
-               IF( td_dom%i_ew0 > 0 )THEN
-                  td_dom%i_iextra(2)=il_jext
-
-               ENDIF
+         ENDIF
+
+         IF( td_dom%i_jmin == 1                       .AND. &
+         &   td_dom%i_jmax == td_dom%t_dim0(2)%i_len )THEN
+            ! nothing to be done
+         ELSE
+            IF( td_dom%i_jmin - il_jext > td_dom%i_ghost0(jp_J,1)*ip_ghost )THEN
+               td_dom%i_jextra(1) = il_jext
+               td_dom%i_jmin      = td_dom%i_jmin - td_dom%i_jextra(1)
+            ELSE ! td_dom%i_jmin - il_jext <= td_dom%i_ghost0(jp_J,1)*ip_ghost
+               td_dom%i_jextra(1) = MIN(0, &
+               &                         td_dom%i_jmin - &
+               &                         td_dom%i_ghost0(jp_J,1)*ip_ghost - 1)
+               td_dom%i_jmin      = td_dom%i_jmin - td_dom%i_jextra(1)
             ENDIF
 
-         ENDIF
-
-         IF( td_dom%i_jmin == td_dom%i_jmax )THEN
-            td_dom%i_jextra(1)=il_iext
-            td_dom%i_jextra(2)=il_jext
-
-         ELSE
-            IF( td_dom%i_jmin /= 1)THEN
-               td_dom%i_jextra(1)=il_iext
-
+            IF( td_dom%i_jmax + il_jext < &
+            &   td_dom%t_dim0(2)%i_len - td_dom%i_ghost0(jp_J,2)*ip_ghost )THEN
+               td_dom%i_jextra(2) = il_jext
+               td_dom%i_jmax      = td_dom%i_jmax + td_dom%i_jextra(2)
+            ELSE ! td_dom%i_jmax + il_jext >= &
+                 !  td_dom%t_dim0(2)%i_len - td_dom%i_ghost0(jp_J,2)*ip_ghost
+               td_dom%i_jextra(2) = MIN(0, &
+               &                         td_dom%t_dim0(2)%i_len - &
+               &                         td_dom%i_ghost0(jp_J,2)*ip_ghost - &
+               &                         td_dom%i_jmax )
+               td_dom%i_jmax      = td_dom%i_jmax + td_dom%i_jextra(2)
             ENDIF
-            IF( td_dom%i_jmax /= td_dom%t_dim(2)%i_len )THEN
-               td_dom%i_jextra(2)=il_jext
-
-            ENDIF
-
-         ENDIF
-
-      ENDIF
-
-      ! change domain
-      td_dom%i_imin         = td_dom%i_imin - td_dom%i_iextra(1)
-      td_dom%i_jmin         = td_dom%i_jmin - td_dom%i_jextra(1)
-
-      td_dom%i_imax         = td_dom%i_imax + td_dom%i_iextra(2)
-      td_dom%i_jmax         = td_dom%i_jmax + td_dom%i_jextra(2)
-
-      td_dom%t_dim(1)%i_len = td_dom%t_dim(1)%i_len + &
-      &                          td_dom%i_iextra(1) + &
-      &                          td_dom%i_iextra(2)
-      td_dom%t_dim(2)%i_len = td_dom%t_dim(2)%i_len + &
-      &                          td_dom%i_jextra(1) + &
-      &                          td_dom%i_jextra(2)
+         ENDIF         
+
+      ENDIF
+
+      IF( td_dom%i_imin <= td_dom%i_imax )THEN
+         td_dom%t_dim(1)%i_len = td_dom%i_imax - td_dom%i_imin +1 
+      ELSE ! td_dom%i_imin > td_dom%i_imax
+         td_dom%t_dim(1)%i_len = td_dom%i_imax + &
+         &                       td_dom%t_dim0(1)%i_len - td_dom%i_imin + 1 - &
+         &                       td_dom%i_ew0 ! remove overlap
+      ENDIF
+
+      td_dom%t_dim(2)%i_len = td_dom%i_jmax-td_dom%i_jmin+1
 
 
    END SUBROUTINE dom_add_extra
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !>  This subroutine clean domain structure. it remove extra point added. 
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !>  This subroutine clean coarse grid domain structure. 
+   !> it remove extra point added. 
+   !
+   !> @author J.Paul
+   !> @date November, 2013
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom_clean_extra( td_dom )
       IMPLICIT NONE
@@ -1404,24 +1464,34 @@
 
    END SUBROUTINE dom_clean_extra
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !>  This subroutine 
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_var : variable strcuture
-   !> @param[inout] td_dom : domain strcuture
-   !> @param[inout] id_rhoi : i-direction refinement factor
-   !> @param[inout] id_rhoj : j-direction refinement factor
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE dom_del_extra( td_var, td_dom, id_rho )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TVAR) , INTENT(INOUT) :: td_var
-      TYPE(TDOM) , INTENT(IN   ) :: td_dom
-      INTEGER(i4), DIMENSION(:), INTENT(IN   ) :: id_rho
+   !>  This subroutine delete extra band, from fine grid variable value, 
+   !> and dimension, taking into account refinement factor.
+   !>
+   !> @details
+   !> @note This subroutine should be used before clean domain structure.
+   !>
+   !> @warning if work on coordinates grid, do not remove all extra point.
+   !> save value on ghost cell. 
+   !> 
+   !> @author J.Paul
+   !> @date November, 2013
+   !> @date September, 2014
+   !> - take into account boundary for one point size domain
+   !> @date December, 2014
+   !> - add special case for coordinates file.
+   !
+   !> @param[inout] td_var variable strcuture
+   !> @param[in] td_dom    domain strcuture
+   !> @param[in] id_rho    array of refinement factor
+   !> @param[in] ld_coord  work on coordinates file or not
+   !-------------------------------------------------------------------
+   SUBROUTINE dom_del_extra( td_var, td_dom, id_rho, ld_coord )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR)               , INTENT(INOUT) :: td_var
+      TYPE(TDOM)               , INTENT(IN   ) :: td_dom
+      INTEGER(i4), DIMENSION(:), INTENT(IN   ), OPTIONAL :: id_rho
+      LOGICAL                  , INTENT(IN   ), OPTIONAL :: ld_coord
 
       ! local variable
@@ -1434,8 +1504,23 @@
       INTEGER(i4) :: il_jmax
       
-      REAL(dp), DIMENSION(:,:,:,:), ALLOCATABLE :: dl_value
-
+      INTEGER(i4), DIMENSION(2)   :: il_rho
+      INTEGER(i4), DIMENSION(2,2) :: il_ghost
+
+      REAL(dp)   , DIMENSION(:,:,:,:), ALLOCATABLE :: dl_value
+
+      LOGICAL     :: ll_coord
       ! loop indices
       !----------------------------------------------------------------
+
+      IF( PRESENT(id_rho) )THEN
+         ! work on coarse grid
+         il_rho(:)=id_rho(jp_I:jp_J)
+      ELSE
+         ! work on fine grid
+         il_rho(:)=1
+      ENDIF
+
+      ll_coord=.false.
+      IF( PRESENT(ld_coord) ) ll_coord=ld_coord
 
       IF( .NOT. ASSOCIATED(td_var%d_value) )THEN
@@ -1443,8 +1528,6 @@
          &     "variable "//TRIM(td_var%c_name) )
       ELSE
-         ! get vairbale right domain
+         ! get variable right domain
          IF( ALL(td_var%t_dim(1:2)%l_use) )THEN
-            il_iextra=SUM(td_dom%i_iextra(:))*id_rho(jp_I)
-            il_jextra=SUM(td_dom%i_jextra(:))*id_rho(jp_J)
 
             ALLOCATE(dl_value(td_var%t_dim(1)%i_len, &
@@ -1454,12 +1537,161 @@
             dl_value(:,:,:,:)=td_var%d_value(:,:,:,:)
 
-            il_imin=1                     + td_dom%i_iextra(1)*id_rho(jp_I)
-            il_imax=td_var%t_dim(1)%i_len - td_dom%i_iextra(2)*id_rho(jp_I)
-
-            il_jmin=1                     + td_dom%i_jextra(1)*id_rho(jp_J)
-            il_jmax=td_var%t_dim(2)%i_len - td_dom%i_jextra(2)*id_rho(jp_J)
-
-            td_var%t_dim(1)%i_len=td_var%t_dim(1)%i_len-il_iextra
-            td_var%t_dim(2)%i_len=td_var%t_dim(2)%i_len-il_jextra
+            il_iextra=SUM(td_dom%i_iextra(:))*il_rho(jp_I)
+            il_jextra=SUM(td_dom%i_jextra(:))*il_rho(jp_J)
+
+            il_ghost(:,:)=0
+            IF( ll_coord )THEN
+               il_ghost(:,:)=td_dom%i_ghost(:,:)
+            ENDIF
+
+            IF( il_iextra >= td_var%t_dim(1)%i_len )THEN
+               ! case one point size dimension
+               SELECT CASE(td_dom%i_bdy) 
+
+                  CASE(jp_north,jp_east)
+
+                     CALL logger_info("DOM DEL EXTRA: special case for north"//&
+                     &                " or east boundary.")
+                     IF( td_dom%i_iextra(1) <= 0 )THEN
+                        il_imin= 1
+                        il_ghost(jp_I,1) = 0
+                     ELSE
+                        il_imin= 1 + (td_dom%i_iextra(1)-1)*il_rho(jp_I) + 1 &
+                        &        - il_ghost(jp_I,1)
+                     ENDIF
+                     IF( td_dom%i_iextra(2) <= 0 )THEN;
+                        il_imax= td_var%t_dim(1)%i_len
+                        il_ghost(jp_I,2) = 0
+                     ELSE
+                        il_imax= td_var%t_dim(1)%i_len - &
+                        &          td_dom%i_iextra(2)*il_rho(jp_I) &
+                        &        + il_ghost(jp_I,2)
+                     ENDIF
+
+                  CASE(jp_south,jp_west)
+
+                     CALL logger_info("DOM DEL EXTRA: special case for south"//&
+                     &                " or west boundary.")
+                     IF( td_dom%i_iextra(1) <= 0 )THEN
+                        il_imin= 1
+                        il_ghost(jp_I,1) = 0
+                     ELSE
+                        il_imin= 1 + td_dom%i_iextra(1)*il_rho(jp_I) &
+                        &        - il_ghost(jp_I,1)
+                     ENDIF
+                     IF( td_dom%i_iextra(2) <= 0 )THEN
+                        il_imax= td_var%t_dim(1)%i_len
+                        il_ghost(jp_I,2) = 0
+                     ELSE
+                        il_imax= td_var%t_dim(1)%i_len - &
+                        &          (td_dom%i_iextra(2)-1)*il_rho(jp_I) - 1 &
+                        &        + il_ghost(jp_I,2)
+                     ENDIF
+
+                  CASE DEFAULT
+
+                     IF( MOD(il_iextra-td_var%t_dim(1)%i_len,2)==0 )THEN
+                        ! case one point size dimension with even refinment
+                        CALL logger_fatal("DOM DEL EXTRA: should have been"//&
+                        &                 "an impossible case: domain of "//&
+                        &                 " one point size and even refinment.")
+                     ELSE
+                        il_imin= 1 + &
+                        &        (td_dom%i_iextra(1)-1)*il_rho(jp_I) + &
+                        &        (il_rho(jp_I)-1)/2 + 1                &
+                        &        - il_ghost(jp_I,1)
+                        il_imax= td_var%t_dim(1)%i_len - &
+                        &        (td_dom%i_iextra(2)-1)*il_rho(jp_I) - &
+                        &        (il_rho(jp_I)-1)/2 - 1                &
+                        &        + il_ghost(jp_I,2)
+                     ENDIF
+
+               END SELECT
+
+               td_var%t_dim(1)%i_len = 1 + SUM(il_ghost(jp_I,:))
+
+            ELSE
+               ! general case
+               il_imin=1                     + td_dom%i_iextra(1)*il_rho(jp_I) &
+               &                             - il_ghost(jp_I,1)
+               il_imax=td_var%t_dim(1)%i_len - td_dom%i_iextra(2)*il_rho(jp_I) &
+               &                             + il_ghost(jp_I,2)
+
+               td_var%t_dim(1)%i_len=td_var%t_dim(1)%i_len - il_iextra &
+               &                                         + SUM(il_ghost(jp_I,:))
+            ENDIF
+
+            IF( il_jextra >= td_var%t_dim(2)%i_len )THEN
+               ! case one point size dimension
+               SELECT CASE(td_dom%i_bdy) 
+
+                  CASE(jp_north,jp_east)
+
+                     IF( td_dom%i_jextra(1) <= 0 )THEN
+                        il_jmin= 1
+                        il_ghost(jp_J,1) = 0
+                     ELSE
+                        il_jmin= 1 + (td_dom%i_jextra(1)-1)*il_rho(jp_J) + 1 &
+                        &        - il_ghost(jp_J,1)
+                     ENDIF
+                     IF( td_dom%i_jextra(2) <= 0 )THEN
+                        il_jmax= td_var%t_dim(2)%i_len
+                        il_ghost(jp_J,2) = 0
+                     ELSE
+                        il_jmax= td_var%t_dim(2)%i_len - &
+                        &          td_dom%i_jextra(2)*il_rho(jp_J) &
+                        &        + il_ghost(jp_J,2)
+                     ENDIF
+
+                  CASE(jp_south,jp_west)
+
+                     IF( td_dom%i_iextra(2) <= 0 )THEN
+                        il_jmin= 1
+                        il_ghost(jp_J,1) = 0
+                     ELSE
+                        il_jmin= 1 + td_dom%i_jextra(1)*il_rho(jp_J) &
+                        &        - il_ghost(jp_J,1)
+                     ENDIF
+                     IF( td_dom%i_jextra(2) <= 0 )THEN
+                        il_jmax= td_var%t_dim(2)%i_len
+                        il_ghost(jp_J,2) = 0
+                     ELSE
+                        il_jmax= td_var%t_dim(2)%i_len - &
+                        &          (td_dom%i_jextra(2)-1)*il_rho(jp_J) - 1 &
+                        &        + il_ghost(jp_J,2)
+                     ENDIF
+
+                  CASE DEFAULT
+
+                     IF( MOD(il_jextra-td_var%t_dim(2)%i_len,2)==0 )THEN
+                        ! case one point size dimension with even refinment
+                        CALL logger_fatal("DOM DEL EXTRA: should have been"//&
+                        &                 "an impossible case: domain of "//&
+                        &                 " one point size and even refinment.")
+                     ELSE
+                        il_jmin= 1 + &
+                        &        (td_dom%i_jextra(1)-1)*il_rho(jp_J) + &
+                        &        (il_rho(jp_J)-1)/2 + 1 &
+                        &        - il_ghost(jp_J,1)
+                        il_jmax= td_var%t_dim(2)%i_len - &
+                        &        (td_dom%i_jextra(2)-1)*il_rho(jp_J) - &
+                        &        (il_rho(jp_J)-1)/2 - 1 &
+                        &        + il_ghost(jp_J,2)
+                     ENDIF
+
+               END SELECT
+
+               td_var%t_dim(2)%i_len = 1 + SUM(il_ghost(jp_J,:))
+
+            ELSE
+               ! general case
+               il_jmin=1                     + td_dom%i_jextra(1)*il_rho(jp_J) &
+               &                             - il_ghost(jp_J,1)
+               il_jmax=td_var%t_dim(2)%i_len - td_dom%i_jextra(2)*il_rho(jp_J) &
+               &                             + il_ghost(jp_J,2)
+
+                td_var%t_dim(2)%i_len= td_var%t_dim(2)%i_len - il_jextra &
+                &                                        + SUM(il_ghost(jp_J,:))
+            ENDIF
 
             DEALLOCATE(td_var%d_value)
@@ -1478,15 +1710,13 @@
 
    END SUBROUTINE dom_del_extra
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !>  This subroutine clean mpp strcuture.
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !>  This subroutine clean domain structure.
+   !
+   !> @author J.Paul
+   !> @date November, 2013
+   !
+   !> @param[inout] td_dom domain strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE dom_clean( td_dom )
       IMPLICIT NONE
@@ -1495,5 +1725,5 @@
 
       ! local variable
-      TYPE(TDOM) :: tl_dom ! empty file structure
+      TYPE(TDOM) :: tl_dom ! empty dom structure
 
       ! loop indices
@@ -1501,5 +1731,5 @@
       !----------------------------------------------------------------
 
-      CALL logger_info( " CLEAN: reset domain " )
+      CALL logger_info( "DOM CLEAN: reset domain " )
 
       ! del dimension
@@ -1511,4 +1741,4 @@
       td_dom=tl_dom
 
-      END SUBROUTINE dom_clean
+   END SUBROUTINE dom_clean
 END MODULE dom
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/extrap.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/extrap.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/extrap.f90	(revision 5075)
@@ -7,7 +7,86 @@
 ! DESCRIPTION:
 !> @brief 
-!> This module 
+!> This module manage extrapolation.
 !>
 !> @details
+!>    Extrapolation method to be used is specify inside variable 
+!>    strcuture, as array of string character.<br/> 
+!>    - td_var\%c_extrap(1) string character is the interpolation name choose between:
+!>       - 'dist_weight'
+!>       - 'min_error'
+!>
+!>    @note Extrapolation method could be specify for each variable in namelist _namvar_,
+!>    defining string character _cn\_varinfo_. By default _dist_weight_.<br/>
+!>    Example:
+!>       - cn_varinfo='varname1:dist_weight', 'varname2:min_error'
+!>
+!>    to detect point to be extrapolated:<br/>
+!> @code
+!>    il_detect(:,:,:)=extrap_detect(td_var, [td_level], [id_offset,] [id_rho,] [id_ext]) 
+!> @endcode
+!>       - il_detect(:,:,:) is 3D array of point to be extrapolated
+!>       - td_var  is coarse grid variable to be extrapolated
+!>       - td_level is fine grid array of level (see vgrid_get_level) [optional]
+!>       - id_offset is array of offset between fine and coarse grid [optional]
+!>       - id_rho    is array of refinment factor [optional]
+!>       - id_ext    is array of number of points to be extrapolated [optional]
+!>
+!>    to extrapolate variable:<br/>
+!> @code
+!>    CALL extrap_fill_value( td_var, [td_level], [id_offset], [id_rho], [id_iext], [id_jext], [id_kext], [id_radius], [id_maxiter])
+!> @endcode
+!>       - td_var  is coarse grid variable to be extrapolated
+!>       - td_level is fine grid array of level (see vgrid_get_level) [optional]
+!>       - id_offset is array of offset between fine and coarse grid [optional]
+!>       - id_rho    is array of refinment factor [optional]
+!>       - id_iext   is number of points to be extrapolated in i-direction [optional]
+!>       - id_jext   is number of points to be extrapolated in j-direction [optional]
+!>       - id_kext   is number of points to be extrapolated in k-direction [optional]
+!>       - id_radius is radius of the halo used to compute extrapolation [optional]
+!>       - id_maxiter is maximum number of iteration [optional]
+!>
+!>    to add extraband to the variable (to be extrapolated):<br/>
+!> @code
+!>    CALL extrap_add_extrabands(td_var, [id_isize,] [id_jsize] )
+!> @endcode
+!>       - td_var is variable structure
+!>       - id_isize : i-direction size of extra bands [optional]
+!>       - id_jsize : j-direction size of extra bands [optional]
+!>
+!>    to delete extraband of a variable:<br/>
+!> @code
+!>    CALL extrap_del_extrabands(td_var, [id_isize,] [id_jsize] )
+!> @endcode
+!>       - td_var is variable structure
+!>       - id_isize : i-direction size of extra bands [optional]
+!>       - id_jsize : j-direction size of extra bands [optional]
+!>
+!>    to compute first derivative of 1D array:<br/>
+!> @code
+!>    dl_value(:)=extrap_deriv_1D( dd_value(:), dd_fill, [ld_discont] )
+!> @endcode
+!>       - dd_value is 1D array of variable
+!>       - dd_fill is FillValue of variable
+!>       - ld_discont is logical to take into account longitudinal East-West discontinuity [optional]
+!>
+!>    to compute first derivative of 2D array:<br/>
+!> @code
+!>    dl_value(:,:)=extrap_deriv_2D( dd_value(:,:), dd_fill, cd_dim, [ld_discont] )
+!> @endcode
+!>       - dd_value is 2D array of variable
+!>       - dd_fill is FillValue of variable
+!>       - cd_dim is character to compute derivative on first (I) or second (J) dimension
+!>       - ld_discont is logical to take into account longitudinal East-West discontinuity [optional]
+!>
+!>    to compute first derivative of 3D array:<br/>
+!> @code
+!>    dl_value(:,:,:)=extrap_deriv_3D( dd_value(:,:,:), dd_fill, cd_dim, [ld_discont] )
+!> @endcode
+!>       - dd_value is 3D array of variable
+!>       - dd_fill is FillValue of variable
+!>       - cd_dim is character to compute derivative on first (I), second (J), or third (K) dimension
+!>       - ld_discont is logical to take into account longitudinal East-West discontinuity [optional]
+!>
+!> @warning _FillValue must not be zero (use var_chg_FillValue())
 !>
 !> @author
@@ -15,47 +94,50 @@
 ! REVISION HISTORY:
 !> @date Nov, 2013 - Initial Version
+!> @date September, 2014
+!> - add header
 !>
-!> @note WARNING: FillValue must not be zero (use var_chg_FillValue)
+!> @todo
+!> - create module for each extrapolation method
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
-!> - something wrong when computing point to be extralopated
-!> - take care of ew value in variable structure
 !----------------------------------------------------------------------
 MODULE extrap
    USE netcdf                          ! nf90 library
-   USE kind
-   USE phycst
-   USE global
-   USE fct
-   USE logger
-   USE dim
-   USE att
-   USE var
+   USE kind                            ! F90 kind parameter
+   USE phycst                          ! physical constant
+   USE global                          ! global variable
+   USE fct                             ! basic useful function
+   USE date                            ! date manager
+   USE logger                          ! log file manager
+   USE att                             ! attribute manager
+   USE dim                             ! dimension manager
+   USE var                             ! variable manager
 
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
+   PRIVATE :: im_maxiter   !< default maximum number of iteration 
+   PRIVATE :: im_minext    !< default minumum number of point to extrapolate
+   PRIVATE :: im_mincubic  !< default minumum number of point to extrapolate for cubic interpolation
 
    ! function and subroutine
    PUBLIC :: extrap_detect         !< detected point to be extrapolated
    PUBLIC :: extrap_fill_value     !< extrapolate value over detected point 
-   PUBLIC :: extrap_add_extrabands !< 
-   PUBLIC :: extrap_del_extrabands !< 
-   PUBLIC :: extrap_deriv_1D !< 
-   PUBLIC :: extrap_deriv_2D !< 
-
-   PRIVATE :: extrap__detect_wrapper !< detected point to be extrapolated
-   PRIVATE :: extrap__detect         !< detected point to be extrapolated
-   PRIVATE :: extrap__fill_value_wrapper     !< extrapolate value over detected point 
-   PRIVATE :: extrap__fill_value     !< extrapolate value over detected point 
-   PRIVATE :: extrap__3D
-   PRIVATE :: extrap_deriv_3D
-   PRIVATE :: extrap__3D_min_error_coef
-   PRIVATE :: extrap__3D_min_error_fill
-   PRIVATE :: extrap__3D_dist_weight_coef
-   PRIVATE :: extrap__3D_dist_weight_fill
+   PUBLIC :: extrap_add_extrabands !< add extraband to the variable (to be extrapolated) 
+   PUBLIC :: extrap_del_extrabands !< delete extraband of the variable 
+   PUBLIC :: extrap_deriv_1D       !< compute first derivative of 1D array 
+   PUBLIC :: extrap_deriv_2D       !< compute first derivative of 2D array 
+   PUBLIC :: extrap_deriv_3D       !< compute first derivative of 3D array
+
+   PRIVATE :: extrap__detect_wrapper      ! detected point to be extrapolated wrapper
+   PRIVATE :: extrap__detect              ! detected point to be extrapolated
+   PRIVATE :: extrap__fill_value_wrapper  ! extrapolate value over detected point wrapper 
+   PRIVATE :: extrap__fill_value          ! extrapolate value over detected point 
+   PRIVATE :: extrap__3D                  !
+   PRIVATE :: extrap__3D_min_error_coef   !
+   PRIVATE :: extrap__3D_min_error_fill   !
+   PRIVATE :: extrap__3D_dist_weight_coef !
+   PRIVATE :: extrap__3D_dist_weight_fill ! 
 
    INTEGER(i4), PARAMETER :: im_maxiter = 10 !< default maximum number of iteration
@@ -64,5 +146,5 @@
 
    INTERFACE extrap_detect
-      MODULE PROCEDURE extrap__detect_wrapper !< detected point to be extrapolated
+      MODULE PROCEDURE extrap__detect_wrapper     !< detected point to be extrapolated
    END INTERFACE extrap_detect
 
@@ -74,23 +156,33 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This function detected point to be extrapolated.
+   !> This function detected point to be extrapolated, given variable structure.
    !> 
    !> @details 
+   !> optionaly, you could sepcify fine grid level, refinment factor (default 1), 
+   !> offset between fine and coarse grid (default compute from refinment factor
+   !> as offset=(rho-1)/2), number of point to be extrapolated in each direction
+   !> (default im_minext).<br/>
    !>
+   !> First coarsening fine grid level, if need be, then select point near 
+   !> grid point already inform.
+   !>
+   !> @note point to be extrapolated are selected using FillValue, 
+   !> so to avoid mistake FillValue should not be zero (use var_chg_FillValue)
+   !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[in] td_var : variable to extrapolate
-   !> @param[in] id_iext : number of points to be extrapolated in i-direction
-   !> @param[in] id_jext : number of points to be extrapolated in j-direction
-   !> @param[in] id_kext : number of points to be extrapolated in k-direction
-   !> @return
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] td_var0   coarse grid variable to extrapolate
+   !> @param[in] td_level1 fine grid array of level
+   !> @param[in] id_offset array of offset between fine and coarse grid 
+   !> @param[in] id_rho    array of refinment factor 
+   !> @param[in] id_ext    array of number of points to be extrapolated
+   !> @return array of point to be extrapolated
+   !-------------------------------------------------------------------
    FUNCTION extrap__detect( td_var0, td_level1, &
    &                        id_offset, id_rho, id_ext )
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) ,                 INTENT(INOUT) :: td_var0
+      TYPE(TVAR) ,                 INTENT(IN   ) :: td_var0
       TYPE(TVAR) , DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: td_level1
       INTEGER(i4), DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_offset
@@ -106,6 +198,7 @@
       CHARACTER(LEN=lc)                                :: cl_level
 
-      INTEGER(i4)                                      :: il_varid
+      INTEGER(i4)                                      :: il_ind
       INTEGER(i4)      , DIMENSION(:,:,:), ALLOCATABLE :: il_detect
+      INTEGER(i4)      , DIMENSION(:,:,:), ALLOCATABLE :: il_tmp
       INTEGER(i4)      , DIMENSION(:,:)  , ALLOCATABLE :: il_offset
       INTEGER(i4)      , DIMENSION(:,:)  , ALLOCATABLE :: il_level1
@@ -143,9 +236,10 @@
       ALLOCATE( il_offset(ip_maxdim,2) )
       il_offset(:,:)=0
-      il_offset(jp_I,:)=FLOOR(REAL(il_rho(jp_I)-1,dp)*0.5)
-      il_offset(jp_J,:)=FLOOR(REAL(il_rho(jp_J)-1,dp)*0.5)
       IF( PRESENT(id_offset) )THEN
          il_offset(1:SIZE(id_offset(:,:),DIM=1),&
          &         1:SIZE(id_offset(:,:),DIM=2) )= id_offset(:,:)
+      ELSE
+         il_offset(jp_I,:)=FLOOR(REAL(il_rho(jp_I)-1,dp)*0.5)
+         il_offset(jp_J,:)=FLOOR(REAL(il_rho(jp_J)-1,dp)*0.5)
       ENDIF
 
@@ -160,19 +254,26 @@
 
       ! select point already inform
-      WHERE( td_var0%d_value(:,:,:,1) /= td_var0%d_fill ) il_detect(:,:,:)=1
+      DO jk0=1,td_var0%t_dim(3)%i_len
+         DO jj0=1,td_var0%t_dim(2)%i_len
+            DO ji0=1,td_var0%t_dim(1)%i_len
+               IF( td_var0%d_value(ji0,jj0,jk0,1) /= td_var0%d_fill ) il_detect(ji0,jj0,jk0)=1
+            ENDDO
+         ENDDO
+      ENDDO
  
       IF( PRESENT(td_level1) )THEN
          SELECT CASE(TRIM(td_var0%c_point))
-         CASE DEFAULT !'T'
-            cl_level='tlevel'
-         CASE('U')
-            cl_level='ulevel'
-         CASE('V')
-            cl_level='vlevel'
-         CASE('F')
-            cl_level='flevel'
+            CASE DEFAULT !'T'
+               cl_level='tlevel'
+            CASE('U')
+               cl_level='ulevel'
+            CASE('V')
+               cl_level='vlevel'
+            CASE('F')
+               cl_level='flevel'
          END SELECT
-         il_varid=var_get_id(td_level1(:),TRIM(cl_level))
-         IF( il_varid == 0 )THEN
+
+         il_ind=var_get_index(td_level1(:),TRIM(cl_level))
+         IF( il_ind == 0 )THEN
             CALL logger_error("EXTRAP DETECT: can not compute point to be "//&
             &     "extrapolated for variable "//TRIM(td_var0%c_name)//&
@@ -180,84 +281,66 @@
             &     "level for variable point "//TRIM(TRIM(td_var0%c_point)))
          ELSE
-            print *,'read ',trim(cl_level)
-            tl_var1=td_level1(il_varid)
+            tl_var1=var_copy(td_level1(il_ind))
+
+            ALLOCATE( il_level1_G0( il_dim0(1), il_dim0(2)) )
+            IF( ALL(tl_var1%t_dim(1:2)%i_len == il_dim0(1:2)) )THEN
+
+               ! variable to be extrapolated use same resolution than level
+               il_level1_G0(:,:)=INT(tl_var1%d_value(:,:,1,1),i4)
+               
+            ELSE
+               ! variable to be extrapolated do not use same resolution than level
+               ALLOCATE( il_level1(tl_var1%t_dim(1)%i_len, &
+               &                   tl_var1%t_dim(2)%i_len) )
+               ! match fine grid vertical level with coarse grid
+               il_level1(:,:)=INT(tl_var1%d_value(:,:,1,1),i4)/il_rho(jp_K)
+
+               ALLOCATE( il_extra(ip_maxdim,2) )
+               ! coarsening fine grid level
+               il_extra(jp_I,1)=CEILING(REAL(il_rho(jp_I)-1,dp)*0.5_dp)
+               il_extra(jp_I,2)=FLOOR(REAL(il_rho(jp_I)-1,dp)*0.5_dp)
+
+               il_extra(jp_J,1)=CEILING(REAL(il_rho(jp_J)-1,dp)*0.5_dp)
+               il_extra(jp_J,2)=FLOOR(REAL(il_rho(jp_J)-1,dp)*0.5_dp)
+
+               DO jj0=1,td_var0%t_dim(2)%i_len
+                  
+                  jj1=(jj0-1)*il_rho(jp_J)+1-il_offset(jp_J,1)
+
+                  jj1m=MAX( jj1-il_extra(jp_J,1), 1 )
+                  jj1p=MIN( jj1+il_extra(jp_J,2), &
+                  &         tl_var1%t_dim(2)%i_len-il_offset(jp_J,2) )
+                  
+                  DO ji0=1,td_var0%t_dim(1)%i_len
+
+                     ji1=(ji0-1)*il_rho(jp_I)+1-id_offset(jp_I,1)
+
+                     ji1m=MAX( ji1-il_extra(jp_I,1), 1 )
+                     ji1p=MIN( ji1+il_extra(jp_I,2), &
+                     &         tl_var1%t_dim(1)%i_len-id_offset(jp_I,2) )
+               
+                     il_level1_G0(ji0,jj0)=MAXVAL(il_level1(ji1m:ji1p,jj1m:jj1p))
+
+                  ENDDO
+               ENDDO
+
+               ! clean
+               DEALLOCATE( il_extra )
+               DEALLOCATE( il_level1 )
+
+            ENDIF
+
+            ! look for sea point
+            DO jk0=1,td_var0%t_dim(3)%i_len
+               WHERE( il_level1_G0(:,:) >= jk0)
+                  il_detect(:,:,jk0)=1
+               END WHERE
+            ENDDO
+
+            ! clean
+            DEALLOCATE( il_level1_G0 )
+            CALL var_clean(tl_var1)
+
          ENDIF
-
-         ALLOCATE( il_level1_G0( il_dim0(1), il_dim0(2)) )
-         IF( ALL(tl_var1%t_dim(1:2)%i_len == il_dim0(1:2)) )THEN
-
-            ! variable to be extrapolated use same resolution than level
-            il_level1_G0(:,:)=INT(tl_var1%d_value(:,:,1,1),i4)
-            
-         ELSE
-            ! variable to be extrapolated do not use same resolution than level
-            ALLOCATE( il_level1(tl_var1%t_dim(1)%i_len, &
-            &                   tl_var1%t_dim(2)%i_len) )
-            ! match fine grid vertical level with coarse grid
-            il_level1(:,:)=INT(tl_var1%d_value(:,:,1,1),i4)/il_rho(jp_K)
-
-            ALLOCATE( il_extra(ig_ndim,2) )
-            ! coarsening fine grid level
-            il_extra(jp_I,1)=CEILING(REAL(il_rho(jp_I)-1,dp)/2._dp)
-            il_extra(jp_I,2)=FLOOR(REAL(il_rho(jp_I)-1,dp)/2._dp)
-
-            il_extra(jp_J,1)=CEILING(REAL(il_rho(jp_J)-1,dp)/2._dp)
-            il_extra(jp_J,2)=FLOOR(REAL(il_rho(jp_J)-1,dp)/2._dp)
-
-            DO jj0=1,td_var0%t_dim(2)%i_len
-               
-               jj1=(jj0-1)*il_rho(jp_J)+1-il_offset(jp_J,1)
-
-               jj1m=MAX( jj1-il_extra(jp_J,1), 1 )
-               jj1p=MIN( jj1+il_extra(jp_J,2), &
-               &         tl_var1%t_dim(2)%i_len-il_offset(jp_J,2) )
-               
-               DO ji0=1,td_var0%t_dim(1)%i_len
-
-                  ji1=(ji0-1)*il_rho(jp_I)+1-id_offset(jp_I,1)
-
-                  ji1m=MAX( ji1-il_extra(jp_I,1), 1 )
-                  ji1p=MIN( ji1+il_extra(jp_I,2), &
-                  &         tl_var1%t_dim(1)%i_len-id_offset(jp_I,2) )
-            
-                  il_level1_G0(ji0,jj0)=MAXVAL(il_level1(ji1m:ji1p,jj1m:jj1p))
-               ENDDO
-            ENDDO
-
-            !il_level1_G0(:,:)=0
-            !DO jj1=1,tl_var1%t_dim(2)%i_len
-      
-            !   jj0=INT(REAL((jj1+il_offset(jp_J,1)-1)-1,dp)/REAL(il_rho(jp_J),dp)) +1
-
-            !   DO ji1=1,tl_var1%t_dim(1)%i_len
-
-            !      ji0=INT(REAL((ji1+il_offset(jp_I,1)-1)-1,dp)/REAL(il_rho(jp_I),dp)) +1
-
-            !      il_level1_G0(ji0,jj0)=MAX(il_level1_G0(ji0,jj0),il_level1(ji1,jj1))
-            !      
-            !   ENDDO
-            !ENDDO
-
-            ! clean
-            DEALLOCATE( il_extra )
-            DEALLOCATE( il_level1 )
-
-         ENDIF
-
-         ! look for sea point
-         !il_detect(:,:,1)=0
-         DO jk0=1,td_var0%t_dim(3)%i_len
-            WHERE( il_level1_G0(:,:) >= jk0)
-               il_detect(:,:,jk0)=1
-            END WHERE
-            !il_detect(:,:,jk0)=il_level1_G0(:,:)
-            !WHERE( td_var0%d_value(:,:,jk0,1) /= td_var0%d_fill )
-            !   il_detect(:,:,1)=jk0-1
-            !END WHERE
-         ENDDO
-
-         ! clean
-         DEALLOCATE( il_level1_G0 )
-
       ENDIF
 
@@ -265,19 +348,37 @@
       DEALLOCATE( il_offset )
  
-      !! select extra point depending on interpolation method
-      !! compute point near grid point already inform
-      !FORALL( ji0=1:il_dim0(1), &
-      !&       jj0=1:il_dim0(2), &
-      !&       jk0=1:il_dim0(3), &
-      !&       il_detect(ji0,jj0,jk0) == 1 )
-
-      !   il_detect(MAX(1,ji0-il_ext(jp_I)):MIN(ji0+il_ext(jp_I),il_dim0(1)),&
-      !   &         MAX(1,jj0-il_ext(jp_J)):MIN(jj0+il_ext(jp_J),il_dim0(2)),&
-      !   &         MAX(1,jk0-il_ext(jp_K)):MIN(jk0+il_ext(jp_K),il_dim0(3)) )=1 
-
-      !END FORALL
+      ALLOCATE( il_tmp(il_dim0(1),&
+      &                il_dim0(2),&
+      &                il_dim0(3)) )
+      il_tmp(:,:,:)=il_detect(:,:,:)
+      ! select extra point depending on interpolation method
+      ! compute point near grid point already inform
+      DO jk0=1,il_dim0(3)
+         DO jj0=1,il_dim0(2)
+            DO ji0=1,il_dim0(1)
+
+               IF( il_tmp(ji0,jj0,jk0) == 1 )THEN
+                  il_detect( &
+                  &  MAX(1,ji0-il_ext(jp_I)):MIN(ji0+il_ext(jp_I),il_dim0(1)),&
+                  &  MAX(1,jj0-il_ext(jp_J)):MIN(jj0+il_ext(jp_J),il_dim0(2)),&
+                  &  MAX(1,jk0-il_ext(jp_K)):MIN(jk0+il_ext(jp_K),il_dim0(3)) &
+                  &  ) = 1 
+               ENDIF
+
+            ENDDO
+         ENDDO
+      ENDDO
       
+      ! clean
+      DEALLOCATE( il_tmp )
+
       ! do not compute grid point already inform
-      WHERE( td_var0%d_value(:,:,:,1) /= td_var0%d_fill ) il_detect(:,:,:)=0
+      DO jk0=1,td_var0%t_dim(3)%i_len
+         DO jj0=1,td_var0%t_dim(2)%i_len
+            DO ji0=1,td_var0%t_dim(1)%i_len
+               IF( td_var0%d_value(ji0,jj0,jk0,1) /= td_var0%d_fill ) il_detect(ji0,jj0,jk0)=0
+            ENDDO
+         ENDDO
+      ENDDO
 
       ! save result
@@ -288,23 +389,22 @@
       DEALLOCATE( il_ext )
       DEALLOCATE( il_detect )
+      DEALLOCATE( il_rho )
 
    END FUNCTION extrap__detect
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function detected point to be extrapolated.
+   !> This function sort variable to be extrapolated, depending on number of
+   !> dimentsion, then detected point to be extrapolated.
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : variable to extrapolate
-   !> @param[in] id_iext : number of points to be extrapolated in i-direction
-   !> @param[in] id_jext : number of points to be extrapolated in j-direction
-   !> @param[in] id_kext : number of points to be extrapolated in k-direction
-   !> @return
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] td_var    coarse grid variable to extrapolate
+   !> @param[in] td_level  fine grid array of level
+   !> @param[in] id_offset array of offset between fine and coarse grid 
+   !> @param[in] id_rho    array of refinment factor 
+   !> @param[in] id_ext    array of number of points to be extrapolated
+   !> @return 3D array of point to be extrapolated
+   !-------------------------------------------------------------------
    FUNCTION extrap__detect_wrapper( td_var, td_level, &
    &                                id_offset, id_rho, id_ext )
@@ -312,6 +412,6 @@
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) ,                         INTENT(INOUT) :: td_var
-      TYPE(TVAR) , DIMENSION(:)          , INTENT(IN   ), OPTIONAL :: td_level
+      TYPE(TVAR) ,                 INTENT(IN   ) :: td_var
+      TYPE(TVAR) , DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: td_level
       INTEGER(i4), DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_offset
       INTEGER(i4), DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_rho
@@ -335,5 +435,5 @@
       ELSE IF( ALL(td_var%t_dim(1:3)%l_use) )THEN
          
-         ! detect point to be interpolated on I-J-K
+         ! detect point to be extrapolated on I-J-K
          CALL logger_debug(" EXTRAP DETECT: detect point "//&
          &              " for variable "//TRIM(td_var%c_name) )
@@ -346,5 +446,5 @@
       ELSE IF( ALL(td_var%t_dim(1:2)%l_use) )THEN
 
-         ! detect point to be interpolated on I-J
+         ! detect point to be extrapolated on I-J
          CALL logger_debug(" EXTRAP DETECT: detect horizontal point "//&
          &              " for variable "//TRIM(td_var%c_name) )
@@ -357,5 +457,5 @@
       ELSE IF( td_var%t_dim(3)%l_use )THEN
          
-         ! detect point to be interpolated on K
+         ! detect point to be extrapolated on K
          CALL logger_debug(" EXTRAP DETECT: detect vertical point "//&
          &              " for variable "//TRIM(td_var%c_name) )
@@ -373,98 +473,32 @@
       
    END FUNCTION extrap__detect_wrapper
-   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief
-!   !> This function detected point to be extrapolated.
-!   !> 
-!   !> @details 
-!   !>
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in] td_var : variable to extrapolate
-!   !> @param[in] id_iext : number of points to be extrapolated in i-direction
-!   !> @param[in] id_jext : number of points to be extrapolated in j-direction
-!   !> @param[in] id_kext : number of points to be extrapolated in k-direction
-!   !> @return 
-!   !
-!   !> @todo
-!   !-------------------------------------------------------------------
-!   !> @code
-!   FUNCTION extrap__detect(td_var, id_iext, id_jext, id_kext)
-!      IMPLICIT NONE
-!      ! Argument
-!      TYPE(TVAR) ,                   INTENT(INOUT) :: td_var
-!      !INTEGER(i4), DIMENSION(:,:,:), INTENT(OUT  ) :: id_detect
-!      INTEGER(i4),                   INTENT(IN   ), OPTIONAL :: id_iext
-!      INTEGER(i4),                   INTENT(IN   ), OPTIONAL :: id_jext
-!      INTEGER(i4),                   INTENT(IN   ), OPTIONAL :: id_kext
-!
-!      ! function
-!      INTEGER(i4), DIMENSION(td_var%t_dim(1)%i_len, &
-!      &                      td_var%t_dim(2)%i_len, &
-!      &                      td_var%t_dim(3)%i_len) :: extrap__detect
-!
-!      ! local variable
-!      INTEGER(i4) :: il_iext
-!      INTEGER(i4) :: il_jext
-!      INTEGER(i4) :: il_kext
-!
-!      INTEGER(i4), DIMENSION(3) :: il_dim
-!
-!      ! loop indices
-!      INTEGER(i4) :: ji
-!      INTEGER(i4) :: jj
-!      INTEGER(i4) :: jk
-!      !----------------------------------------------------------------
-!
-!      ! optional argument
-!      il_iext=im_minext
-!      IF( PRESENT(id_iext) ) il_iext=id_iext
-!      il_jext=im_minext
-!      IF( PRESENT(id_jext) ) il_jext=id_jext
-!      il_kext=im_minext
-!      IF( PRESENT(id_kext) ) il_kext=id_kext
-!
-!      ! init
-!      extrap__detect(:,:,:)=0
-!
-!      il_dim(:)=td_var%t_dim(1:3)%i_len
-!
-!      ! compute point near grid point already inform
-!      FORALL( ji=1:il_dim(1), &
-!      &       jj=1:il_dim(2), &
-!      &       jk=1:il_dim(3), &
-!      &       td_var%d_value(ji,jj,jk,1) /= td_var%d_fill )
-!
-!         extrap__detect(MAX(1,ji-il_iext):MIN(ji+il_iext,il_dim(1)),&
-!         &              MAX(1,jj-il_jext):MIN(jj+il_jext,il_dim(2)),&
-!         &              MAX(1,jk-il_kext):MIN(jk+il_kext,il_dim(3)) )=1 
-!
-!
-!      END FORALL
-!      
-!      ! do not compute grid point already inform
-!      WHERE( td_var%d_value(:,:,:,1) /= td_var%d_fill ) extrap__detect(:,:,:)=0
-!
-!   END FUNCTION extrap__detect
-!   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine select method to be used for extrapolation.
+   !> If need be, increase number of points to be extrapolated.
+   !> Finally launch extrap__fill_value.
    !> 
-   !> @details 
+   !> @details
+   !> optionaly, you could specify :<br/>
+   !>  - refinment factor (default 1)
+   !>  - offset between fine and coarse grid (default compute from refinment factor
+   !> as offset=(rho-1)/2) 
+   !>  - number of point to be extrapolated in each direction (default im_minext)
+   !>  - radius of the halo used to compute extrapolation
+   !>  - maximum number of iteration
    !>
    !> @author J.Paul
    !> - Nov, 2013- Initial Version
    !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] id_iext : number of points to be extrapolated in i-direction
-   !> @param[in] id_jext : number of points to be extrapolated in j-direction
-   !> @param[in] id_kext : number of points to be extrapolated in k-direction
-   !> @param[in] id_extend :  radius of the box used to compute extrapolation 
-   !> @param[in] id_maxiter : maximum nuber of iteration
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[inout] td_var    variable structure
+   !> @param[in] td_level     fine grid array of level
+   !> @param[in] id_offset    array of offset between fine and coarse grid 
+   !> @param[in] id_rho       array of refinment factor 
+   !> @param[in] id_iext      number of points to be extrapolated in i-direction
+   !> @param[in] id_jext      number of points to be extrapolated in j-direction
+   !> @param[in] id_kext      number of points to be extrapolated in k-direction
+   !> @param[in] id_radius    radius of the halo used to compute extrapolation 
+   !> @param[in] id_maxiter   maximum number of iteration
+   !-------------------------------------------------------------------
    SUBROUTINE extrap__fill_value_wrapper( td_var, td_level, &
    &                                      id_offset,        &
@@ -496,5 +530,5 @@
       !----------------------------------------------------------------
       IF( .NOT. ASSOCIATED(td_var%d_value) )THEN
-         CALL logger_error("EXTRAP FILL VALUE: no table of value "//&
+         CALL logger_error("EXTRAP FILL VALUE: no value "//&
          &  "associted to variable "//TRIM(td_var%c_name) )
       ELSE
@@ -542,6 +576,5 @@
          IF( (il_iext /= 0 .AND. td_var%t_dim(1)%l_use) .OR. &
          &   (il_jext /= 0 .AND. td_var%t_dim(2)%l_use) .OR. &
-         &   (il_kext /= 0 .AND. td_var%t_dim(3)%l_use) .OR. &
-         &   PRESENT(td_level) )THEN
+         &   (il_kext /= 0 .AND. td_var%t_dim(3)%l_use) )THEN
 
             ! number of point use to compute box
@@ -577,23 +610,28 @@
 
    END SUBROUTINE extrap__fill_value_wrapper
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine compute point to be extrapolated, then extrapolate point.
    !> 
    !> @details 
+   !> optionaly, you could specify :<br/>
+   !>  - refinment factor (default 1)
+   !>  - offset between fine and coarse grid (default compute from refinment factor
+   !> as offset=(rho-1)/2) 
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] cd_method : extrapolation method
-   !> @param[in] id_iext : number of points to be extrapolated in i-direction
-   !> @param[in] id_jext : number of points to be extrapolated in j-direction
-   !> @param[in] id_kext : number of points to be extrapolated in k-direction
-   !> @param[in] id_radius : radius of the halo used to compute extrapolation
-   !> @param[in] id_maxiter : maximum nuber of iteration
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[inout] td_var    variable structure
+   !> @param[in] cd_method    extrapolation method
+   !> @param[in] id_iext      number of points to be extrapolated in i-direction
+   !> @param[in] id_jext      number of points to be extrapolated in j-direction
+   !> @param[in] id_kext      number of points to be extrapolated in k-direction
+   !> @param[in] id_radius    radius of the halo used to compute extrapolation
+   !> @param[in] id_maxiter   maximum number of iteration
+   !> @param[in] td_level     fine grid array of level
+   !> @param[in] id_offset    array of offset between fine and coarse grid 
+   !> @param[in] id_rho       array of refinment factor
+   !-------------------------------------------------------------------
    SUBROUTINE extrap__fill_value( td_var, cd_method, &
    &                              id_iext, id_jext, id_kext, &
@@ -619,11 +657,8 @@
 
       INTEGER(i4), DIMENSION(:,:,:)  , ALLOCATABLE :: il_detect
-      INTEGER(i4)                                  :: il_radius
-      INTEGER(i4)                                  :: il_iter
 
       TYPE(TATT)                                   :: tl_att
 
       ! loop indices
-      INTEGER(i4) :: jl
       !----------------------------------------------------------------
 
@@ -637,5 +672,4 @@
       &                                 id_rho,           &
       &                                 id_ext=(/id_iext, id_jext, id_kext/) )
-
       !2- add attribute to variable
       cl_extrap=fct_concat(td_var%c_extrap(:))
@@ -643,65 +677,50 @@
       CALL var_move_att(td_var, tl_att)
 
-      CALL logger_warn(" EXTRAP FILL: "//&
+      CALL att_clean(tl_att)
+
+      CALL logger_info(" EXTRAP FILL: "//&
          &              TRIM(fct_str(SUM(il_detect(:,:,:))))//&
          &              " point(s) to extrapolate " )
 
       !3- extrapolate
-      DO jl=1,td_var%t_dim(4)%i_len
-        
-!            td_var%d_value(:,:,:,jl)=il_detect(:,:,:)
-         il_iter=1
-         DO WHILE( ANY(il_detect(:,:,:)==1) )
-            ! change extend value to minimize number of iteration
-            il_radius=id_radius+(il_iter/id_maxiter)
-            
-            CALL logger_debug(" EXTRAP FILL VALUE: "//&
-            &              TRIM(fct_str(SUM(il_detect(:,:,:))))//&
-            &              " points to extrapolate " )
-            
-            CALL extrap__3D(td_var%d_value(:,:,:,jl), td_var%d_fill,    &
-            &               il_detect(:,:,:),                           &
-            &               cd_method, il_radius )
-               
-            il_iter=il_iter+1
-         ENDDO
-
-      ENDDO
- 
-      IF( SUM(il_detect(:,:,:)) /= 0 )THEN
-         CALL logger_warn(" EXTRAP FILL: still "//&
-         &              TRIM(fct_str(SUM(il_detect(:,:,:))))//&
-         &              " point(s) to extrapolate " )
-      ENDIF
+      CALL extrap__3D(td_var%d_value(:,:,:,:), td_var%d_fill,    &
+      &               il_detect(:,:,:),                           &
+      &               cd_method, id_radius, id_maxiter  )
 
       DEALLOCATE(il_detect)
 
    END SUBROUTINE extrap__fill_value
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine compute point to be extrapolated in 3D array.
    !> 
    !> @details 
+   !> in case of 'min_error' method:<br/>
+   !>    - compute derivative in i-, j- and k- direction
+   !>    - compute minimum error coefficient (distance to center of halo)
+   !>    - compute extrapolatd values by calculated minimum error using taylor expansion 
+   !> in case of 'dist_weight' method:<br/>
+   !>    - compute distance weight coefficient (inverse of distance to center of halo) 
+   !>    - compute extrapolatd values using Inverse Distance Weighting
    !>
    !> @author J.Paul
    !> - Nov, 2013- Initial Version
    !
-   !> @param[inout] dd_value : 3D table of variable to be extrapolated
-   !> @param[in] dd_fill : FillValue of variable
-   !> @param[inout] id_detect : table of point to extrapolate
-   !> @param[in] id_ext : number of point use to compute box 
-   !> @param[in] cd_method : extrapolation method
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[inout] dd_value  3D array of variable to be extrapolated
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[inout] id_detect array of point to extrapolate
+   !> @param[in] cd_method    extrapolation method
+   !> @param[in] id_radius    radius of the halo used to compute extrapolation
+   !-------------------------------------------------------------------
    SUBROUTINE extrap__3D( dd_value, dd_fill, id_detect,&
-   &                      cd_method, id_ext )
+   &                      cd_method, id_radius, id_maxiter )
       IMPLICIT NONE
       ! Argument
-      REAL(dp)   , DIMENSION(:,:,:), INTENT(INOUT) :: dd_value
+      REAL(dp)   , DIMENSION(:,:,:,:), INTENT(INOUT) :: dd_value
       REAL(dp)   ,                   INTENT(IN   ) :: dd_fill
       INTEGER(i4), DIMENSION(:,:,:), INTENT(INOUT) :: id_detect
       CHARACTER(LEN=*),              INTENT(IN   ) :: cd_method
-      INTEGER(i4),                   INTENT(IN   ) :: id_ext
+      INTEGER(i4),                   INTENT(IN   ) :: id_radius
+      INTEGER(i4),                   INTENT(IN   ) :: id_maxiter
 
       ! local variable
@@ -712,7 +731,11 @@
       INTEGER(i4) :: il_kmin
       INTEGER(i4) :: il_kmax
-
-      INTEGER(i4), DIMENSION(3) :: il_shape
+      INTEGER(i4) :: il_iter
+      INTEGER(i4) :: il_radius
+
+      INTEGER(i4), DIMENSION(4) :: il_shape
       INTEGER(i4), DIMENSION(3) :: il_dim
+
+      INTEGER(i4), DIMENSION(:,:,:), ALLOCATABLE :: il_detect
 
       REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_dfdx
@@ -725,187 +748,217 @@
       INTEGER(i4) :: jj
       INTEGER(i4) :: jk
+      INTEGER(i4) :: jl
       !----------------------------------------------------------------
 
       il_shape(:)=SHAPE(dd_value)
 
+      ALLOCATE( il_detect( il_shape(1), il_shape(2), il_shape(3)) )
+
       SELECT CASE(TRIM(cd_method))
-         CASE('min_error')
-
-            ALLOCATE( dl_dfdx(il_shape(1), il_shape(2), il_shape(3)) ) 
-            ALLOCATE( dl_dfdy(il_shape(1), il_shape(2), il_shape(3)) ) 
-            ALLOCATE( dl_dfdz(il_shape(1), il_shape(2), il_shape(3)) ) 
-
-
-            ! compute derivative in i-direction
-            dl_dfdx(:,:,:)=dd_fill
-            IF( il_shape(1) > 1 )THEN
-               dl_dfdx(:,:,:)=extrap_deriv_3D( dd_value(:,:,:), dd_fill, 'I' )
-            ENDIF
-
-            ! compute derivative in i-direction
-            dl_dfdy(:,:,:)=dd_fill
-            IF( il_shape(2) > 1 )THEN
-               dl_dfdy(:,:,:)=extrap_deriv_3D( dd_value(:,:,:), dd_fill, 'J' )
-            ENDIF
-               
-            ! compute derivative in i-direction
-            dl_dfdz(:,:,:)=dd_fill
-            IF( il_shape(3) > 1 )THEN
-               dl_dfdz(:,:,:)=extrap_deriv_3D( dd_value(:,:,:), dd_fill, 'K' )
-            ENDIF
-      
-            il_dim(1)=2*id_ext+1
-            IF( il_shape(1) < 2*id_ext+1 ) il_dim(1)=1
-            il_dim(2)=2*id_ext+1
-            IF( il_shape(2) < 2*id_ext+1 ) il_dim(2)=1
-            il_dim(3)=2*id_ext+1
-            IF( il_shape(3) < 2*id_ext+1 ) il_dim(3)=1
-
-            ALLOCATE( dl_coef(il_dim(1), il_dim(2), il_dim(3)) ) 
-
-            dl_coef(:,:,:)=extrap__3D_min_error_coef(dd_value( 1:il_dim(1), &
-            &                                                  1:il_dim(2), &
-            &                                                  1:il_dim(3)))
-
-            DO jk=1,il_shape(3)
-               IF( ALL(id_detect(:,:,jk) == 0) ) CYCLE
-               DO jj=1,il_shape(2)
-                  IF( ALL(id_detect(:,jj,jk) == 0) ) CYCLE
-                  DO ji=1,il_shape(1)
-
-                     IF( id_detect(ji,jj,jk) == 1 )THEN
-                       
-                        il_imin=MAX(ji-id_ext,1)
-                        il_imax=MIN(ji+id_ext,il_shape(1))
-                        IF( il_dim(1) == 1 )THEN
-                           il_imin=ji
-                           il_imax=ji
+      CASE('min_error')
+         DO jl=1,il_shape(4)
+
+            ! intitialise table of poitn to be extrapolated
+            il_detect(:,:,:)=id_detect(:,:,:)
+
+            il_iter=1
+            DO WHILE( ANY(il_detect(:,:,:)==1) )
+               ! change extend value to minimize number of iteration
+               il_radius=id_radius+(il_iter/id_maxiter)
+
+               ALLOCATE( dl_dfdx(il_shape(1), il_shape(2), il_shape(3)) ) 
+               ALLOCATE( dl_dfdy(il_shape(1), il_shape(2), il_shape(3)) ) 
+               ALLOCATE( dl_dfdz(il_shape(1), il_shape(2), il_shape(3)) ) 
+
+               ! compute derivative in i-direction
+               dl_dfdx(:,:,:)=dd_fill
+               IF( il_shape(1) > 1 )THEN
+                  dl_dfdx(:,:,:)=extrap_deriv_3D( dd_value(:,:,:,jl), dd_fill, 'I' )
+               ENDIF
+
+               ! compute derivative in j-direction
+               dl_dfdy(:,:,:)=dd_fill
+               IF( il_shape(2) > 1 )THEN
+                  dl_dfdy(:,:,:)=extrap_deriv_3D( dd_value(:,:,:,jl), dd_fill, 'J' )
+               ENDIF
+ 
+               ! compute derivative in k-direction
+               dl_dfdz(:,:,:)=dd_fill
+               IF( il_shape(3) > 1 )THEN
+                  dl_dfdz(:,:,:)=extrap_deriv_3D( dd_value(:,:,:,jl), dd_fill, 'K' )
+               ENDIF
+ 
+               il_dim(1)=2*il_radius+1
+               IF( il_shape(1) < 2*il_radius+1 ) il_dim(1)=1
+               il_dim(2)=2*il_radius+1
+               IF( il_shape(2) < 2*il_radius+1 ) il_dim(2)=1
+               il_dim(3)=2*il_radius+1
+               IF( il_shape(3) < 2*il_radius+1 ) il_dim(3)=1
+
+               ALLOCATE( dl_coef(il_dim(1), il_dim(2), il_dim(3)) ) 
+
+               dl_coef(:,:,:)=extrap__3D_min_error_coef(dd_value( 1:il_dim(1), &
+               &                                                  1:il_dim(2), &
+               &                                                  1:il_dim(3), &
+               &                                                  jl ))
+
+               DO jk=1,il_shape(3)
+                  IF( ALL(il_detect(:,:,jk) == 0) ) CYCLE
+                  DO jj=1,il_shape(2)
+                     IF( ALL(il_detect(:,jj,jk) == 0) ) CYCLE
+                     DO ji=1,il_shape(1)
+
+                        IF( il_detect(ji,jj,jk) == 1 )THEN
+                          
+                           il_imin=MAX(ji-il_radius,1)
+                           il_imax=MIN(ji+il_radius,il_shape(1))
+                           IF( il_dim(1) == 1 )THEN
+                              il_imin=ji
+                              il_imax=ji
+                           ENDIF
+
+                           il_jmin=MAX(jj-il_radius,1)
+                           il_jmax=MIN(jj+il_radius,il_shape(2))
+                           IF( il_dim(2) == 1 )THEN
+                              il_jmin=jj
+                              il_jmax=jj
+                           ENDIF
+
+                           il_kmin=MAX(jk-il_radius,1)
+                           il_kmax=MIN(jk+il_radius,il_shape(3))
+                           IF( il_dim(3) == 1 )THEN
+                              il_kmin=jk
+                              il_kmax=jk
+                           ENDIF
+
+                           dd_value(ji,jj,jk,jl)=extrap__3D_min_error_fill( &
+                           &  dd_value( il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax,jl ), dd_fill, il_radius, &
+                           &  dl_dfdx(  il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax ), &
+                           &  dl_dfdy(  il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax ), &
+                           &  dl_dfdz(  il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax ), &
+                           &  dl_coef(:,:,:) )
+
+                           IF( dd_value(ji,jj,jk,jl) /= dd_fill )THEN
+                              il_detect(ji,jj,jk)= 0
+                           ENDIF
+
                         ENDIF
 
-                        il_jmin=MAX(jj-id_ext,1)
-                        il_jmax=MIN(jj+id_ext,il_shape(2))
-                        IF( il_dim(2) == 1 )THEN
-                           il_jmin=jj
-                           il_jmax=jj
-                        ENDIF
-
-                        il_kmin=MAX(jk-id_ext,1)
-                        il_kmax=MIN(jk+id_ext,il_shape(3))
-                        IF( il_dim(3) == 1 )THEN
-                           il_kmin=jk
-                           il_kmax=jk
-                        ENDIF
-
-                        dd_value(ji,jj,jk)=extrap__3D_min_error_fill( &
-                        &  dd_value( il_imin:il_imax, &
-                        &            il_jmin:il_jmax, &
-                        &            il_kmin:il_kmax ), dd_fill, id_ext, &
-                        &  dl_dfdx(  il_imin:il_imax, &
-                        &            il_jmin:il_jmax, &
-                        &            il_kmin:il_kmax ), &
-                        &  dl_dfdy(  il_imin:il_imax, &
-                        &            il_jmin:il_jmax, &
-                        &            il_kmin:il_kmax ), &
-                        &  dl_dfdz(  il_imin:il_imax, &
-                        &            il_jmin:il_jmax, &
-                        &            il_kmin:il_kmax ), &
-                        &  dl_coef(:,:,:) )
-
-                        IF( dd_value(ji,jj,jk) /= dd_fill )THEN
-                           id_detect(ji,jj,jk)= 0
-                        ENDIF
-
-                     ENDIF
-
+                     ENDDO
                   ENDDO
                ENDDO
+
+               DEALLOCATE( dl_dfdx )
+               DEALLOCATE( dl_dfdy )
+               DEALLOCATE( dl_dfdz )
+               DEALLOCATE( dl_coef )
+
+               il_iter=il_iter+1
             ENDDO
-
-            IF( ALLOCATED(dl_dfdx) ) DEALLOCATE( dl_dfdx )
-            IF( ALLOCATED(dl_dfdy) ) DEALLOCATE( dl_dfdy )
-            IF( ALLOCATED(dl_dfdz) ) DEALLOCATE( dl_dfdz )
-            IF( ALLOCATED(dl_coef) ) DEALLOCATE( dl_coef )
-
-         CASE DEFAULT ! 'dist_weight'
-
-            il_dim(1)=2*id_ext+1
-            IF( il_shape(1) < 2*id_ext+1 ) il_dim(1)=1
-            il_dim(2)=2*id_ext+1
-            IF( il_shape(2) < 2*id_ext+1 ) il_dim(2)=1
-            il_dim(3)=2*id_ext+1
-            IF( il_shape(3) < 2*id_ext+1 ) il_dim(3)=1
-            
-            ALLOCATE( dl_coef(il_dim(1), il_dim(2), il_dim(3)) )
-
-            dl_coef(:,:,:)=extrap__3D_dist_weight_coef(dd_value(1:il_dim(1), &
-            &                                                   1:il_dim(2), &
-            &                                                   1:il_dim(3)) )
-
-            DO jk=1,il_shape(3)
-               IF( ALL(id_detect(:,:,jk) == 0) ) CYCLE
-               DO jj=1,il_shape(2)
-                  IF( ALL(id_detect(:,jj,jk) == 0) ) CYCLE
-                  DO ji=1,il_shape(1)
-
-                     IF( id_detect(ji,jj,jk) == 1 )THEN
-                        
-                        il_imin=MAX(ji-id_ext,1)
-                        il_imax=MIN(ji+id_ext,il_shape(1))
-                        IF( il_dim(1) == 1 )THEN
-                           il_imin=ji
-                           il_imax=ji
+         ENDDO
+
+      CASE DEFAULT ! 'dist_weight'
+         DO jl=1,il_shape(4)
+
+            ! intitialise table of poitn to be extrapolated
+            il_detect(:,:,:)=id_detect(:,:,:)
+
+            il_iter=1
+            DO WHILE( ANY(il_detect(:,:,:)==1) )
+               ! change extend value to minimize number of iteration
+               il_radius=id_radius+(il_iter/id_maxiter)
+
+               il_dim(1)=2*il_radius+1
+               IF( il_shape(1) < 2*il_radius+1 ) il_dim(1)=1
+               il_dim(2)=2*il_radius+1
+               IF( il_shape(2) < 2*il_radius+1 ) il_dim(2)=1
+               il_dim(3)=2*il_radius+1
+               IF( il_shape(3) < 2*il_radius+1 ) il_dim(3)=1
+               
+               ALLOCATE( dl_coef(il_dim(1), il_dim(2), il_dim(3)) )
+
+               dl_coef(:,:,:)=extrap__3D_dist_weight_coef(dd_value(1:il_dim(1), &
+               &                                                   1:il_dim(2), &
+               &                                                   1:il_dim(3), &
+               &                                                   jl ) )
+
+               DO jk=1,il_shape(3)
+                  IF( ALL(il_detect(:,:,jk) == 0) ) CYCLE
+                  DO jj=1,il_shape(2)
+                     IF( ALL(il_detect(:,jj,jk) == 0) ) CYCLE
+                     DO ji=1,il_shape(1)
+
+                        IF( il_detect(ji,jj,jk) == 1 )THEN
+                           
+                           il_imin=MAX(ji-il_radius,1)
+                           il_imax=MIN(ji+il_radius,il_shape(1))
+                           IF( il_dim(1) == 1 )THEN
+                              il_imin=ji
+                              il_imax=ji
+                           ENDIF
+
+                           il_jmin=MAX(jj-il_radius,1)
+                           il_jmax=MIN(jj+il_radius,il_shape(2))
+                           IF( il_dim(2) == 1 )THEN
+                              il_jmin=jj
+                              il_jmax=jj
+                           ENDIF
+
+                           il_kmin=MAX(jk-il_radius,1)
+                           il_kmax=MIN(jk+il_radius,il_shape(3))
+                           IF( il_dim(3) == 1 )THEN
+                              il_kmin=jk
+                              il_kmax=jk
+                           ENDIF
+
+                           dd_value(ji,jj,jk,jl)=extrap__3D_dist_weight_fill( &
+                           &  dd_value( il_imin:il_imax, &
+                           &            il_jmin:il_jmax, &
+                           &            il_kmin:il_kmax, &
+                           &            jl), dd_fill, il_radius, &
+                           &  dl_coef(:,:,:) )
+
+                           IF( dd_value(ji,jj,jk,jl) /= dd_fill )THEN
+                              il_detect(ji,jj,jk)= 0
+                           ENDIF
+
                         ENDIF
 
-                        il_jmin=MAX(jj-id_ext,1)
-                        il_jmax=MIN(jj+id_ext,il_shape(2))
-                        IF( il_dim(2) == 1 )THEN
-                           il_jmin=jj
-                           il_jmax=jj
-                        ENDIF
-
-                        il_kmin=MAX(jk-id_ext,1)
-                        il_kmax=MIN(jk+id_ext,il_shape(3))
-                        IF( il_dim(3) == 1 )THEN
-                           il_kmin=jk
-                           il_kmax=jk
-                        ENDIF
-
-                        dd_value(ji,jj,jk)=extrap__3D_dist_weight_fill( &
-                        &  dd_value( il_imin:il_imax, &
-                        &            il_jmin:il_jmax, &
-                        &            il_kmin:il_kmax ), dd_fill, id_ext, &
-                        &  dl_coef(:,:,:) )
-
-                        IF( dd_value(ji,jj,jk) /= dd_fill )THEN
-                           id_detect(ji,jj,jk)= 0
-                        ENDIF
-
-                     ENDIF
-
+                     ENDDO
                   ENDDO
                ENDDO
+
+               DEALLOCATE( dl_coef )
+               il_iter=il_iter+1
             ENDDO
-
-            IF( ALLOCATED(dl_coef) ) DEALLOCATE( dl_coef )
-            
+         ENDDO            
       END SELECT
 
+      DEALLOCATE( il_detect )
+
    END SUBROUTINE extrap__3D
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function compute derivative of a function in i- and
-   !> j-direction
+   !> This function compute derivative of 1D array.
    !> 
    !> @details 
+   !> optionaly you could specify to take into account east west discontinuity
+   !> (-180° 180° or 0° 360° for longitude variable)
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[in] dd_value : 1D table of variable to be extrapolated
-   !> @param[in] dd_fill : FillValue of variable
-   !> @param[in] cd_dim : compute derivative on first (I) or second (J) dimension 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] dd_value     1D array of variable to be extrapolated
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] ld_discont   logical to take into account east west discontinuity 
+   !-------------------------------------------------------------------
    PURE FUNCTION extrap_deriv_1D( dd_value, dd_fill, ld_discont )
 
@@ -1003,20 +1056,22 @@
 
    END FUNCTION extrap_deriv_1D
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function compute derivative of a function in i- and
-   !> j-direction
-   !> 
+   !> This function compute derivative of 2D array.
+   !> you have to specify in which direction derivative have to be computed:
+   !> first (I) or second (J) dimension. 
+   !>
    !> @details 
+   !> optionaly you could specify to take into account east west discontinuity
+   !> (-180° 180° or 0° 360° for longitude variable)
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[in] dd_value : 2D table of variable to be extrapolated
-   !> @param[in] dd_fill : FillValue of variable
-   !> @param[in] cd_dim : compute derivative on first (I) or second (J) dimension 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] dd_value     2D array of variable to be extrapolated
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] cd_dim       compute derivative on first (I) or second (J) dimension 
+   !> @param[in] ld_discont   logical to take into account east west discontinuity 
+   !-------------------------------------------------------------------
    FUNCTION extrap_deriv_2D( dd_value, dd_fill, cd_dim, ld_discont )
 
@@ -1123,5 +1178,5 @@
             END WHERE
 
-      ENDDO
+         ENDDO
 
       CASE('J')
@@ -1187,20 +1242,22 @@
 
    END FUNCTION extrap_deriv_2D
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function compute derivative of a function in i- and
-   !> j-direction
+   !> This function compute derivative of 3D array.
+   !> you have to specify in which direction derivative have to be computed:
+   !> first (I), second (J) or third (K) dimension.
    !> 
    !> @details 
+   !> optionaly you could specify to take into account east west discontinuity
+   !> (-180° 180° or 0° 360° for longitude variable)
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[inout] dd_value : 3D table of variable to be extrapolated
-   !> @param[in] dd_fill : FillValue of variable
-   !> @param[in] cd_dim : compute derivative on first (I) second (J) or third (K) dimension   
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[inout] dd_value  3D array of variable to be extrapolated
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] cd_dim       compute derivative on first (I) second (J) or third (K) dimension   
+   !> @param[in] ld_discont   logical to take into account east west discontinuity
+   !-------------------------------------------------------------------
    PURE FUNCTION extrap_deriv_3D( dd_value, dd_fill, cd_dim, ld_discont )
 
@@ -1431,26 +1488,18 @@
 
    END FUNCTION extrap_deriv_3D
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function compute extrapolatd values by calculated minimum error using
-   !> taylor expansion
+   !> This function compute coefficient for min_error extrapolation.
    !> 
    !> @details 
+   !> coefficients are  "grid distance" to the center of the box choosed to compute
+   !> extrapolation.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[in] dd_value : 3D table of variable to be extrapolated
-   !> @param[in] dd_fill : FillValue of variable
-   !> @param[in] dd_ideriv : derivative of function in i-direction
-   !> @param[in] dd_jderiv : derivative of function in j-direction
-   !> @param[in] dd_kderiv : derivative of function in k-direction
-   !> @param[in] id_ji  : i-direction indices table
-   !> @param[in] id_jj  : j-direction indices table 
-   !> @param[in] id_ii  : i-direction indices of the point to extrapolate 
-   !> @param[in] id_ij  : j-direction indices of the point to extrapolate
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] dd_value  3D array of variable to be extrapolated
+   !> @return 3D array of coefficient for minimum error extrapolation
+   !-------------------------------------------------------------------
    PURE FUNCTION extrap__3D_min_error_coef( dd_value )
 
@@ -1514,24 +1563,22 @@
 
    END FUNCTION extrap__3D_min_error_coef
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function compute extrapolatd values by calculated minimum error using
+   !> This function compute extrapolatd value by calculated minimum error using
    !> taylor expansion
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_value : 3D table of variable to be extrapolated
-   !> @param[in] dd_fill : FillValue of variable
-   !> @param[in] dd_dfdx : derivative of function in i-direction
-   !> @param[in] dd_dfdy : derivative of function in j-direction
-   !> @param[in] dd_dfdz : derivative of function in k-direction
-   !> @param[in] dd_coef : 
-   !-------------------------------------------------------------------
-   !> @code
-   PURE FUNCTION extrap__3D_min_error_fill( dd_value, dd_fill, id_ext, &
+   !> @param[in] dd_value  3D array of variable to be extrapolated
+   !> @param[in] dd_fill   FillValue of variable
+   !> @param[in] id_radius radius of the halo used to compute extrapolation
+   !> @param[in] dd_dfdx   derivative of function in i-direction
+   !> @param[in] dd_dfdy   derivative of function in j-direction
+   !> @param[in] dd_dfdz   derivative of function in k-direction
+   !> @param[in] dd_coef   array of coefficient for min_error extrapolation 
+   !> @return extrapolatd value
+   !-------------------------------------------------------------------
+   PURE FUNCTION extrap__3D_min_error_fill( dd_value, dd_fill, id_radius, &
    &                                        dd_dfdx, dd_dfdy, dd_dfdz, &
    &                                        dd_coef )
@@ -1540,5 +1587,5 @@
       REAL(dp)   , DIMENSION(:,:,:), INTENT(IN) :: dd_value
       REAL(dp)   ,                   INTENT(IN) :: dd_fill
-      INTEGER(i4),                   INTENT(IN) :: id_ext
+      INTEGER(i4),                   INTENT(IN) :: id_radius
       REAL(dp)   , DIMENSION(:,:,:), INTENT(IN) :: dd_dfdx
       REAL(dp)   , DIMENSION(:,:,:), INTENT(IN) :: dd_dfdy
@@ -1564,5 +1611,5 @@
       extrap__3D_min_error_fill=dd_fill
 
-      il_min=MAX(1,(SIZE(dd_value(:,:,:)))/(1+id_ext*2))
+      il_min=MAX(1,(SIZE(dd_value(:,:,:)))/(1+id_radius*2))
 
       IF( COUNT(dd_value(:,:,:) /= dd_fill) >= il_min )THEN
@@ -1602,18 +1649,18 @@
 
    END FUNCTION extrap__3D_min_error_fill
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function compute extrapolatd values by calculated minimum error using
-   !> taylor expansion
+   !> This function compute coefficient for inverse distance weighted method 
    !> 
    !> @details 
+   !> coefficients are inverse "grid distance" to the center of the box choosed to compute
+   !> extrapolation.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[in] dd_value : 3D table of variable to be extrapolated
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] dd_value  3D array of variable to be extrapolated
+   !> @return 3D array of coefficient for inverse distance weighted extrapolation
+   !-------------------------------------------------------------------
    PURE FUNCTION extrap__3D_dist_weight_coef( dd_value )
 
@@ -1677,27 +1724,27 @@
 
    END FUNCTION extrap__3D_dist_weight_coef
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function compute extrapolatd values by calculated minimum error using
-   !> taylor expansion
+   !> This function compute extrapolatd value using inverse distance weighted
+   !> method
    !> 
    !> @details 
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[in] dd_value : 3D table of variable to be extrapolated
-   !> @param[in] dd_fill : FillValue of variable
-   !> @param[in] dd_coef :  
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION extrap__3D_dist_weight_fill( dd_value, dd_fill, id_ext, &
-   &                                          dd_coef )
+   !> @param[in] dd_value  3D array of variable to be extrapolated
+   !> @param[in] dd_fill   FillValue of variable
+   !> @param[in] id_radius radius of the halo used to compute extrapolation
+   !> @param[in] dd_coef   3D array of coefficient for inverse distance weighted extrapolation 
+   !> @return extrapolatd value
+   !-------------------------------------------------------------------
+   FUNCTION extrap__3D_dist_weight_fill( dd_value, dd_fill, id_radius, &
+   &                                     dd_coef )
       IMPLICIT NONE
       ! Argument
       REAL(dp)   , DIMENSION(:,:,:), INTENT(IN) :: dd_value
       REAL(dp)   ,                   INTENT(IN) :: dd_fill
-      INTEGER(i4),                   INTENT(IN) :: id_ext
+      INTEGER(i4),                   INTENT(IN) :: id_radius
       REAL(dp)   , DIMENSION(:,:,:), INTENT(IN) :: dd_coef
 
@@ -1722,5 +1769,5 @@
       extrap__3D_dist_weight_fill=dd_fill
 
-      il_min=MAX(1,(SIZE(dd_value(:,:,:)))/(1+id_ext*2))
+      il_min=MAX(1,(SIZE(dd_value(:,:,:)))/(1+id_radius*2))
 
       IF( COUNT(dd_value(:,:,:)/= dd_fill) >= il_min )THEN
@@ -1733,18 +1780,22 @@
          dl_coef(:,:,:)=0
 
-         FORALL( ji=1:il_shape(1), &
-         &       jj=1:il_shape(2), &
-         &       jk=1:il_shape(3), &
-         &       dd_value(ji,jj,jk) /= dd_fill )
-
-            ! compute factor
-            dl_value(ji,jj,jk)=dd_coef(ji,jj,jk)*dd_value(ji,jj,jk)
-            dl_coef(ji,jj,jk)=dd_coef(ji,jj,jk)
-
-         END FORALL
+         DO jk=1,il_shape(3)
+            DO jj=1,il_shape(2)
+               DO ji=1,il_shape(1)
+
+                  IF( dd_value(ji,jj,jk) /= dd_fill )THEN
+                     ! compute factor
+                     dl_value(ji,jj,jk)=dd_coef(ji,jj,jk)*dd_value(ji,jj,jk)
+                     dl_coef(ji,jj,jk)=dd_coef(ji,jj,jk)
+                  ENDIF
+
+               ENDDO
+            ENDDO
+         ENDDO
 
          ! return value
          IF( SUM( dl_coef(:,:,:) ) /= 0 )THEN
-            extrap__3D_dist_weight_fill=SUM( dl_value(:,:,:) )/SUM( dl_coef(:,:,:) )
+            extrap__3D_dist_weight_fill = &
+            &  SUM( dl_value(:,:,:) )/SUM( dl_coef(:,:,:) )
          ENDIF
 
@@ -1755,5 +1806,4 @@
 
    END FUNCTION extrap__3D_dist_weight_fill
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -1761,14 +1811,16 @@
    !> extraband of N points at north,south,east and west boundaries.
    !> 
+   !> @details
+   !> optionaly you could specify size of extra bands in i- and j-direction
+   !>
    !> @author J.Paul
-   !> - 2013-Initial version
+   !> - November, 2013-Initial version
    !
-   !> @param[inout] td_var : variable 
-   !> @param[in] id_isize : i-direction size of extra bands (default=im_minext)
-   !> @param[in] id_jsize : j-direction size of extra bands (default=im_minext)
+   !> @param[inout] td_var variable 
+   !> @param[in] id_isize  i-direction size of extra bands (default=im_minext)
+   !> @param[in] id_jsize  j-direction size of extra bands (default=im_minext)
    !> @todo
    !> - invalid special case for grid with north fold
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE extrap_add_extrabands(td_var, id_isize, id_jsize )
       IMPLICIT NONE
@@ -1821,4 +1873,5 @@
       dl_value(:,:,:,:)=td_var%d_value(:,:,:,:)
 
+
       td_var%t_dim(1)%i_len = td_var%t_dim(1)%i_len + 2*il_isize
       td_var%t_dim(2)%i_len = td_var%t_dim(2)%i_len + 2*il_jsize
@@ -1855,5 +1908,4 @@
 
    END SUBROUTINE extrap_add_extrabands
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -1861,16 +1913,18 @@
    !> of N points at north,south,east and west boundaries.
    !> 
+   !> @details
+   !> optionaly you could specify size of extra bands in i- and j-direction
+   !>
    !> @author J.Paul
-   !> - 2013-Initial version
-   !
-   !> @param[inout] td_var : variable 
-   !> @param[in] id_isize : i-direction size of extra bands (default=im_minext)
-   !> @param[in] id_jsize : j-direction size of extra bands (default=im_minext)
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013-Initial version
+   !>
+   !> @param[inout] td_var variable 
+   !> @param[in] id_isize  i-direction size of extra bands (default=im_minext)
+   !> @param[in] id_jsize  j-direction size of extra bands (default=im_minext)
+   !-------------------------------------------------------------------
    SUBROUTINE extrap_del_extrabands(td_var, id_isize, id_jsize )
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(INOUT)  :: td_var
+      TYPE(TVAR) , INTENT(INOUT) :: td_var
       INTEGER(i4), INTENT(IN   ), OPTIONAL :: id_isize
       INTEGER(i4), INTENT(IN   ), OPTIONAL :: id_jsize
@@ -1881,5 +1935,5 @@
       INTEGER(i4) :: il_isize
       INTEGER(i4) :: il_jsize
-      
+ 
       INTEGER(i4) :: il_imin
       INTEGER(i4) :: il_imax
@@ -1935,50 +1989,3 @@
 
    END SUBROUTINE extrap_del_extrabands
-   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief
-!   !> This function
-!   !> 
-!   !> @details 
-!   !>
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in]
-!   !> @param[out] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   FUNCTION extrap_( )
-!      IMPLICIT NONE
-!      ! Argument
-!
-!      ! local variable
-!
-!      ! loop indices
-!      !----------------------------------------------------------------
-!   END FUNCTION extrap_
-!   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief
-!   !> This subroutine
-!   !> 
-!   !> @details 
-!   !>
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in]
-!   !> @param[out] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   SUBROUTINE extrap_( )
-!      IMPLICIT NONE
-!      ! Argument
-!
-!      ! local variable
-!
-!      ! loop indices
-!      !----------------------------------------------------------------
-!   END SUBROUTINE extrap_
-!   !> @endcode
 END MODULE extrap
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/file.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/file.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/file.f90	(revision 5075)
@@ -7,15 +7,23 @@
 !> @brief 
 !> This module manage file structure.
-!
+!>
 !> @details
-!>
 !>    define type TFILE:<br/>
-!>    TYPE(TFILE) :: tl_file<br/>
-!>
-!>    to initialise a file structure:<br/>
-!>    tl_file=file_init(cd_file [,cd_type] [,ld_wrt])
+!> @code
+!>    TYPE(TFILE) :: tl_file
+!> @endcode
+!>
+!>    to initialize a file structure:<br/>
+!> @code
+!>    tl_file=file_init(cd_file [,cd_type] [,ld_wrt] [,cd_grid])
+!%    tl_file=file_init(cd_file [,cd_type] [,ld_wrt] [,id_ew] [,id_perio] [,id_pivot] [,cd_grid])
+!> @endcode
 !>       - cd_file is the file name
-!>       - cd_type is the type of the file ('cdf', 'dimg') (optional)
-!>       - ld_wrt  file in write mode or not (optional)
+!>       - cd_type is the type of the file ('cdf', 'dimg') [optional]
+!>       - ld_wrt  file in write mode or not [optional]
+!%       - id_ew is the number of point for east-west overlap [optional]
+!%       - id_perio is the NEMO periodicity index [optional]
+!%       - id_pivot is the NEMO pivot point index F(0),T(1) [optional]
+!>       - cd_grid is the grid type (default 'ARAKAWA-C')
 !>
 !>    to get file name:<br/>
@@ -38,5 +46,5 @@
 !>    - tl_file\%i_nvar
 !>
-!>    to get the table of variable structure associated to the file:<br/>
+!>    to get the array of variable structure associated to the file:<br/>
 !>    - tl_file\%t_var(:)
 !>
@@ -45,5 +53,5 @@
 !>    - tl_file\%i_natt
 !>
-!>    to get the table of attributes structure associated to the file:<br/>
+!>    to get the array of attributes structure associated to the file:<br/>
 !>    - tl_file\%t_att(:)
 !>
@@ -52,49 +60,76 @@
 !>    - tl_file\%i_ndim
 !>
-!>    to get the table of dimension structure (4 elts) associated to the
+!>    to get the array of dimension structure (4 elts) associated to the
 !>    file:<br/>
 !>    - tl_file\%t_dim(:)
 !>
 !>    to print information about file structure:<br/>
+!> @code
 !>    CALL file_print(td_file)
+!> @endcode
+!>
+!>    to clean file structure:<br/>
+!> @code
+!>    CALL file_clean(td_file)
+!> @endcode
 !>
 !>    to add a global attribute structure in file structure:<br/>
+!> @code
 !>    CALL file_add_att(td_file, td_att)
+!> @endcode
 !>       - td_att is an attribute structure
 !>
 !>    to add a dimension structure in file structure:<br/>
+!> @code
 !>    CALL file_add_dim(td_file, td_dim)
+!> @endcode
 !>       - td_dim is a dimension structure
 !>
 !>    to add a variable structure in file structure:<br/>
+!> @code
 !>    CALL file_add_var(td_file, td_var)
+!> @endcode
 !>       - td_var is a variable structure
 !>
 !>    to delete a global attribute structure in file structure:<br/>
+!> @code
 !>    CALL file_del_att(td_file, td_att)
+!> @endcode
 !>       - td_att is an attribute structure
 !>
 !>    to delete a dimension structure in file structure:<br/>
+!> @code
 !>    CALL file_del_dim(td_file, td_dim)
+!> @endcode
 !>       - td_dim is a dimension structure
 !>
 !>    to delete a variable structure in file structure:<br/>
+!> @code
 !>    CALL file_del_var(td_file, td_var)
+!> @endcode
 !>       - td_var is a variable structure
 !>
 !>    to overwrite one attribute structure in file structure:<br/>
+!> @code
 !>    CALL file_move_att(td_file, td_att)
+!> @endcode
 !>       - td_att is an attribute structure
 !>
 !>    to  overwrite one dimension strucutre in file structure:<br/>
+!> @code
 !>    CALL file_move_dim(td_file, td_dim)
+!> @endcode
 !>       - td_dim is a dimension structure
 !>
 !>    to overwrite one variable  structure in file structure:<br/>
+!> @code
 !>    CALL file_move_var(td_file, td_var)
+!> @endcode
 !>       - td_var is a variable structure
 !> 
 !>    to check if file and variable structure share same dimension:<br/>
+!> @code
 !>    ll_check_dim = file_check_var_dim(td_file, td_var)
+!> @endcode
 !>       - td_var is a variable structure
 !>
@@ -102,10 +137,8 @@
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013- Initial Version
+!> @date November, 2013- Initial Version
+!> @date November, 2014 - Fix memory leaks bug
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
-!> - file_get_var(td_file, varname)
-!> - add description generique de l'objet file
 !----------------------------------------------------------------------
 MODULE file
@@ -113,100 +146,107 @@
    USE global                          ! global variable
    USE fct                             ! basic useful function
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE dim                             ! dimension manager
    USE att                             ! attribute manager
    USE var                             ! variable manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
-   PUBLIC :: TFILE   ! file structure
+   PUBLIC :: TFILE   !< file structure
 
    ! function and subroutine
-   PUBLIC :: ASSIGNMENT(=)   !< copy file structure
-   PUBLIC :: file_print      !< print information about file structure
-   PUBLIC :: file_clean      !< clean file structure
-   PUBLIC :: file_init       !< initialise file structure
-   PUBLIC :: file_add_att    !< add one attribute structure in file structure
-   PUBLIC :: file_add_var    !< add one variable  structure in file structure
-   PUBLIC :: file_add_dim    !< add one dimension strucutre in file structure
-   PUBLIC :: file_del_att    !< delete one attribute structure of file structure
-   PUBLIC :: file_del_var    !< delete one variable  structure of file structure
-   PUBLIC :: file_del_dim    !< delete one dimension strucutre of file structure
-   PUBLIC :: file_move_att   !< overwrite one attribute structure in file structure
-   PUBLIC :: file_move_var   !< overwrite one variable  structure in file structure
-   PUBLIC :: file_move_dim   !< overwrite one dimension strucutre in file structure
+   PUBLIC :: file_copy           !< copy file structure
+   PUBLIC :: file_print          !< print information about file structure
+   PUBLIC :: file_clean          !< clean file structure
+   PUBLIC :: file_init           !< initialize file structure
+   PUBLIC :: file_add_att        !< add one attribute structure in file structure
+   PUBLIC :: file_add_var        !< add one variable  structure in file structure
+   PUBLIC :: file_add_dim        !< add one dimension strucutre in file structure
+   PUBLIC :: file_del_att        !< delete one attribute structure of file structure
+   PUBLIC :: file_del_var        !< delete one variable  structure of file structure
+   PUBLIC :: file_del_dim        !< delete one dimension strucutre of file structure
+   PUBLIC :: file_move_att       !< overwrite one attribute structure in file structure
+   PUBLIC :: file_move_var       !< overwrite one variable  structure in file structure
+   PUBLIC :: file_move_dim       !< overwrite one dimension strucutre in file structure
    PUBLIC :: file_check_var_dim  !< check if file and variable structure use same dimension.
-   PUBLIC :: file_get_type   !< get type of file
-   PUBLIC :: file_get_id     !< get file id
-   PUBLIC :: file_rename     !< rename file name
-   PUBLIC :: file_add_suffix !< add suffix to file name
+   PUBLIC :: file_get_type       !< get type of file
+   PUBLIC :: file_get_id         !< get file id
+   PUBLIC :: file_rename         !< rename file name
+   PUBLIC :: file_add_suffix     !< add suffix to file name
  
-   PRIVATE :: file__del_var_name !< delete a variable structure in file structure, given variable name or standard name
-   PRIVATE :: file__del_var_str  !< delete a variable structure in file structure, given variable structure
-   PRIVATE :: file__del_att_name !< delete a attribute structure in file structure, given attribute name
-   PRIVATE :: file__del_att_str  !< delete a attribute structure in file structure, given attribute structure
-   PRIVATE :: file__get_number   !< get number in file name without suffix
-   PRIVATE :: file__get_suffix   !< get suffix of file name
-   PRIVATE :: file__copy_unit    !< copy file structure
-   PRIVATE :: file__copy_tab     !< copy file structure
-
-   !> @struct
-   TYPE TFILE
+   PRIVATE :: file__clean_unit    ! clean file structure
+   PRIVATE :: file__clean_arr     ! clean array of file structure
+   PRIVATE :: file__del_var_name ! delete a variable structure in file structure, given variable name or standard name
+   PRIVATE :: file__del_var_str  ! delete a variable structure in file structure, given variable structure
+   PRIVATE :: file__del_att_name ! delete a attribute structure in file structure, given attribute name
+   PRIVATE :: file__del_att_str  ! delete a attribute structure in file structure, given attribute structure
+   PRIVATE :: file__get_number   ! get number in file name without suffix
+   PRIVATE :: file__get_suffix   ! get suffix of file name
+   PRIVATE :: file__copy_unit    ! copy file structure
+   PRIVATE :: file__copy_arr     ! copy array of file structure
+   PRIVATE :: file__rename_char  ! rename file name, given processor number.
+   PRIVATE :: file__rename_str   ! rename file name, given file structure.
+
+   TYPE TFILE !< file structure
 
       ! general 
-      CHARACTER(LEN=lc)                 :: c_name = "" !< file name
-      CHARACTER(LEN=lc)                 :: c_type = "" !< type of the file (cdf, cdf4, dimg)
-      INTEGER(i4)                       :: i_id   = 0         !< file id
-      LOGICAL                           :: l_wrt  = .FALSE.   !< read or write mode
-      INTEGER(i4)                       :: i_nvar = 0         !< number of variable
-      TYPE(TVAR), DIMENSION(:), POINTER :: t_var  => NULL()   !< file variables
+      CHARACTER(LEN=lc)                 :: c_name = ""       !< file name
+      CHARACTER(LEN=lc)                 :: c_type = ""       !< type of the file (cdf, cdf4, dimg)
+      INTEGER(i4)                       :: i_id   = 0        !< file id
+      LOGICAL                           :: l_wrt  = .FALSE.  !< read or write mode
+      INTEGER(i4)                       :: i_nvar = 0        !< number of variable
+      TYPE(TVAR), DIMENSION(:), POINTER :: t_var  => NULL()  !< file variables
 
       CHARACTER(LEN=lc)                 :: c_grid = 'ARAKAWA-C' !< grid type
 
-      INTEGER(i4)                       :: i_ew    =-1   !< east-west overlap
-      INTEGER(i4)                       :: i_perio =-1   !< NEMO periodicity index
-      INTEGER(i4)                       :: i_pivot =-1   !< NEMO pivot point index F(0),T(1)
-
-      INTEGER(i4)                       :: i_depthid = 0         !< variable id of depth
-      INTEGER(i4)                       :: i_timeid  = 0         !< variable id of time
+      INTEGER(i4)                       :: i_ew    =-1       !< east-west overlap
+      INTEGER(i4)                       :: i_perio =-1       !< NEMO periodicity index
+      INTEGER(i4)                       :: i_pivot =-1       !< NEMO pivot point index F(0),T(1)
+
+      INTEGER(i4)                       :: i_depthid = 0     !< variable id of depth
+      INTEGER(i4)                       :: i_timeid  = 0     !< variable id of time
 
       ! netcdf file
-      INTEGER(i4)                       :: i_ndim  = 0        !< number of dimensions used in the file
-      INTEGER(i4)                       :: i_natt  = 0        !< number of global attributes in the file
-      INTEGER(i4)                       :: i_uldid = 0        !< id of the unlimited dimension in the file
-      LOGICAL                           :: l_def   = .FALSE.  !< define mode or not
-      TYPE(TATT), DIMENSION(:), POINTER :: t_att   => NULL()  !< global attributes
-      TYPE(TDIM), DIMENSION(ip_maxdim)  :: t_dim              !< dimension structure
+      INTEGER(i4)                       :: i_ndim  = 0       !< number of dimensions used in the file
+      INTEGER(i4)                       :: i_natt  = 0       !< number of global attributes in the file
+      INTEGER(i4)                       :: i_uldid = 0       !< id of the unlimited dimension in the file
+      LOGICAL                           :: l_def   = .FALSE. !< define mode or not
+      TYPE(TATT), DIMENSION(:), POINTER :: t_att   => NULL() !< global attributes
+      TYPE(TDIM), DIMENSION(ip_maxdim)  :: t_dim             !< dimension structure
       
       ! dimg file
-      INTEGER(i4)                       :: i_recl = 0         !< record length (binary file)
-      INTEGER(i4)                       :: i_n0d  = 0         !< number of scalar variable
-      INTEGER(i4)                       :: i_n1d  = 0         !< number of 1D variable
-      INTEGER(i4)                       :: i_n2d  = 0         !< number of 2D variable
-      INTEGER(i4)                       :: i_n3d  = 0         !< number of 3D variable
-      INTEGER(i4)                       :: i_rhd  = 0         !< record of the header infos (last record)
+      INTEGER(i4)                       :: i_recl = 0        !< record length (binary file)
+      INTEGER(i4)                       :: i_n0d  = 0        !< number of scalar variable
+      INTEGER(i4)                       :: i_n1d  = 0        !< number of 1D variable
+      INTEGER(i4)                       :: i_n2d  = 0        !< number of 2D variable
+      INTEGER(i4)                       :: i_n3d  = 0        !< number of 3D variable
+      INTEGER(i4)                       :: i_rhd  = 0        !< record of the header infos (last record)
 
       ! mpp
       ! only use for massively parallel processing
-      INTEGER(i4)                       :: i_pid  = -1        !< processor id (start to 1)
-      INTEGER(i4)                       :: i_impp = 0         !< i-indexes for mpp-subdomain left bottom
-      INTEGER(i4)                       :: i_jmpp = 0         !< j-indexes for mpp-subdomain left bottom
-      INTEGER(i4)                       :: i_lci  = 0         !< i-dimensions of subdomain
-      INTEGER(i4)                       :: i_lcj  = 0         !< j-dimensions of subdomain
-      INTEGER(i4)                       :: i_ldi  = 0         !< first indoor i-indices
-      INTEGER(i4)                       :: i_ldj  = 0         !< first indoor j-indices
-      INTEGER(i4)                       :: i_lei  = 0         !< last  indoor i-indices
-      INTEGER(i4)                       :: i_lej  = 0         !< last  indoor j-indices
-
-      LOGICAL                           :: l_ctr  = .FALSE.   !< domain is on border
-      LOGICAL                           :: l_use  = .FALSE.   !< domain is used
-
-      ! only use to draw domain decomposition when initialise with mpp_init
-      INTEGER(i4)                       :: i_iind = 0         !< i-direction indices
-      INTEGER(i4)                       :: i_jind = 0         !< j-direction indices
+      INTEGER(i4)                       :: i_pid  = -1       !< processor id (start to 1)
+      INTEGER(i4)                       :: i_impp = 0        !< i-indexes for mpp-subdomain left bottom
+      INTEGER(i4)                       :: i_jmpp = 0        !< j-indexes for mpp-subdomain left bottom
+      INTEGER(i4)                       :: i_lci  = 0        !< i-dimensions of subdomain
+      INTEGER(i4)                       :: i_lcj  = 0        !< j-dimensions of subdomain
+      INTEGER(i4)                       :: i_ldi  = 0        !< first indoor i-indices
+      INTEGER(i4)                       :: i_ldj  = 0        !< first indoor j-indices
+      INTEGER(i4)                       :: i_lei  = 0        !< last  indoor i-indices
+      INTEGER(i4)                       :: i_lej  = 0        !< last  indoor j-indices
+
+      LOGICAL                           :: l_ctr  = .FALSE.  !< domain is on border
+      LOGICAL                           :: l_use  = .FALSE.  !< domain is used
+
+      ! only use to draw domain decomposition when initialize with mpp_init
+      INTEGER(i4)                       :: i_iind = 0        !< i-direction indices
+      INTEGER(i4)                       :: i_jind = 0        !< j-direction indices
 
    END TYPE TFILE
+
+   INTERFACE file_clean
+      MODULE PROCEDURE file__clean_unit
+      MODULE PROCEDURE file__clean_arr
+   END INTERFACE file_clean
 
    INTERFACE file_del_var
@@ -225,7 +265,7 @@
    END INTERFACE file_rename
 
-    INTERFACE ASSIGNMENT(=)
-      MODULE PROCEDURE file__copy_unit   ! copy file structure
-      MODULE PROCEDURE file__copy_tab    ! copy file structure
+    INTERFACE file_copy
+      MODULE PROCEDURE file__copy_unit   
+      MODULE PROCEDURE file__copy_arr    
    END INTERFACE
 
@@ -233,8 +273,7 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This function copy file structure in another file
-   !> structure
+   !> This subroutine copy file structure in another one
    !> @details 
-   !> file variable and attribute value are copied in a temporary table, 
+   !> file variable and attribute value are copied in a temporary array, 
    !> so input and output file structure value do not point on the same 
    !> "memory cell", and so on are independant. 
@@ -242,19 +281,29 @@
    !> @note new file is assume to be closed.
    !>
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_file=file_copy(file_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>   
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[out] td_file1  : file structure
-   !> @param[in] td_file2  : file structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE file__copy_unit( td_file1, td_file2 )
+   !> - November, 2013- Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
+   !
+   !> @param[in] td_file  file structure
+   !> @return copy of input file structure
+   !-------------------------------------------------------------------
+   FUNCTION file__copy_unit( td_file )
       IMPLICIT NONE
       ! Argument
-      TYPE(TFILE), INTENT(  OUT) :: td_file1
-      TYPE(TFILE), INTENT(IN   )  :: td_file2
+      TYPE(TFILE), INTENT(IN) :: td_file
+      ! function
+      TYPE(TFILE) :: file__copy_unit
+
+      ! local variable
+      TYPE(TVAR) :: tl_var
+      TYPE(TATT) :: tl_att
 
       ! loop indices
@@ -262,78 +311,90 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace("COPY: file "//TRIM(td_file2%c_name) )
+      CALL logger_trace("FILE COPY: file "//TRIM(td_file%c_name) )
 
       ! copy file variable
-      td_file1%c_name = TRIM(td_file2%c_name)
-      td_file1%c_type = TRIM(td_file2%c_type)
+      file__copy_unit%c_name = TRIM(td_file%c_name)
+      file__copy_unit%c_type = TRIM(td_file%c_type)
       ! file1 should be closed even if file2 is opened right now
-      td_file1%i_id   = 0
-      td_file1%l_wrt  = td_file2%l_wrt
-      td_file1%i_nvar = td_file2%i_nvar
-
-      td_file1%c_grid = td_file2%c_grid
-
-      td_file1%i_ew   = td_file2%i_ew
-      td_file1%i_perio= td_file2%i_perio
-      td_file1%i_pivot= td_file2%i_pivot
+      file__copy_unit%i_id   = 0
+      file__copy_unit%l_wrt  = td_file%l_wrt
+      file__copy_unit%i_nvar = td_file%i_nvar
+
+      file__copy_unit%c_grid = td_file%c_grid
+
+      file__copy_unit%i_ew   = td_file%i_ew
+      file__copy_unit%i_perio= td_file%i_perio
+      file__copy_unit%i_pivot= td_file%i_pivot
+
+      file__copy_unit%i_depthid = td_file%i_depthid
+      file__copy_unit%i_timeid  = td_file%i_timeid
 
       ! copy variable structure
-      IF( ASSOCIATED(td_file1%t_var) ) DEALLOCATE(td_file1%t_var)
-      IF( ASSOCIATED(td_file2%t_var) .AND. td_file1%i_nvar > 0 )THEN
-         ALLOCATE( td_file1%t_var(td_file1%i_nvar) )
-         DO ji=1,td_file1%i_nvar
-            td_file1%t_var(ji) = td_file2%t_var(ji)
+      IF( ASSOCIATED(file__copy_unit%t_var) )THEN
+         CALL var_clean(file__copy_unit%t_var(:))
+         DEALLOCATE(file__copy_unit%t_var)
+      ENDIF
+      IF( ASSOCIATED(td_file%t_var) .AND. file__copy_unit%i_nvar > 0 )THEN
+         ALLOCATE( file__copy_unit%t_var(file__copy_unit%i_nvar) )
+         DO ji=1,file__copy_unit%i_nvar
+            tl_var = var_copy(td_file%t_var(ji))
+            file__copy_unit%t_var(ji) = var_copy(tl_var)
          ENDDO
       ENDIF
       
       ! copy netcdf variable
-      td_file1%i_ndim    = td_file2%i_ndim
-      td_file1%i_natt    = td_file2%i_natt
-      td_file1%i_uldid   = td_file2%i_uldid
-      td_file1%l_def     = td_file2%l_def
+      file__copy_unit%i_ndim   = td_file%i_ndim
+      file__copy_unit%i_natt   = td_file%i_natt
+      file__copy_unit%i_uldid  = td_file%i_uldid
+      file__copy_unit%l_def    = td_file%l_def
 
       ! copy dimension
-      td_file1%t_dim(:) = td_file2%t_dim(:)
+      file__copy_unit%t_dim(:) = dim_copy(td_file%t_dim(:))
       
       ! copy attribute structure
-      IF( ASSOCIATED(td_file1%t_att) ) DEALLOCATE(td_file1%t_att)
-      IF( ASSOCIATED(td_file2%t_att) .AND. td_file1%i_natt > 0 )THEN
-         ALLOCATE( td_file1%t_att(td_file1%i_natt) )
-         DO ji=1,td_file1%i_natt
-            td_file1%t_att(ji) = td_file2%t_att(ji)
+      IF( ASSOCIATED(file__copy_unit%t_att) )THEN
+         CALL att_clean(file__copy_unit%t_att(:))
+         DEALLOCATE(file__copy_unit%t_att)
+      ENDIF
+      IF( ASSOCIATED(td_file%t_att) .AND. file__copy_unit%i_natt > 0 )THEN
+         ALLOCATE( file__copy_unit%t_att(file__copy_unit%i_natt) )
+         DO ji=1,file__copy_unit%i_natt
+            tl_att = att_copy(td_file%t_att(ji))
+            file__copy_unit%t_att(ji) = att_copy(tl_att)
          ENDDO
       ENDIF
 
+      ! clean
+      CALL att_clean(tl_att)
+
       ! copy dimg variable
-      td_file1%i_recl = td_file2%i_recl
-      td_file1%i_n0d  = td_file2%i_n0d
-      td_file1%i_n1d  = td_file2%i_n1d
-      td_file1%i_n2d  = td_file2%i_n2d
-      td_file1%i_n3d  = td_file2%i_n3d 
-      td_file1%i_rhd  = td_file2%i_rhd
+      file__copy_unit%i_recl = td_file%i_recl
+      file__copy_unit%i_n0d  = td_file%i_n0d
+      file__copy_unit%i_n1d  = td_file%i_n1d
+      file__copy_unit%i_n2d  = td_file%i_n2d
+      file__copy_unit%i_n3d  = td_file%i_n3d 
+      file__copy_unit%i_rhd  = td_file%i_rhd
       
       ! copy mpp variable
-      td_file1%i_pid  = td_file2%i_pid
-      td_file1%i_impp = td_file2%i_impp
-      td_file1%i_jmpp = td_file2%i_jmpp
-      td_file1%i_lci  = td_file2%i_lci
-      td_file1%i_lcj  = td_file2%i_lcj
-      td_file1%i_ldi  = td_file2%i_ldi
-      td_file1%i_ldj  = td_file2%i_ldj
-      td_file1%i_lei  = td_file2%i_lei
-      td_file1%i_lej  = td_file2%i_lej
-      td_file1%l_ctr  = td_file2%l_ctr
-      td_file1%l_use  = td_file2%l_use
-      td_file1%i_iind = td_file2%i_iind
-      td_file1%i_jind = td_file2%i_jind
-
-   END SUBROUTINE file__copy_unit
-   !> @endcode
+      file__copy_unit%i_pid  = td_file%i_pid
+      file__copy_unit%i_impp = td_file%i_impp
+      file__copy_unit%i_jmpp = td_file%i_jmpp
+      file__copy_unit%i_lci  = td_file%i_lci
+      file__copy_unit%i_lcj  = td_file%i_lcj
+      file__copy_unit%i_ldi  = td_file%i_ldi
+      file__copy_unit%i_ldj  = td_file%i_ldj
+      file__copy_unit%i_lei  = td_file%i_lei
+      file__copy_unit%i_lej  = td_file%i_lej
+      file__copy_unit%l_ctr  = td_file%l_ctr
+      file__copy_unit%l_use  = td_file%l_use
+      file__copy_unit%i_iind = td_file%i_iind
+      file__copy_unit%i_jind = td_file%i_jind
+
+   END FUNCTION file__copy_unit
    !-------------------------------------------------------------------
    !> @brief
-   !> This function copy file structure in another file
-   !> structure
+   !> This subroutine copy a array of file structure in another one
    !> @details 
-   !> file variable and attribute value are copied in a temporary table, 
+   !> file variable and attribute value are copied in a temporary array, 
    !> so input and output file structure value do not point on the same 
    !> "memory cell", and so on are independant. 
@@ -341,19 +402,25 @@
    !> @note new file is assume to be closed.
    !>
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_file=file_copy(file_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>   
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[out] td_file1  : file structure
-   !> @param[in] td_file2  : file structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE file__copy_tab( td_file1, td_file2 )
+   !> - November, 2013- Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
+   !
+   !> @param[in] td_file  file structure
+   !> @return copy of input array of file structure
+   !-------------------------------------------------------------------
+   FUNCTION file__copy_arr( td_file )
       IMPLICIT NONE
       ! Argument
-      TYPE(TFILE), DIMENSION(:)                , INTENT(IN   )  :: td_file2
-      TYPE(TFILE), DIMENSION(SIZE(td_file2(:))), INTENT(  OUT) :: td_file1
+      TYPE(TFILE), DIMENSION(:)                , INTENT(IN   ) :: td_file
+      ! function
+      TYPE(TFILE), DIMENSION(SIZE(td_file(:))) :: file__copy_arr
 
       ! loop indices
@@ -361,26 +428,35 @@
       !----------------------------------------------------------------
 
-      DO ji=1,SIZE(td_file2(:))
-         td_file1(ji)=td_file2(ji)
+      DO ji=1,SIZE(td_file(:))
+         file__copy_arr(ji)=file_copy(td_file(ji))
       ENDDO
 
-   END SUBROUTINE file__copy_tab
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initialise file structure.<br/>
+   END FUNCTION file__copy_arr
+   !-------------------------------------------------------------------
+   !> @brief This function initialize file structure.<br/> 
+   !> @details
    !> If cd_type is not specify, check if file name include '.nc' or
-   !> .'dimg'<br/>
+   !> '.dimg'<br/>
+   !> Optionally, you could specify:<br/>
+   !> - write mode (default .FALSE., ld_wrt)
+   !% - East-West overlap (id_ew)
+   !% - NEMO periodicity index (id_perio)
+   !% - NEMO pivot point index F(0),T(1) (id_pivot)
+   !> - grid type (default: 'ARAKAWA-C')
    !
    !> @details
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_file : file name
-   !> @param[in] cd_type : file type ('cdf', 'dimg')
-   !> @param[in] ld_wrt  : write mode (default .FALSE.)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_file   file name
+   !> @param[in] cd_type   file type ('cdf', 'dimg')
+   !> @param[in] ld_wrt    write mode (default .FALSE.)
+   !> @param[in] id_ew     east-west overlap
+   !> @param[in] id_perio  NEMO periodicity index
+   !> @param[in] id_pivot  NEMO pivot point index F(0),T(1)
+   !> @param[in] cd_grid   grid type (default 'ARAKAWA-C')
    !> @return file structure
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TFILE) FUNCTION file_init( cd_file, cd_type, ld_wrt, &
    &                               id_ew, id_perio, id_pivot,&
@@ -397,5 +473,5 @@
 
       ! local variable
-      TYPE(TATT) :: tl_att
+      TYPE(TATT)  :: tl_att
       !----------------------------------------------------------------
 
@@ -404,12 +480,5 @@
 
       file_init%c_name=TRIM(ADJUSTL(cd_file))
-      CALL logger_trace("INIT: initialise file "//TRIM(file_init%c_name))
-
-      ! create some global attribute
-      tl_att=att_init("Conventions","CF-1.5")
-      CALL file_add_att(file_init,tl_att)
-     
-      tl_att=att_init("Grid",TRIM(file_init%c_grid))
-      CALL file_add_att(file_init,tl_att)
+      CALL logger_trace("FILE INIT: initialize file "//TRIM(file_init%c_name))
 
       ! check type
@@ -421,5 +490,5 @@
                file_init%c_type='dimg'
             CASE DEFAULT
-               CALL logger_error( " INIT: can't initialise file "//&
+               CALL logger_error( " FILE INIT: can't initialize file "//&
                &               TRIM(file_init%c_name)//" : type unknown " )
          END SELECT
@@ -427,4 +496,13 @@
          file_init%c_type=TRIM(file_get_type(cd_file))
       ENDIF
+
+      ! create some global attribute
+      IF( TRIM(file_init%c_type) == 'cdf' )THEN
+         tl_att=att_init("Conventions","CF-1.5")
+         CALL file_add_att(file_init,tl_att)
+      ENDIF
+     
+      tl_att=att_init("Grid",TRIM(file_init%c_grid))
+      CALL file_add_att(file_init,tl_att)
 
       IF( PRESENT(ld_wrt) )THEN
@@ -460,6 +538,8 @@
       ENDIF
 
+      ! clean
+      CALL att_clean(tl_att)
+
    END FUNCTION file_init
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
@@ -473,14 +553,14 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_file : file name
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_file   file name
    !> @return type of file
    !-------------------------------------------------------------------
-   !> @code
    CHARACTER(LEN=lc) FUNCTION file_get_type(cd_file)
       IMPLICIT NONE
       ! Argument      
       CHARACTER(LEN=*), INTENT(IN) :: cd_file
+
       !local variable
       CHARACTER(LEN=lc) :: cl_suffix
@@ -490,11 +570,11 @@
       SELECT CASE( TRIM(fct_lower(cl_suffix)) )
          CASE('.nc','.cdf')
-            CALL logger_debug(" GET TYPE: file "//TRIM(cd_file)//" is cdf")
+            CALL logger_debug(" FILE GET TYPE: file "//TRIM(cd_file)//" is cdf")
             file_get_type='cdf'
          CASE('.dimg')
-            CALL logger_debug(" GET TYPE: file "//TRIM(cd_file)//" is dimg" )
+            CALL logger_debug(" FILE GET TYPE: file "//TRIM(cd_file)//" is dimg" )
             file_get_type='dimg'
          CASE DEFAULT
-            CALL logger_warn(" GET TYPE: type unknown, we assume file: "//&
+            CALL logger_warn(" FILE GET TYPE: type unknown, we assume file: "//&
             &              TRIM(cd_file)//" is dimg ")
             file_get_type='dimg'
@@ -502,5 +582,4 @@
 
    END FUNCTION file_get_type
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function check if variable dimension to be used 
@@ -510,11 +589,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] td_var : variable structure
-   !> @return dimension of variable and file structure agree (or not)
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] td_var    variable structure
+   !> @return true if dimension of variable and file structure agree
+   !-------------------------------------------------------------------
    LOGICAL FUNCTION file_check_var_dim(td_file, td_var)
       IMPLICIT NONE
@@ -524,5 +602,8 @@
 
       ! local variable
-      INTEGER(i4) :: il_ndim
+      CHARACTER(LEN=lc) :: cl_dim
+      LOGICAL           :: ll_error
+
+      INTEGER(i4) :: il_ind
 
       ! loop indices
@@ -530,7 +611,21 @@
       !----------------------------------------------------------------
       file_check_var_dim=.TRUE.
+
       ! check used dimension 
-      IF( ANY( td_var%t_dim(:)%l_use .AND. &
-      &        td_var%t_dim(:)%i_len /= td_file%t_dim(:)%i_len) )THEN
+      ll_error=.FALSE.
+      DO ji=1,ip_maxdim
+         il_ind=dim_get_index( td_file%t_dim(:), &
+         &                     TRIM(td_var%t_dim(ji)%c_name), &
+         &                     TRIM(td_var%t_dim(ji)%c_sname))
+         IF( il_ind /= 0 )THEN
+         IF( td_var%t_dim(ji)%l_use  .AND. &
+         &   td_file%t_dim(il_ind)%l_use .AND. &
+         &   td_var%t_dim(ji)%i_len /= td_file%t_dim(il_ind)%i_len )THEN
+            ll_error=.TRUE.
+         ENDIF
+         ENDIF
+      ENDDO
+
+      IF( ll_error )THEN
 
          file_check_var_dim=.FALSE.
@@ -542,30 +637,37 @@
 
 
-         CALL logger_debug( &
-         &  " file dimension: "//TRIM(fct_str(td_file%i_ndim))//&
-         &  " variable dimension: "//TRIM(fct_str(td_var%i_ndim)) )
-         il_ndim=MIN(td_var%i_ndim, td_file%i_ndim )
-         DO ji = 1, il_ndim
-            CALL logger_debug( &
-            &  " FILE CHECK VAR DIM: for dimension "//&
-            &  TRIM(td_file%t_dim(ji)%c_name)//&
-            &  ", file length: "//&
-            &  TRIM(fct_str(td_file%t_dim(ji)%i_len))//&
-            &  ", variable length: "//&
-            &  TRIM(fct_str(td_var%t_dim(ji)%i_len))//&
-            &  ", variable used "//TRIM(fct_str(td_var%t_dim(ji)%l_use)))
+         cl_dim='(/'
+         DO ji = 1, td_file%i_ndim
+            IF( td_file%t_dim(ji)%l_use )THEN
+               cl_dim=TRIM(cl_dim)//&
+               &  TRIM(fct_upper(td_file%t_dim(ji)%c_sname))//':'//&
+               &  TRIM(fct_str(td_file%t_dim(ji)%i_len))//','
+            ENDIF
          ENDDO
+         cl_dim=TRIM(cl_dim)//'/)'
+         CALL logger_debug( " file dimension: "//TRIM(cl_dim) )
+
+         cl_dim='(/'
+         DO ji = 1, td_var%i_ndim
+            IF( td_var%t_dim(ji)%l_use )THEN
+               cl_dim=TRIM(cl_dim)//&
+               &  TRIM(fct_upper(td_var%t_dim(ji)%c_sname))//':'//&
+               &  TRIM(fct_str(td_var%t_dim(ji)%i_len))//','
+            ENDIF
+         ENDDO
+         cl_dim=TRIM(cl_dim)//'/)'
+         CALL logger_debug( " variable dimension: "//TRIM(cl_dim) )
+
       ELSE
-         IF( ANY( td_var%t_dim(:)%l_use .AND. &
-         &  .NOT. td_file%t_dim(:)%l_use ) )THEN
-            
-            CALL logger_info("FILE CHECK VAR DIM: variable use more dimension "//&
-            &  " than file do until now. file dimension use will change.")
-
-         ENDIF
+
+         IF( td_var%i_ndim >  td_file%i_ndim )THEN
+            CALL logger_info("FILE CHECK VAR DIM: variable "//&
+            &  TRIM(td_var%c_name)//" use more dimension than file "//&
+            &  TRIM(td_file%c_name)//" do until now.")
+         ENDIF
+
       ENDIF
 
    END FUNCTION file_check_var_dim
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine add a variable structure in a file structure.<br/>
@@ -577,14 +679,12 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_var : variable structure
-   !
-   !> @todo 
-   !> - check dimension order
-   !> - voir pour ajouter variable avec plus de dim que deja presente dans fichier
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - add dimension to file if need be
+   !> - do not reorder dimension from variable, before put in file
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_var       variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE file_add_var(td_file, td_var)
       IMPLICIT NONE
@@ -596,6 +696,5 @@
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_varid
-      INTEGER(i4) :: il_rec
+      !INTEGER(i4) :: il_rec
       INTEGER(i4) :: il_ind
 
@@ -606,9 +705,8 @@
       !----------------------------------------------------------------
       ! check if file opened
-      !IF( TRIM(td_file%c_name) == "unknown" )THEN
       IF( TRIM(td_file%c_name) == '' )THEN
 
-         CALL logger_error( " ADD VAR: structure file unknown" )
-         CALL logger_debug( " ADD VAR: you should have used file_init before "//&
+         CALL logger_error( " FILE ADD VAR: structure file unknown" )
+         CALL logger_debug( " FILE ADD VAR: you should have used file_init before "//&
          & "running file_add_var" )
 
@@ -617,17 +715,17 @@
          IF( TRIM(td_var%c_name) == '' .AND. &
          &   TRIM(td_var%c_stdname) == '' )THEN
-            CALL logger_error(" ADD VAR: variable not define ")
+            CALL logger_error(" FILE ADD VAR: variable without name ")
          ELSE
             ! check if variable already in file structure
-            il_varid=0
+            il_ind=0
             IF( ASSOCIATED(td_file%t_var) )THEN
-               il_varid=var_get_id( td_file%t_var(:), td_var%c_name,   &
-               &                                      td_var%c_stdname )
+               il_ind=var_get_index( td_file%t_var(:), td_var%c_name,   &
+               &                                       td_var%c_stdname )
             ENDIF
 
-            IF( il_varid /= 0 )THEN
+            IF( il_ind /= 0 )THEN
 
                CALL logger_error( &
-               &  " ADD VAR: variable "//TRIM(td_var%c_name)//&
+               &  " FILE ADD VAR: variable "//TRIM(td_var%c_name)//&
                &  ", standard name "//TRIM(td_var%c_stdname)//&
                &  ", already in file "//TRIM(td_file%c_name) )
@@ -641,31 +739,37 @@
             ELSE
 
-               CALL logger_info( &
-               &  " ADD VAR: add variable "//TRIM(td_var%c_name)//&
+               CALL logger_trace( &
+               &  " FILE ADD VAR: add variable "//TRIM(td_var%c_name)//&
                &  ", standard name "//TRIM(td_var%c_stdname)//&
                &  ", in file "//TRIM(td_file%c_name) )
 
-               ! if none, force to use variable dimension
-               IF( ALL( .NOT. td_file%t_dim(:)%l_use) )THEN
-                  td_file%t_dim(:)=td_var%t_dim(:)
-               ENDIF
-
                ! check used dimension 
                IF( file_check_var_dim(td_file, td_var) )THEN
 
+                  ! update dimension if need be
+                  DO ji=1,ip_maxdim
+                     IF( td_var%t_dim(ji)%l_use .AND. &
+                     &   .NOT. td_file%t_dim(ji)%l_use )THEN
+                        CALL file_add_dim(td_file,td_var%t_dim(ji))
+                     ENDIF
+                  ENDDO
+
+                  ! get index of new variable
                   SELECT CASE(td_var%i_ndim)
                      CASE(0)
                         il_ind=td_file%i_n0d+1
-                        il_rec=0
+                        !il_rec=0
                      CASE(1)
                         il_ind=td_file%i_n0d+td_file%i_n1d+1
-                        il_rec=1
+                        !il_rec=1
                      CASE(2)
                         il_ind=td_file%i_n0d+td_file%i_n1d+td_file%i_n2d+1
-                        il_rec=1
+                        !il_rec=1
                      CASE(3,4)
                         il_ind=td_file%i_n0d+td_file%i_n1d+td_file%i_n2d+td_file%i_n3d+1
-                        il_rec=td_file%t_dim(3)%i_len
+                        !il_rec=td_file%t_dim(3)%i_len
                   END SELECT
+                  CALL logger_info( &
+                     &  " FILE ADD VAR: variable index "//TRIM(fct_str(il_ind)))
 
                   IF( td_file%i_nvar > 0 )THEN
@@ -675,5 +779,5 @@
 
                         CALL logger_error( &
-                        &  " ADD VAR: not enough space to put variables "//&
+                        &  " FILE ADD VAR: not enough space to put variables "//&
                         &  "from "//TRIM(td_file%c_name)//&
                         &  " in variable structure")
@@ -682,7 +786,8 @@
 
                         ! save temporary variable of file structure
-                        tl_var(:)=td_file%t_var(:)
-
-                        DEALLOCATE( td_file%t_var )
+                        tl_var(:)=var_copy(td_file%t_var(:))
+
+                        CALL var_clean( td_file%t_var(:) )
+                        DEALLOCATE(td_file%t_var)
                         ALLOCATE( td_file%t_var(td_file%i_nvar+1), &
                         &         stat=il_status)
@@ -690,5 +795,5 @@
 
                            CALL logger_error( &
-                           &  " ADD VAR: not enough space to put variable "//&
+                           &  " FILE ADD VAR: not enough space to put variable "//&
                            &  "in file structure "//TRIM(td_file%c_name) )
 
@@ -697,18 +802,16 @@
                         ! copy variable in file before
                         ! variable with less than or equal dimension that new variable
-                        td_file%t_var( 1:il_ind-1 ) = tl_var( 1:il_ind-1 )
-
-                        ! variable with greater dimension than new variable
-                        td_file%t_var( il_ind+1 : td_file%i_nvar+1 ) = &
-                        &                 tl_var( il_ind : td_file%i_nvar )
-
-                        ! update id
-                        td_file%t_var( il_ind+1 : td_file%i_nvar+1 )%i_id = &
-                        &           tl_var( il_ind : td_file%i_nvar )%i_id + 1
-
-                        ! update record index
-                        td_file%t_var( il_ind+1 : td_file%i_nvar+1 )%i_rec = &
-                        & tl_var( il_ind : td_file%i_nvar )%i_rec + il_rec
-
+                        IF( il_ind > 1 )THEN
+                           td_file%t_var( 1:il_ind-1 ) = var_copy(tl_var(1:il_ind-1))
+                        ENDIF
+
+                        IF( il_ind < td_file%i_nvar )THEN
+                           ! variable with more dimension than new variable
+                           td_file%t_var( il_ind+1 : td_file%i_nvar+1 ) = &
+                           &        var_copy( tl_var(il_ind : td_file%i_nvar) )
+                        ENDIF
+
+                        ! clean
+                        CALL var_clean(tl_var(:))
                         DEALLOCATE(tl_var)
                      ENDIF
@@ -717,4 +820,5 @@
                   ! no variable in file structure
                      IF( ASSOCIATED(td_file%t_var) )THEN
+                        CALL var_clean(td_file%t_var(:))
                         DEALLOCATE(td_file%t_var)
                      ENDIF
@@ -723,5 +827,5 @@
 
                         CALL logger_error( &
-                        &  " ADD VAR: not enough space to put variable "//&
+                        &  " FILE ADD VAR: not enough space to put variable "//&
                         &  "in file structure "//TRIM(td_file%c_name) )
 
@@ -730,13 +834,14 @@
                   ENDIF
 
+                  ! add new variable in array of variable
                   ALLOCATE( tl_var(1), stat=il_status )
                   IF(il_status /= 0 )THEN
 
                      CALL logger_error( &
-                     &  " ADD VAR: not enough space to put variables from "//&
+                     &  " FILE ADD VAR: not enough space to put variables from "//&
                      &  TRIM(td_var%c_name)//" in variable structure")
 
                   ELSE
-                     tl_var(1)=td_var
+                     tl_var(1)=var_copy(td_var)
 
                      ! update dimension name in new variable
@@ -744,5 +849,5 @@
                   
                      ! add new variable
-                     td_file%t_var(il_ind)=tl_var(1)
+                     td_file%t_var(il_ind)=var_copy(tl_var(1))
 
                      ! update number of variable
@@ -755,21 +860,10 @@
                         CASE(2)
                            td_file%i_n2d=td_file%i_n2d+1
-                        CASE(3)
+                        CASE(3,4)
                            td_file%i_n3d=td_file%i_n3d+1
                      END SELECT
 
                      ! update variable id
-                     td_file%t_var(il_ind)%i_id=il_ind
-
-                     ! update record header index
-                     td_file%i_rhd=td_file%i_rhd+il_rec
-
-                     ! update record index
-                     IF( il_ind > 1 )THEN
-                        td_file%t_var(il_ind)%i_rec = &
-                        &     td_file%t_var(il_ind-1)%i_rec+il_rec
-                     ELSE
-                        td_file%t_var(il_ind)%i_rec = il_rec
-                     ENDIF
+                     td_file%t_var(il_ind)%i_id=var_get_unit(td_file%t_var(:))
 
                      ! update dimension used
@@ -780,11 +874,12 @@
                         ENDIF
                      ENDDO
-                     CALL dim_reorder(td_file%t_dim(:))
+
                      ! update number of dimension
                      td_file%i_ndim=COUNT(td_file%t_dim(:)%l_use)
 
-                     DEALLOCATE( tl_var )
+                     ! clean
+                     CALL var_clean( tl_var(:) )
+                     DEALLOCATE(tl_var)
                   ENDIF
-
                ENDIF
             ENDIF
@@ -793,18 +888,14 @@
 
    END SUBROUTINE file_add_var
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine delete a variable structure 
-   !> in file structure.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name : variable name or standard name
-   !-------------------------------------------------------------------
-   !> @code
+   !> in file structure, given variable name or standard name.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] cd_name      variable name or standard name
+   !-------------------------------------------------------------------
    SUBROUTINE file__del_var_name(td_file, cd_name )
       IMPLICIT NONE
@@ -815,5 +906,5 @@
 
       ! local variable
-      INTEGER(i4)       :: il_varid
+      INTEGER(i4)       :: il_ind
       !----------------------------------------------------------------
 
@@ -821,6 +912,6 @@
       IF( TRIM(td_file%c_name) == '' )THEN
 
-         CALL logger_error( " DEL VAR NAME: file structure unknown ")
-         CALL logger_debug( " DEL VAR NAME: you should have used file_init before "//&
+         CALL logger_error( " FILE DEL VAR NAME: file structure unknown ")
+         CALL logger_debug( " FILE DEL VAR NAME: you should have used file_init before "//&
          & "running file_del_var" )
 
@@ -829,17 +920,18 @@
          IF( td_file%i_nvar /= 0 )THEN
 
-            ! get the variable id, in file variable structure
-            il_varid=0
+            ! get the variable index, in file variable structure
+            il_ind=0
             IF( ASSOCIATED(td_file%t_var) )THEN
-               il_varid=var_get_id(td_file%t_var(:), cd_name )
+               il_ind=var_get_index(td_file%t_var(:), cd_name )
             ENDIF
-            IF( il_varid /= 0 )THEN
+
+            IF( il_ind /= 0 )THEN
    
-               CALL file_del_var(td_file, td_file%t_var(il_varid))
+               CALL file_del_var(td_file, td_file%t_var(il_ind))
 
             ELSE
 
                CALL logger_warn( &
-               &  " DEL VAR NAME: there is no variable with name or "//&
+               &  " FILE DEL VAR NAME: there is no variable with name or "//&
                &  "standard name "//TRIM(cd_name)//" in file "//&
                &  TRIM(td_file%c_name))
@@ -848,6 +940,7 @@
 
          ELSE
-            CALL logger_debug( " DEL VAR NAME: no variable associated to file "//&
-            &               TRIM(td_file%c_name) )
+            CALL logger_debug( " FILE DEL VAR NAME: "//&
+            &        "no variable associated to file "//&
+            &        TRIM(td_file%c_name) )
          ENDIF
 
@@ -855,20 +948,14 @@
 
    END SUBROUTINE file__del_var_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine delete a variable structure 
    !> in file structure, given variable structure.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_var : variable structure
-   !> @todo
-   !> - verifier pose pas de souci de ne pas modifier id
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_var       variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE file__del_var_str(td_file, td_var)
       IMPLICIT NONE
@@ -880,5 +967,5 @@
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_varid
+      INTEGER(i4) :: il_ind
       INTEGER(i4) :: il_rec
       TYPE(TVAR), DIMENSION(:), ALLOCATABLE :: tl_var
@@ -889,25 +976,204 @@
 
       ! check if file opened
-      !IF( TRIM(td_file%c_name) == "unknown" )THEN
       IF( TRIM(td_file%c_name) == '' )THEN
 
-         CALL logger_error( " DEL VAR: file structure unknown ")
-         CALL logger_debug( " DEL VAR: you should have used file_init before "//&
-         & "running file_del_var" )      
+         CALL logger_error( " FILE DEL VAR: file structure unknown ")
+         CALL logger_debug( " FILE DEL VAR: you should have used "//&
+         &  "file_init before running file_del_var" )      
 
       ELSE
 
-         ! check if variable already in file structure
-         il_varid=var_get_id(td_file%t_var(:), td_var%c_name, td_var%c_stdname )
-         IF( il_varid == 0 )THEN
-
+         ! check if variable is member of a file
+         IF( td_var%l_file )THEN
+            CALL logger_warn( &
+            &  " FILE DEL VAR: variable "//TRIM(td_var%c_name)//&
+            &  ", belong to file "//TRIM(td_file%c_name)//&
+            &  " and can not be removed.")
+         ELSE
+            ! check if variable already in file structure
+            il_ind=0
+            IF( ASSOCIATED(td_file%t_var) )THEN
+               il_ind=var_get_index( td_file%t_var(:), td_var%c_name, &
+               &                                       td_var%c_stdname )
+            ENDIF
+
+            IF( il_ind == 0 )THEN
+
+               CALL logger_warn( "FILE DEL VAR: no variable "//&
+               &     TRIM(td_var%c_name)//", in file "//TRIM(td_file%c_name) )
+
+               DO ji=1,td_file%i_nvar
+                  CALL logger_debug( "FILE DEL VAR: in file "//&
+                  &  TRIM(td_file%t_var(ji)%c_name)//", standard name "//&
+                  &  TRIM(td_file%t_var(ji)%c_stdname) )
+               ENDDO
+
+            ELSE
+               
+               CALL logger_trace( "FILE DEL VAR: delete variable "//&
+               &  TRIM(td_var%c_name)//", from file "//TRIM(td_file%c_name) )
+
+               ALLOCATE( tl_var(td_file%i_nvar-1), stat=il_status )
+               IF(il_status /= 0 )THEN
+
+                  CALL logger_error( &
+                  &  " FILE DEL VAR: not enough space to put variables from "//&
+                  &  TRIM(td_file%c_name)//" in temporary variable structure")
+
+               ELSE
+
+                  ! save temporary variable's file structure
+                  IF( il_ind > 1 )THEN
+                     tl_var(1:il_ind-1)=var_copy(td_file%t_var(1:il_ind-1))
+                  ENDIF
+
+                  IF( il_ind < td_file%i_nvar )THEN
+                     tl_var(il_ind:)=var_copy(td_file%t_var(il_ind+1:))
+                  ENDIF
+
+                  ! new number of variable in file
+                  td_file%i_nvar=td_file%i_nvar-1
+
+                  SELECT CASE(td_var%i_ndim)
+                     CASE(0)
+                        td_file%i_n0d=td_file%i_n0d-1
+                        il_rec=0
+                     CASE(1)
+                        td_file%i_n1d=td_file%i_n1d-1
+                        il_rec=1
+                     CASE(2)
+                        td_file%i_n2d=td_file%i_n2d-1
+                        il_rec=1
+                     CASE(3,4)
+                        td_file%i_n3d=td_file%i_n3d-1
+                        il_rec=td_file%t_dim(3)%i_len
+                  END SELECT
+
+                  CALL var_clean( td_file%t_var(:) )
+                  DEALLOCATE(td_file%t_var)
+
+                  IF( td_file%i_nvar > 0 )THEN
+                     ALLOCATE( td_file%t_var(td_file%i_nvar), stat=il_status )
+                     IF(il_status /= 0 )THEN
+
+                        CALL logger_error( " FILE DEL VAR: not enough space"//&
+                        &  "to put variables in file structure "//&
+                        &  TRIM(td_file%c_name) )
+
+                     ENDIF
+
+                     ! copy attribute in file before
+                     td_file%t_var(:)=var_copy(tl_var(:))
+
+                     ! update dimension used
+                     td_file%t_dim(:)%l_use=.FALSE.
+                     DO ji=1,ip_maxdim
+                        IF( ANY(td_file%t_var(:)%t_dim(ji)%l_use) )THEN
+                           td_file%t_dim(ji)%l_use=.TRUE.
+                        ENDIF
+                     ENDDO
+
+                     ! update number of dimension
+                     td_file%i_ndim=COUNT(td_file%t_dim(:)%l_use)
+
+                  ENDIF
+
+                  ! clean
+                  CALL var_clean(tl_var(:))
+                  DEALLOCATE(tl_var)
+                  
+               ENDIF 
+            ENDIF
+         ENDIF
+      ENDIF
+
+   END SUBROUTINE file__del_var_str
+   !-------------------------------------------------------------------
+   !> @brief This subroutine overwrite variable structure 
+   !> in file structure.
+   !
+   !> @warning change variable id in file structure.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_var       variable structure
+   !-------------------------------------------------------------------
+   SUBROUTINE file_move_var(td_file, td_var)
+      IMPLICIT NONE
+
+      ! Argument      
+      TYPE(TFILE), INTENT(INOUT) :: td_file
+      TYPE(TVAR),  INTENT(IN)    :: td_var
+
+      ! local variable
+      TYPE(TVAR) :: tl_var
+      !----------------------------------------------------------------
+
+      ! copy variable
+      tl_var=var_copy(td_var)
+
+      ! remove variable with same name or standard name
+      CALL file_del_var(td_file, tl_var)
+
+      ! add new variable
+      CALL file_add_var(td_file, tl_var)
+
+      ! clean
+      CALL var_clean(tl_var)
+
+   END SUBROUTINE file_move_var
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add a global attribute 
+   !> in a file structure.<br/>
+   !> Do not overwrite, if attribute already in file structure.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_att       attribute structure
+   !-------------------------------------------------------------------
+   SUBROUTINE file_add_att(td_file, td_att)
+      IMPLICIT NONE
+
+      ! Argument      
+      TYPE(TFILE), INTENT(INOUT) :: td_file
+      TYPE(TATT),  INTENT(IN)    :: td_att
+
+      ! local variable
+      INTEGER(i4) :: il_status
+      INTEGER(i4) :: il_ind
+      TYPE(TATT), DIMENSION(:), ALLOCATABLE :: tl_att
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      ! check if file opened
+      IF( TRIM(td_file%c_name) == '' )THEN
+
+         CALL logger_error( " FILE ADD ATT: file structure unknown ")
+         CALL logger_debug( " FILE ADD ATT: you should have used file_init before "//&
+         & "running file_add_att" )      
+
+      ELSE
+
+         ! check if attribute already in file structure
+         il_ind=0
+         IF( ASSOCIATED(td_file%t_att) )THEN
+            il_ind=att_get_index( td_file%t_att(:), td_att%c_name )
+         ENDIF
+
+         IF( il_ind /= 0 )THEN
+         
             CALL logger_error( &
-            &  " DEL VAR: no variable "//TRIM(td_var%c_name)//&
-            &  ", in file "//TRIM(td_file%c_name) )
-
-            DO ji=1,td_file%i_nvar
+            &  " FILE ADD ATT: attribute "//TRIM(td_att%c_name)//&
+            &  ", already in file "//TRIM(td_file%c_name) )
+
+            DO ji=1,td_file%i_natt
                CALL logger_debug( &
-               &  " DEL VAR: in file "//TRIM(td_file%t_var(ji)%c_name)//&
-               &  ", standard name "//TRIM(td_file%t_var(ji)%c_stdname) )
+               &  " FILE ADD ATT: in file "//TRIM(td_file%t_att(ji)%c_name) )
             ENDDO
 
@@ -915,189 +1181,5 @@
             
             CALL logger_trace( &
-            &  " DEL VAR: delete variable "//TRIM(td_var%c_name)//&
-            &  ", from file "//TRIM(td_file%c_name) )
-
-            ALLOCATE( tl_var(td_file%i_nvar-1), stat=il_status )
-            IF(il_status /= 0 )THEN
-
-               CALL logger_error( &
-               &  " DEL VAR: not enough space to put variables from "//&
-               &  TRIM(td_file%c_name)//" in temporary variable structure")
-
-            ELSE
-
-               ! save temporary variable's file structure
-               tl_var(1:il_varid-1)=td_file%t_var(1:il_varid-1)
-               tl_var(il_varid:)=td_file%t_var(il_varid+1:)
-
-               ! new number of variable in file
-               td_file%i_nvar=td_file%i_nvar-1
-
-               SELECT CASE(td_var%i_ndim)
-                  CASE(0)
-                     td_file%i_n0d=td_file%i_n0d-1
-                     il_rec=0
-                  CASE(1)
-                     td_file%i_n1d=td_file%i_n1d-1
-                     il_rec=1
-                  CASE(2)
-                     td_file%i_n2d=td_file%i_n2d-1
-                     il_rec=1
-                  CASE(3,4)
-                     td_file%i_n3d=td_file%i_n3d-1
-                     il_rec=td_file%t_dim(3)%i_len
-               END SELECT
-
-               DEALLOCATE( td_file%t_var )
-
-               IF( td_file%i_nvar > 0 )THEN
-                  ALLOCATE( td_file%t_var(td_file%i_nvar), stat=il_status )
-                  IF(il_status /= 0 )THEN
-
-                     CALL logger_error( &
-                     &  " DEL VAR: not enough space to put variables "//&
-                     &  "in file structure "//TRIM(td_file%c_name) )
-
-                  ENDIF
-
-                  ! copy attribute in file before
-                  td_file%t_var(:)=tl_var(:)
-
-                  ! update record header index
-                  td_file%i_rhd = td_file%i_rhd - il_rec
-
-!                  ! update id
-!                  td_file%t_var( il_varid : td_file%i_nvar )%i_id = &
-!                  &     td_file%t_var( il_varid : td_file%i_nvar )%i_id - 1
-
-                  ! update record index
-                  td_file%t_var( il_varid : td_file%i_nvar )%i_rec = &
-                  &     td_file%t_var( il_varid : td_file%i_nvar )%i_rec - il_rec
-
-                  ! update dimension used
-                  td_file%t_dim(:)%l_use=.FALSE.
-                  DO ji=1,ip_maxdim
-                     IF( ANY(td_file%t_var(:)%t_dim(ji)%l_use) )THEN
-                        td_file%t_dim(ji)%l_use=.TRUE.
-                     ENDIF
-                  ENDDO
-                  CALL dim_reorder(td_file%t_dim(:))
-                  ! update number of dimension
-                  td_file%i_ndim=COUNT(td_file%t_dim(:)%l_use)
-
-               ENDIF
-               DEALLOCATE(tl_var)
-               
-            ENDIF 
-         ENDIF
-      ENDIF
-
-   END SUBROUTINE file__del_var_str
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine overwrite variable structure 
-   !> in file structure.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_var : variable structure
-   !> @todo
-   !> - check independance td_var (cf move dim variable)
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE file_move_var(td_file, td_var)
-      IMPLICIT NONE
-
-      ! Argument      
-      TYPE(TFILE), INTENT(INOUT) :: td_file
-      TYPE(TVAR),  INTENT(IN)    :: td_var
-
-      ! local variable
-      TYPE(TVAR) :: tl_var
-      INTEGER(i4):: il_varid
-      !----------------------------------------------------------------
-
-      ! copy variable
-      tl_var=td_var
-
-      IF( ASSOCIATED(td_file%t_var) )THEN
-         il_varid=var_get_id(td_file%t_var(:),TRIM(tl_var%c_name))
-         IF( il_varid /= 0 )THEN
-            ! remove variable with same name or standard name
-            CALL file_del_var(td_file, tl_var)
-         ENDIF
-      ENDIF
-
-      ! add new variable
-      CALL file_add_var(td_file, tl_var)
-
-   END SUBROUTINE file_move_var
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a global attribute 
-   !> in a file structure.<br/>
-   !> Do not overwrite, if attribute already in file structure.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_att : attribute structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE file_add_att(td_file, td_att)
-      IMPLICIT NONE
-
-      ! Argument      
-      TYPE(TFILE), INTENT(INOUT) :: td_file
-      TYPE(TATT),  INTENT(IN)    :: td_att
-
-      ! local variable
-      INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_attid
-      TYPE(TATT), DIMENSION(:), ALLOCATABLE :: tl_att
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-
-      ! check if file opened
-      !IF( TRIM(td_file%c_name) == "unknown" )THEN
-      IF( TRIM(td_file%c_name) == '' )THEN
-
-         CALL logger_error( " ADD ATT: file structure unknown ")
-         CALL logger_debug( " ADD ATT: you should have used file_init before "//&
-         & "running file_add_att" )      
-
-      ELSE
-
-         ! check if attribute already in file structure
-         il_attid=0
-         IF( ASSOCIATED(td_file%t_att) )THEN
-            il_attid=att_get_id( td_file%t_att(:), td_att%c_name )
-         ENDIF
-
-         IF( il_attid /= 0 )THEN
-         
-            CALL logger_error( &
-            &  " ADD ATT: attribute "//TRIM(td_att%c_name)//&
-            &  ", already in file "//TRIM(td_file%c_name) )
-            CALL logger_flush()
-
-            DO ji=1,td_file%i_natt
-               CALL logger_debug( &
-               &  " ADD ATT: in file "//TRIM(td_file%t_att(ji)%c_name) )
-            ENDDO
-
-         ELSE
-            
-            CALL logger_debug( &
-            &  " ADD ATT: add attribute "//TRIM(td_att%c_name)//&
+            &  " FILE ADD ATT: add attribute "//TRIM(td_att%c_name)//&
             &  ", in file "//TRIM(td_file%c_name) )
 
@@ -1108,5 +1190,5 @@
 
                   CALL logger_error( &
-                  &  " ADD ATT: not enough space to put attributes from "//&
+                  &  " FILE ADD ATT: not enough space to put attributes from "//&
                   &  TRIM(td_file%c_name)//" in temporary attribute structure")
 
@@ -1114,12 +1196,13 @@
 
                   ! save temporary global attribute's file structure
-                  tl_att(:)=td_file%t_att(:)
-
-                  DEALLOCATE( td_file%t_att )
+                  tl_att(:)=att_copy(td_file%t_att(:))
+
+                  CALL att_clean( td_file%t_att(:) )
+                  DEALLOCATE(td_file%t_att)
                   ALLOCATE( td_file%t_att(td_file%i_natt+1), stat=il_status )
                   IF(il_status /= 0 )THEN
 
                      CALL logger_error( &
-                     &  " ADD ATT: not enough space to put attributes "//&
+                     &  " FILE ADD ATT: not enough space to put attributes "//&
                      &  "in file structure "//TRIM(td_file%c_name) )
 
@@ -1127,28 +1210,29 @@
 
                   ! copy attribute in file before
-                  td_file%t_att(1:td_file%i_natt)=tl_att(:)
-
+                  td_file%t_att(1:td_file%i_natt)=att_copy(tl_att(:))
+
+                   ! clean
+                  CALL att_clean(tl_att(:))
                   DEALLOCATE(tl_att)
+
                ENDIF
             ELSE
             ! no attribute in file structure
                IF( ASSOCIATED(td_file%t_att) )THEN
+                  CALL att_clean(td_file%t_att(:))
                   DEALLOCATE(td_file%t_att)
                ENDIF
-               CALL logger_debug(" natt "//TRIM(fct_str(td_file%i_natt)) )
+
                ALLOCATE( td_file%t_att(td_file%i_natt+1), stat=il_status )
                IF(il_status /= 0 )THEN
 
                   CALL logger_error( &
-                  &  " ADD ATT: not enough space to put attributes "//&
+                  &  " FILE ADD ATT: not enough space to put attributes "//&
                   &  "in file structure "//TRIM(td_file%c_name) )
 
                ENDIF
             ENDIF
-            ! add new attributes
-            td_file%t_att(td_file%i_natt+1)=td_att
-
-            ! update attributes id
-            td_file%t_att(td_file%i_natt+1)%i_id=td_file%i_natt+1
+            ! add new attribute
+            td_file%t_att(td_file%i_natt+1)=att_copy(td_att)
 
             ! update number of attribute
@@ -1158,18 +1242,14 @@
 
    END SUBROUTINE file_add_att
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine delete a variable structure 
-   !> in file structure.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name : variable name or standard name
-   !-------------------------------------------------------------------
-   !> @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine delete a global attribute structure 
+   !> in file structure, given attribute name.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] cd_name      attribute name
+   !-------------------------------------------------------------------
    SUBROUTINE file__del_att_name(td_file, cd_name )
       IMPLICIT NONE
@@ -1180,5 +1260,5 @@
 
       ! local variable
-      INTEGER(i4)       :: il_attid
+      INTEGER(i4)       :: il_ind
       !----------------------------------------------------------------
 
@@ -1186,7 +1266,7 @@
       IF( TRIM(td_file%c_name) == '' )THEN
 
-         CALL logger_error( " DEL ATT NAME: file structure unknown ")
-         CALL logger_debug( " DEL ATT NAME: you should have used file_init before "//&
-         & "running file_del_var" )
+         CALL logger_error( " FILE DEL ATT NAME: file structure unknown ")
+         CALL logger_debug( " FILE DEL ATT NAME: you should have "//&
+         &  "used file_init before running file_del_att" )
 
       ELSE
@@ -1195,16 +1275,17 @@
 
             ! get the variable id, in file variable structure
-            il_attid=0
+            il_ind=0
             IF( ASSOCIATED(td_file%t_att) )THEN
-               il_attid=att_get_id(td_file%t_att(:), cd_name )
+               il_ind=att_get_index(td_file%t_att(:), cd_name )
             ENDIF
-            IF( il_attid /= 0 )THEN
+
+            IF( il_ind /= 0 )THEN
    
-               CALL file_del_att(td_file, td_file%t_att(il_attid))
+               CALL file_del_att(td_file, td_file%t_att(il_ind))
 
             ELSE
 
                CALL logger_warn( &
-               &  " DEL ATT NAME: there is no attribute with name "//&
+               &  " FILE DEL ATT NAME: there is no attribute with name "//&
                &  TRIM(cd_name)//" in file "//TRIM(td_file%c_name))
 
@@ -1212,6 +1293,6 @@
 
          ELSE
-            CALL logger_debug( " DEL ATT NAME: no attribute associated to file "//&
-            &               TRIM(td_file%c_name) )
+            CALL logger_debug( " FILE DEL ATT NAME: no attribute "//&
+            &  "associated to file "//TRIM(td_file%c_name) )
          ENDIF
 
@@ -1219,18 +1300,14 @@
 
    END SUBROUTINE file__del_att_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine delete a global attribute structure 
-   !> from file structure.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_att : attribute structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> from file structure, given attribute structure.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_att       attribute structure
+   !-------------------------------------------------------------------
    SUBROUTINE file__del_att_str(td_file, td_att)
       IMPLICIT NONE
@@ -1242,37 +1319,35 @@
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_attid
+      INTEGER(i4) :: il_ind
       TYPE(TATT), DIMENSION(:), ALLOCATABLE :: tl_att
 
       ! loop indices
-      INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
       ! check if file opened
-      !IF( TRIM(td_file%c_name) == "unknown" )THEN
       IF( TRIM(td_file%c_name) == '' )THEN
 
-         CALL logger_error( " DEL ATT: file structure unknown ")
-         CALL logger_debug( " DEL ATT: you should have used file_init before "//&
-         & "running file_del_att" )      
+         CALL logger_error( " FILE DEL ATT: file structure unknown ")
+         CALL logger_debug( " FILE DEL ATT: you should have used "//&
+         &  "file_init before running file_del_att" )      
 
       ELSE
 
          ! check if attribute already in file structure
-         il_attid=0
+         il_ind=0
          IF( ASSOCIATED(td_file%t_att) )THEN
-            il_attid=att_get_id( td_file%t_att(:), td_att%c_name )
-         ENDIF
-
-         IF( il_attid == 0 )THEN
+            il_ind=att_get_index( td_file%t_att(:), td_att%c_name )
+         ENDIF
+
+         IF( il_ind == 0 )THEN
 
             CALL logger_error( &
-            &  " DEL ATT: no attribute "//TRIM(td_att%c_name)//&
+            &  " FILE DEL ATT: no attribute "//TRIM(td_att%c_name)//&
             &  ", in file "//TRIM(td_file%c_name) )
 
          ELSE
             
-            CALL logger_debug( &
-            &  " DEL ATT: del attribute "//TRIM(td_att%c_name)//&
+            CALL logger_trace( &
+            &  " FILE DEL ATT: del attribute "//TRIM(td_att%c_name)//&
             &  ", in file "//TRIM(td_file%c_name) )
 
@@ -1281,5 +1356,5 @@
 
                CALL logger_error( &
-               &  " ADD ATT: not enough space to put attributes from "//&
+               &  " FILE ADD ATT: not enough space to put attributes from "//&
                &  TRIM(td_file%c_name)//" in temporary attribute structure")
 
@@ -1287,8 +1362,14 @@
 
                ! save temporary global attribute's file structure
-               tl_att(1:il_attid-1)=td_file%t_att(1:il_attid-1)
-               tl_att(il_attid:)=td_file%t_att(il_attid+1:)
-
-               DEALLOCATE( td_file%t_att )
+               IF( il_ind > 1 )THEN
+                  tl_att(1:il_ind-1)=att_copy(td_file%t_att(1:il_ind-1))
+               ENDIF
+
+               IF( il_ind < td_file%i_natt )THEN
+                  tl_att(il_ind:)=att_copy(td_file%t_att(il_ind+1:))
+               ENDIF
+
+               CALL att_clean( td_file%t_att(:) )
+               DEALLOCATE(td_file%t_att)
 
                ! new number of attribute in file
@@ -1299,5 +1380,5 @@
 
                   CALL logger_error( &
-                  &  " ADD ATT: not enough space to put attributes "//&
+                  &  " FILE ADD ATT: not enough space to put attributes "//&
                   &  "in file structure "//TRIM(td_file%c_name) )
 
@@ -1305,12 +1386,10 @@
 
                ! copy attribute in file before
-               td_file%t_att(1:td_file%i_natt)=tl_att(:)
-
-               ! update attribute id
-               DO ji=1,td_file%i_natt
-                  td_file%t_att(ji)%i_id=ji
-               ENDDO
-
+               td_file%t_att(1:td_file%i_natt)=att_copy(tl_att(:))
+
+               ! clean 
+               CALL att_clean(tl_att(:))
                DEALLOCATE(tl_att)
+
             ENDIF 
          ENDIF
@@ -1318,20 +1397,15 @@
 
    END SUBROUTINE file__del_att_str
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine move a global attribute structure 
    !> from file structure.
-   !> @note attribute id could be change
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_att : attribute structure
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
+   !> @warning change attribute id in file structure.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_att       attribute structure
+   !-------------------------------------------------------------------
    SUBROUTINE file_move_att(td_file, td_att)
       IMPLICIT NONE
@@ -1343,13 +1417,13 @@
       ! local variable
       TYPE(TATT)  :: tl_att
-      INTEGER(i4) :: il_attid
+      INTEGER(i4) :: il_ind
       !----------------------------------------------------------------
 
       ! copy attribute
-      tl_att=td_att
+      tl_att=att_copy(td_att)
 
       IF( ASSOCIATED(td_file%t_att) )THEN
-         il_attid=att_get_id(td_file%t_att(:),TRIM(tl_att%c_name))
-         IF( il_attid /= 0 )THEN
+         il_ind=att_get_index(td_file%t_att(:),TRIM(tl_att%c_name))
+         IF( il_ind /= 0 )THEN
             ! remove attribute with same name
             CALL file_del_att(td_file, tl_att)
@@ -1360,6 +1434,8 @@
       CALL file_add_att(td_file, tl_att)
 
+       ! clean
+       CALL att_clean(tl_att)
+
    END SUBROUTINE file_move_att
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine add a dimension structure in file 
@@ -1367,85 +1443,79 @@
    !> Do not overwrite, if dimension already in file structure.
    !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_dim : dimension structure
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - do not reorder dimension, before put in file
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_dim       dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE file_add_dim(td_file, td_dim)
       IMPLICIT NONE
 
       ! Argument      
-      TYPE(TFILE), INTENT(INOUT) :: td_file
-      TYPE(TDIM),  INTENT(IN)    :: td_dim
-
-      ! local variable
-      INTEGER(i4) :: il_dimid
+      TYPE(TFILE)     , INTENT(INOUT) :: td_file
+      TYPE(TDIM)      , INTENT(IN   ) :: td_dim
+
+      ! local variable
+      INTEGER(i4) :: il_ind
+
+      ! loop indices
+      INTEGER(i4) :: ji
       !----------------------------------------------------------------
       ! check if file opened
-      !IF( TRIM(td_file%c_name) == "unknown" )THEN
       IF( TRIM(td_file%c_name) == '' )THEN
 
-         CALL logger_error( " ADD DIM: file structure unknown ")
-         CALL logger_debug( " ADD DIM: you should have used file_init before "//&
-         & "running file_add_dim" )      
+         CALL logger_error( " FILE ADD DIM: file structure unknown ")
+         CALL logger_debug( " FILE ADD DIM: you should have used "//&
+         &  "file_init before running file_add_dim" )      
 
       ELSE
 
-         IF( td_file%i_ndim <= 4 )THEN
+         IF( td_file%i_ndim <= ip_maxdim )THEN
 
             ! check if dimension already in file structure
-            il_dimid=dim_get_id(td_file%t_dim(:), td_dim%c_name, td_dim%c_sname)
-            IF( il_dimid /= 0 )THEN
-
-               CALL logger_warn("ADD DIM: dimension "//TRIM(td_dim%c_name)//&
-               &  ", short name "//TRIM(td_dim%c_sname)//&
-               &  ", already in file "//TRIM(td_file%c_name) )
-
-               IF( td_file%t_dim(il_dimid)%i_len /= td_dim%i_len )THEN
+            il_ind=dim_get_index(td_file%t_dim(:), td_dim%c_sname)
+            IF( il_ind /= 0 )THEN
+               IF( td_file%t_dim(il_ind)%l_use )THEN
                   CALL logger_error( &
-                  &  "ADD DIM: dimension "//TRIM(td_dim%c_name)//&
-                  &  " already in file "//TRIM(td_file%c_name)//&
-                  &  " differ from added dimension ")
+                  &  "FILE ADD DIM: dimension "//TRIM(td_dim%c_name)//&
+                  &  ", short name "//TRIM(td_dim%c_sname)//&
+                  &  ", already used in file "//TRIM(td_file%c_name) )
+               ELSE
+                  ! replace dimension
+                  td_file%t_dim(il_ind)=dim_copy(td_dim)
+                  td_file%t_dim(il_ind)%i_id=il_ind
+                  td_file%t_dim(il_ind)%l_use=.TRUE.
                ENDIF
-
             ELSE
-
-               CALL logger_debug( &
-               &  " ADD DIM: add dimension "//TRIM(td_dim%c_name)//&
-               &  ", short name "//TRIM(td_dim%c_sname)//&
-               &  ", in file "//TRIM(td_file%c_name) )
-
-               IF( td_file%i_ndim == 4 )THEN
+               IF( td_file%i_ndim == ip_maxdim )THEN
+                  CALL logger_error( &
+                  &  "FILE ADD DIM: can not add dimension "//TRIM(td_dim%c_name)//&
+                  &  ", short name "//TRIM(td_dim%c_sname)//&
+                  &  ", in file "//TRIM(td_file%c_name)//". Already "//&
+                  &  TRIM(fct_str(ip_maxdim))//" dimensions." )
+               ELSE
                   ! search empty dimension
-                  il_dimid=dim_get_void_id(td_file%t_dim(:),TRIM(td_dim%c_name), &
-                  &                                         TRIM(td_dim%c_sname))
-                  ! replace empty dimension
-                  td_file%t_dim(il_dimid)=td_dim
-                  td_file%t_dim(il_dimid)%i_id=il_dimid
-                  td_file%t_dim(il_dimid)%l_use=.TRUE.
-               ELSE
-                  ! add new dimension
-                  il_dimid=dim_get_void_id(td_file%t_dim(:),TRIM(td_dim%c_name), &
-                  &                                         TRIM(td_dim%c_sname))
-                  td_file%t_dim(il_dimid)=td_dim
-                  td_file%t_dim(il_dimid)%i_id=td_file%i_ndim+1
-                  td_file%t_dim(il_dimid)%l_use=.TRUE.
+                  DO ji=1,ip_maxdim
+                     IF( td_file%t_dim(ji)%i_id == 0 )THEN
+                        il_ind=ji 
+                        EXIT
+                     ENDIF
+                  ENDDO
+ 
+                  ! add new dimension    
+                  td_file%t_dim(il_ind)=dim_copy(td_dim)
                   ! update number of attribute
                   td_file%i_ndim=COUNT(td_file%t_dim(:)%l_use)
-               ENDIF
-
-               ! reorder dimension to ('x','y','z','t')
-               CALL dim_reorder(td_file%t_dim)
-               
+
+                  td_file%t_dim(il_ind)%i_id=td_file%i_ndim
+                  td_file%t_dim(il_ind)%l_use=.TRUE.
+               ENDIF               
             ENDIF
+
          ELSE
             CALL logger_error( &
-            &  " ADD DIM: too much dimension in file "//&
+            &  " FILE ADD DIM: too much dimension in file "//&
             &  TRIM(td_file%c_name)//" ("//TRIM(fct_str(td_file%i_ndim))//")")
          ENDIF
@@ -1454,172 +1524,136 @@
 
    END SUBROUTINE file_add_dim
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine delete a dimension structure in file 
-   !> structure.<br/>
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_dim : dimension structure
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !> structure.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_dim       dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE file_del_dim(td_file, td_dim)
       IMPLICIT NONE
 
       ! Argument      
-      TYPE(TFILE), INTENT(INOUT) :: td_file
-      TYPE(TDIM),  INTENT(IN)    :: td_dim
+      TYPE(TFILE)     , INTENT(INOUT) :: td_file
+      TYPE(TDIM)      , INTENT(IN   ) :: td_dim
 
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_dimid
+      INTEGER(i4) :: il_ind
+
       TYPE(TDIM), DIMENSION(:), ALLOCATABLE  :: tl_dim
+
+      ! loop indices
+      INTEGER(i4) :: ji
       !----------------------------------------------------------------
       ! check if file opened
-      !IF( TRIM(td_file%c_name) == "unknown" )THEN
       IF( TRIM(td_file%c_name) == '' )THEN
 
-         CALL logger_error( " DEL DIM: file structure unknown ")
-         CALL logger_debug( " DEL DIM: you should have used file_init before "//&
-         & "running file_del_dim" )      
+         CALL logger_error( " FILE DEL DIM: file structure unknown ")
+         CALL logger_debug( " FILE DEL DIM: you should have used "//&
+         &  "file_init before running file_del_dim" )      
 
       ELSE
 
-         IF( td_file%i_ndim <= 4 )THEN
-
-            ! check if dimension already in file structure
-            il_dimid=dim_get_id(td_file%t_dim(:), td_dim%c_name, td_dim%c_sname)
-            IF( il_dimid == 0 )THEN
+         ! check if dimension already in file structure
+         il_ind=dim_get_index(td_file%t_dim(:), td_dim%c_sname)
+         IF( il_ind == 0 )THEN
+
+            CALL logger_error( &
+            &  "FILE DEL DIM: no dimension "//TRIM(td_dim%c_name)//&
+            &  ", short name "//TRIM(td_dim%c_sname)//&
+            &  ", in file "//TRIM(td_file%c_name) )
+
+         ELSE
+            ALLOCATE( tl_dim(td_file%i_ndim-1), stat=il_status )
+            IF(il_status /= 0 )THEN
 
                CALL logger_error( &
-               &  " DEL DIM: no dimension "//TRIM(td_dim%c_name)//&
-               &  ", short name "//TRIM(td_dim%c_sname)//&
-               &  ", in file "//TRIM(td_file%c_name) )
-
-            ELSE
-
-               CALL logger_debug( &
-               &  " DEL DIM: delete dimension "//TRIM(td_dim%c_name)//&
-               &  ", short name "//TRIM(td_dim%c_sname)//&
-               &  ", in file "//TRIM(td_file%c_name) )
-
-               IF( td_file%i_ndim == 4 )THEN
-                  ALLOCATE( tl_dim(1), stat=il_status )
-                  IF(il_status /= 0 )THEN
-                     CALL logger_error( &
-                     &  " DEL DIM: not enough space to put dimensions from "//&
-                     &  TRIM(td_file%c_name)//" in temporary dimension structure")
-                  ELSE
-                     ! replace dimension by empty one
-                     td_file%t_dim(il_dimid)=tl_dim(1)
-                  ENDIF
-                  DEALLOCATE(tl_dim)
-               ELSE
-                  ! 
-                  !ALLOCATE( tl_dim(td_file%i_ndim), stat=il_status )
-                  ALLOCATE( tl_dim(ip_maxdim), stat=il_status )
-                  IF(il_status /= 0 )THEN
-
-                     CALL logger_error( &
-                     &  " DEL DIM: not enough space to put dimensions from "//&
-                     &  TRIM(td_file%c_name)//" in temporary dimension structure")
-
-                  ELSE
-
-                     print *,"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
-                     print *,'il_dimid '//TRIM(fct_str(il_dimid))
-                     CALL dim_print(td_file%t_dim(:))
-                     ! save temporary dimension's file structure
-                     tl_dim( 1 : il_dimid-1 ) = td_file%t_dim( 1 : il_dimid-1 )
-                     !tl_dim( il_dimid : td_file%i_ndim-1 ) = &
-                     !&           td_file%t_dim( il_dimid+1 : td_file%i_ndim )
-                     tl_dim( il_dimid : ip_maxdim-1 ) = &
-                     &           td_file%t_dim( il_dimid+1 : ip_maxdim )
-                     print *,"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
-                     CALL dim_print(tl_dim(:))
-
-                     ! copy dimension in file, except one
-                     !td_file%t_dim(1:td_file%i_ndim)=tl_dim(:)
-                     td_file%t_dim(:)=tl_dim(:)
-                     print *,"<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"
-                     CALL dim_print(td_file%t_dim(:))
-
-                     ! update number of dimension
-                     td_file%i_ndim=td_file%i_ndim-1
-
-                  ENDIF
-               ENDIF
-
-               ! reorder dimension to ('x','y','z','t')
-               CALL dim_reorder(td_file%t_dim)
-
+               &  "FILE DEL DIM: not enough space to put dimensions from "//&
+               &  TRIM(td_file%c_name)//" in temporary dimension structure")
+
+            ELSE            
+               ! save temporary dimension's mpp structure
+               tl_dim( 1 : il_ind-1 ) = dim_copy(td_file%t_dim(1 : il_ind-1))
+               tl_dim( il_ind : td_file%i_ndim-1 ) = &
+               &      dim_copy(td_file%t_dim(il_ind+1 : td_file%i_ndim))
+
+               ! remove dimension from file
+               CALL dim_clean(td_file%t_dim(:))
+               ! copy dimension in file, except one
+               td_file%t_dim(1:td_file%i_ndim)=dim_copy(tl_dim(:))
+
+               ! update number of dimension
+               td_file%i_ndim=td_file%i_ndim-1
+
+               ! update dimension id
+               DO ji=1,td_file%i_ndim
+                  td_file%t_dim(ji)%i_id=ji
+               ENDDO
+
+               ! clean
+               CALL dim_clean(tl_dim(:))
+               DEALLOCATE(tl_dim)
             ENDIF
-         ELSE
-            CALL logger_error( &
-            &  " DEL DIM: too much dimension in file "//&
-            &  TRIM(td_file%c_name)//" ("//TRIM(fct_str(td_file%i_ndim))//")")
-         ENDIF
-
+         ENDIF
       ENDIF
 
    END SUBROUTINE file_del_dim
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine move a dimension structure 
    !> in file structure.
-   !> @warning dimension order Nov have changed
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] td_dim : dimension structure
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
+   !> @warning change dimension order in file structure. 
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] td_dim       dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE file_move_dim(td_file, td_dim)
       IMPLICIT NONE
 
       ! Argument      
-      TYPE(TFILE), INTENT(INOUT) :: td_file
-      TYPE(TDIM),  INTENT(IN)    :: td_dim
-
-      ! local variable
-      TYPE(TDIM)  :: tl_dim
+      TYPE(TFILE)     , INTENT(INOUT) :: td_file
+      TYPE(TDIM)      , INTENT(IN   ) :: td_dim
+
+      ! local variable
+      INTEGER(i4) :: il_ind
       INTEGER(i4) :: il_dimid
       !----------------------------------------------------------------
-
-      ! copy dimension
-      tl_dim=td_dim
-
-      il_dimid=dim_get_id(td_file%t_dim(:), TRIM(td_dim%c_name), &
-      &                                     TRIM(td_dim%c_sname))
-      IF( il_dimid /= 0 )THEN
-         ! remove dimension with same name
-         CALL file_del_dim(td_file, tl_dim)
-      ENDIF
-
-      ! add new dimension
-      CALL file_add_dim(td_file, tl_dim)
+      IF( td_file%i_ndim <= ip_maxdim )THEN
+
+         ! check if dimension already in mpp structure
+         il_ind=dim_get_index(td_file%t_dim(:), td_dim%c_name, td_dim%c_sname)
+         IF( il_ind /= 0 )THEN
+
+            il_dimid=td_file%t_dim(il_ind)%i_id
+            ! replace dimension
+            td_file%t_dim(il_ind)=dim_copy(td_dim)
+            td_file%t_dim(il_ind)%i_id=il_dimid
+            td_file%t_dim(il_ind)%l_use=.TRUE.
+
+         ELSE
+            CALL file_add_dim(td_file, td_dim)
+         ENDIF
+
+      ELSE
+         CALL logger_error( &
+         &  "FILE MOVE DIM: too much dimension in mpp "//&
+         &  TRIM(td_file%c_name)//" ("//TRIM(fct_str(td_file%i_ndim))//")")
+      ENDIF
 
    END SUBROUTINE file_move_dim
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine print some information about file strucutre.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE file_print(td_file)
       IMPLICIT NONE
@@ -1688,19 +1722,17 @@
 
    END SUBROUTINE file_print
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function get suffix of file name.
    !> @details
    !> we assume suffix is define as alphanumeric character following the
-   !> last '.' in file name
+   !> last '.' in file name.<br/>
    !> If no suffix is found, return empty character.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_file : file structure
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_file   file structure
    !> @return suffix
    !-------------------------------------------------------------------
-   !> @code
    CHARACTER(LEN=lc) FUNCTION file__get_suffix(cd_file)
       IMPLICIT NONE
@@ -1713,5 +1745,5 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace( "GET SUFFIX: look for suffix in file name "//&
+      CALL logger_trace( "FILE GET SUFFIX: look for suffix in file name "//&
       &               TRIM(cd_file) )
 
@@ -1721,5 +1753,5 @@
          READ( cd_file(il_ind:),'(a)' ) file__get_suffix
 
-         IF( fct_is_num(file__get_suffix) )THEN
+         IF( fct_is_num(file__get_suffix(2:)) )THEN
             file__get_suffix=''
          ENDIF
@@ -1730,18 +1762,16 @@
 
    END FUNCTION file__get_suffix
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function get number in file name without suffix.
    !> @details
    !> Actually it get the number following the last separator.
-   !> separator could be '.' or '_'
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_file : file name (without suffix)
-   !> @return file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> separator could be '.' or '_'.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_file   file name (without suffix)
+   !> @return character file number.
+   !-------------------------------------------------------------------
    CHARACTER(LEN=lc) FUNCTION file__get_number(cd_file)
       IMPLICIT NONE
@@ -1760,6 +1790,6 @@
       ! get number position in file name
       il_indmax=0
-      DO ji=1,ig_nsep
-         il_ind=INDEX(TRIM(cd_file),TRIM(cg_sep(ji)),BACK=.TRUE.)
+      DO ji=1,ip_nsep
+         il_ind=INDEX(TRIM(cd_file),TRIM(cp_sep(ji)),BACK=.TRUE.)
          IF( il_ind > il_indmax )THEN
             il_indmax=il_ind
@@ -1779,7 +1809,6 @@
 
    END FUNCTION file__get_number
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function rename file name.
+   !-------------------------------------------------------------------
+   !> @brief This function rename file name, given processor number.
    !> @details
    !> If no processor number is given, return file name without number
@@ -1787,11 +1816,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_num : processor number (start to 1)
-   !> @return file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_num    processor number (start to 1)
+   !> @return file name
+   !-------------------------------------------------------------------
    CHARACTER(LEN=lc) FUNCTION file__rename_char(cd_file, id_num)
       IMPLICIT NONE
@@ -1841,8 +1869,7 @@
          WRITE(file__rename_char,'(a,a)') TRIM(cl_base),TRIM(cl_suffix)
       ENDIF
-      CALL logger_trace(" RENAME : "//TRIM(file__rename_char))
+      CALL logger_trace(" FILE RENAME : "//TRIM(file__rename_char))
 
    END FUNCTION file__rename_char
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function rename file name, given file structure.
@@ -1852,11 +1879,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_num : processor number (start to 1)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_num    processor number (start to 1)
    !> @return file structure
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TFILE) FUNCTION file__rename_str(td_file, id_num)
       IMPLICIT NONE
@@ -1876,15 +1902,13 @@
 
    END FUNCTION file__rename_str
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function add suffix to file name.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @return file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @return file name
+   !-------------------------------------------------------------------
    CHARACTER(LEN=lc) FUNCTION file_add_suffix(cd_file, cd_type)
       IMPLICIT NONE
@@ -1918,20 +1942,18 @@
             ENDIF
          CASE DEFAULT
-            CALL logger_error( " ADD SUFFIX: type unknown "//TRIM(cd_type) )
+            CALL logger_error(" FILE ADD SUFFIX: type unknown "//TRIM(cd_type))
       END SELECT
 
    END FUNCTION file_add_suffix
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
-   !>  This subroutine clean mpp strcuture.
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE file_clean( td_file )
+   !>  This subroutine clean file strcuture.
+   !
+   !> @author J.Paul
+   !> @date November, 2013 - Inital version
+   !
+   !> @param[inout] td_file   file strcuture
+   !-------------------------------------------------------------------
+   SUBROUTINE file__clean_unit( td_file )
       IMPLICIT NONE
       ! Argument
@@ -1942,50 +1964,65 @@
 
       ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-
-      CALL logger_info( &
-      &  " CLEAN: reset file "//TRIM(td_file%c_name) )
+      !----------------------------------------------------------------
+
+      CALL logger_trace( &
+      &  " FILE CLEAN: reset file "//TRIM(td_file%c_name) )
 
       ! del attribute
       IF( ASSOCIATED( td_file%t_att ) )THEN
-         DO ji=td_file%i_natt,1,-1
-            CALL att_clean( td_file%t_att(ji) )
-         ENDDO
-         DEALLOCATE( td_file%t_att )
+         CALL att_clean( td_file%t_att(:) )
+         DEALLOCATE(td_file%t_att)
       ENDIF
 
       ! del dimension
       IF( td_file%i_ndim /= 0 )THEN
-         DO ji=td_file%i_ndim,1,-1
-            CALL dim_clean( td_file%t_dim(ji) )
-         ENDDO
+         CALL dim_clean( td_file%t_dim(:) )
       ENDIF
 
       ! del variable
       IF( ASSOCIATED( td_file%t_var ) )THEN
-         DO ji=td_file%i_nvar,1,-1
-            CALL var_clean( td_file%t_var(ji) )
-         ENDDO
-         DEALLOCATE( td_file%t_var )
+         CALL var_clean( td_file%t_var(:) )
+         DEALLOCATE(td_file%t_var)
       ENDIF
 
       ! replace by empty structure
-      td_file=tl_file
-
-   END SUBROUTINE file_clean
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function return the file id, in a table of file
-   !> structure,  given file name 
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : table of file structure
-   !> @param[in] cd_name : file name
-   !> @return file id in table of file structure (0 if not found)
-   !-------------------------------------------------------------------
-   !> @code
+      td_file=file_copy(tl_file)
+
+   END SUBROUTINE file__clean_unit
+   !-------------------------------------------------------------------
+   !> @brief 
+   !>  This subroutine clean file array of file strcuture.
+   !
+   !> @author J.Paul
+   !> @date Marsh, 2014 - Inital version
+   !
+   !> @param[inout] td_file   array file strcuture
+   !-------------------------------------------------------------------
+   SUBROUTINE file__clean_arr( td_file )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TFILE), DIMENSION(:), INTENT(INOUT) :: td_file
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      DO ji=SIZE(td_file(:)),1,-1
+         CALL file_clean(td_file(ji))
+      ENDDO
+
+   END SUBROUTINE file__clean_arr
+   !-------------------------------------------------------------------
+   !> @brief This function return the file id, in a array of file
+   !> structure,  given file name. 
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   array of file structure
+   !> @param[in] cd_name   file name
+   !> @return file id in array of file structure (0 if not found)
+   !-------------------------------------------------------------------
    INTEGER(i4) FUNCTION file_get_id(td_file, cd_name)
       IMPLICIT NONE
@@ -2003,11 +2040,10 @@
       il_size=SIZE(td_file(:))
 
-      ! check if file is in table of file structure
+      ! check if file is in array of file structure
       DO ji=1,il_size
          ! look for file name
-         CALL logger_debug(" cd_name "//TRIM(fct_lower(cd_name)) )
          IF( fct_lower(td_file(ji)%c_name) == fct_lower(cd_name) )THEN
          
-            file_get_id=ji
+            file_get_id=td_file(ji)%i_id
             EXIT
 
@@ -2016,5 +2052,28 @@
 
    END FUNCTION file_get_id
-   !> @endcode
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This function get the next unused unit in array of file structure.
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !
+   !> @param[in] td_file   array of file 
+   !-------------------------------------------------------------------
+   FUNCTION file_get_unit(td_file)
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TFILE), DIMENSION(:), INTENT(IN   ) :: td_file
+
+      ! function
+      INTEGER(i4) :: file_get_unit
+
+      ! local variable
+      ! loop indices
+      !----------------------------------------------------------------
+
+      file_get_unit=MAXVAL(td_file(:)%i_id)+1
+
+   END FUNCTION file_get_unit
 END MODULE file
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/filter.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/filter.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/filter.f90	(revision 5075)
@@ -6,20 +6,57 @@
 !
 ! DESCRIPTION:
-!> @brief filter manager <br/>
+!> @brief This module is filter manager.
 !>
-!> @details
+!> @details Filtering method to be used is specify inside variable strcuture,
+!>    as array of string character.<br/>
+!>    td_var\%c_filter(1) string character is the filter name choose between:<br/>
+!>       - 'hann'
+!>          - rad < cutoff : @f$ filter=0.5+0.5*COS(\pi*\frac{rad}{cutoff}) @f$
+!>          - rad > cutoff : @f$ filter=0 @f$
+!>       - 'hamming'
+!>          - rad < cutoff : @f$ filter=0.54+0.46*COS(\pi*\frac{rad}{cutoff}) @f$
+!>          - rad > cutoff : @f$ filter=0 @f$               
+!>       - 'blackman'
+!>          - rad < cutoff : @f$ filter=0.42 + 0.5*COS(\pi*\frac{rad}{cutoff}) + 0.08*COS(2\pi*\frac{rad}{cutoff}) @f$
+!>          - rad > cutoff : @f$ filter=0 @f$
+!>       - 'gauss'
+!>          - @f$filter=exp(-(\alpha * rad^2) / (2*cutoff^2))@f$
+!>       - 'butterworth'
+!>          - @f$ filer=1 / (1+(rad^2 / cutoff^2)^{\alpha}) @f$
+!>             .
+!>
+!>       with @f$ rad= \sqrt{(dist-radius)^2} @f$
+!>
+!>    td_var\%c_filter(2) string character is the number of turn to be done<br/>
+!>    td_var\%c_filter(3) string character is the cut-off frequency (count in number of mesh grid)<br/>
+!>    td_var\%c_filter(4) string character is the halo radius (count in number of mesh grid)<br/>
+!>    td_var\%c_filter(5) string character is the alpha parameter (for gauss and butterworth method)<br/>
+!>    
+!>    @note Filter method could be specify for each variable in namelist _namvar_,
+!>    defining string character _cn\_varinfo_. None by default.<br/>
+!>    Filter method parameters are informed inside bracket.
+!>       - @f$\alpha@f$ parameter is added for _gauss_ and _butterworth_ methods
 !> 
+!>    The number of turn is specify using '*' separator.<br/>
+!>    Example:
+!>       - cn_varinfo='varname1:2*hamming(@f$cutoff@f$,@f$radius@f$)', 'varname2:gauss(@f$cutoff@f$,@f$radius@f$,@f$\alpha@f$)'
+!>
+!>    to filter variable value:<br/>
+!> @code
+!>    CALL filter_fill_value( td_var )
+!> @endcode
+!>       - td_var is variable structure
+!>
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
 !----------------------------------------------------------------------
 MODULE filter
    USE kind                            ! F90 kind parameter
    USE phycst                          ! physical constant
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE fct                             ! basic usefull function
    use att                             ! attribute manager
@@ -27,5 +64,4 @@
    USE extrap                          ! extrapolation manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
@@ -34,17 +70,25 @@
 
    ! function and subroutine
-   PUBLIC :: filter_fill_value
-
-   PRIVATE :: filter__fill_value_wrapper
-   PRIVATE :: filter__fill_value
-   PRIVATE :: filter__3D_fill_value
-   PRIVATE :: filter__2D_fill_value
-   PRIVATE :: filter__2D
-   PRIVATE :: filter__2D_coef
-   PRIVATE :: filter__2D_hann
-   PRIVATE :: filter__2D_hamming
-   PRIVATE :: filter__2D_blackman
-   PRIVATE :: filter__2D_gauss
-   PRIVATE :: filter__2D_butterworth
+   PUBLIC :: filter_fill_value   !< filter variable value
+
+   PRIVATE :: filter__fill_value_wrapper !
+   PRIVATE :: filter__fill_value         !
+   PRIVATE :: filter__3D_fill_value      ! 
+   PRIVATE :: filter__2D_fill_value      !
+   PRIVATE :: filter__2D                 !
+   PRIVATE :: filter__2D_coef            !
+   PRIVATE :: filter__2D_hann            !
+   PRIVATE :: filter__2D_hamming         !
+   PRIVATE :: filter__2D_blackman        !
+   PRIVATE :: filter__2D_gauss           !
+   PRIVATE :: filter__2D_butterworth     !
+   PRIVATE :: filter__1D_fill_value      !
+   PRIVATE :: filter__1D                 !
+   PRIVATE :: filter__1D_coef            !
+   PRIVATE :: filter__1D_hann            !
+   PRIVATE :: filter__1D_hamming         !
+   PRIVATE :: filter__1D_blackman        !
+   PRIVATE :: filter__1D_gauss           !
+   PRIVATE :: filter__1D_butterworth     !
 
    INTERFACE filter_fill_value
@@ -55,14 +99,15 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine filtering variable value.
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable 
-   !-------------------------------------------------------------------
-   !> @code
+   !> This subroutine filter variable value.
+   !>
+   !> @details
+   !> it checks if filtering method is available,
+   !>  gets parameter value, and launch filter__fill_value 
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure 
+   !-------------------------------------------------------------------
    SUBROUTINE filter__fill_value_wrapper( td_var )
       IMPLICIT NONE
@@ -85,5 +130,5 @@
 
       IF( .NOT. ASSOCIATED(td_var%d_value) )THEN
-         CALL logger_error("FILTER FILL VALUE: no table of value "//&
+         CALL logger_error("FILTER FILL VALUE: no array of value "//&
          &  "associted to variable "//TRIM(td_var%c_name) )
       ELSE
@@ -93,5 +138,5 @@
          CASE DEFAULT
          
-            CALL logger_info("FILTER FILL VALUE: no filter selected "//&
+            CALL logger_trace("FILTER FILL VALUE: no filter selected "//&
             &  "for variable "//TRIM(td_var%c_name))
 
@@ -181,5 +226,7 @@
                tl_att=att_init('filter',cl_filter)
                CALL var_move_att(td_var,tl_att)
-               
+               ! clean
+               CALL att_clean(tl_att)
+
                DO jl=1,il_nturn
                   CALL filter__fill_value( td_var, TRIM(cl_method),  & 
@@ -192,21 +239,23 @@
       ENDIF
    END SUBROUTINE filter__fill_value_wrapper
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine filtering variable value.
+   !> This subroutine filtering variable value, given cut-off frequency
+   !> halo radius and alpha parameter.
    !> 
    !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable 
-   !> @param[in] cd_name : filter name
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter
-   !-------------------------------------------------------------------
-   !> @code
+   !>    First extrabands are added to array of variable value.
+   !>    Then values are extrapolated, before apply filter.
+   !>    Finally extrabands are removed.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable 
+   !> @param[in] cd_name   filter name
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @param[in] dd_alpha  filter parameter
+   !-------------------------------------------------------------------
    SUBROUTINE filter__fill_value( td_var, cd_name, &
    &                              dd_cutoff, id_radius, dd_alpha )
@@ -274,28 +323,31 @@
       END WHERE
 
+      ! clean
+      CALL var_clean(tl_mask)
+
       !6-remove extraband
       CALL extrap_del_extrabands(td_var, id_radius, id_radius)
 
    END SUBROUTINE filter__fill_value
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine compute filtered value of 3D table. 
-   !>
-   !> @details
-   !>
-   !> @warning table of value should have been already extrapolated before
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute filtered value of 3D array. 
+   !>
+   !> @details
+   !>    First compute filter coefficient.
+   !>    Then apply it on each level of variable value.
+   !>
+   !> @warning array of value should have been already extrapolated before
    !> running this subroutine.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] dd_value : table of value to be filtered 
-   !> @param[in] dd_fill : fill value 
-   !> @param[in] cd_name : filter name
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] dd_value  array of value to be filtered 
+   !> @param[in] dd_fill      fill value 
+   !> @param[in] cd_name      filter name
+   !> @param[in] dd_cutoff    cut-off frequency
+   !> @param[in] id_radius    filter halo radius
+   !> @param[in] dd_alpha     filter parameter
+   !-------------------------------------------------------------------
    SUBROUTINE filter__3D_fill_value( dd_value, dd_fill, cd_name, &
    &                                 dd_cutoff, id_radius, dd_alpha)
@@ -330,24 +382,24 @@
 
    END SUBROUTINE filter__3D_fill_value
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine compute filtered value of 2D table.
-   !
-   !> @details
-   !
-   !> @warning table of value should have been already extrapolated before
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute filtered value of 2D array.
+   !
+   !> @details
+   !>    First compute filter coefficient.
+   !>    Then apply it on variable value.
+   !>
+   !> @warning array of value should have been already extrapolated before
    !> running this subroutine.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] dd_value : table of value to be filtered 
-   !> @param[in] dd_fill : fill value 
-   !> @param[in] cd_name : filter name
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] dd_value  array of value to be filtered 
+   !> @param[in] dd_fill      fill value 
+   !> @param[in] cd_name      filter name
+   !> @param[in] dd_cutoff    cut-off frequency
+   !> @param[in] id_radius    filter halo radius
+   !> @param[in] dd_alpha     filter parameter
+   !-------------------------------------------------------------------
    SUBROUTINE filter__2D_fill_value( dd_value, dd_fill, cd_name, &
    &                                 dd_cutoff, id_radius, dd_alpha)
@@ -376,24 +428,24 @@
 
    END SUBROUTINE filter__2D_fill_value
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine compute filtered value of 1D table.
-   !
-   !> @details
-   !
-   !> @warning table of value should have been already extrapolated before
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute filtered value of 1D array.
+   !
+   !> @details
+   !>    First compute filter coefficient.
+   !>    Then apply it on variable value.
+   !>
+   !> @warning array of value should have been already extrapolated before
    !> running this subroutine.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] dd_value : table of value to be filtered 
-   !> @param[in] dd_fill : fill value 
-   !> @param[in] cd_name : filter name
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] dd_value  array of value to be filtered 
+   !> @param[in] dd_fill      fill value 
+   !> @param[in] cd_name      filter name
+   !> @param[in] dd_cutoff    cut-off frequency
+   !> @param[in] id_radius    filter halo radius
+   !> @param[in] dd_alpha     filter parameter
+   !-------------------------------------------------------------------
    SUBROUTINE filter__1D_fill_value( dd_value, dd_fill, cd_name, &
    &                                 dd_cutoff, id_radius, dd_alpha)
@@ -422,23 +474,19 @@
 
    END SUBROUTINE filter__1D_fill_value
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine 
-   !
-   !> @details
-   !
-   !> @note 
-   !> if fill value are detected in the computing area, 
-   !> no filtering is done.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] dd_value : table of value to be filtered 
-   !> @param[in] dd_fill : fill value 
-   !> @param[in] dd_coef :  filter coefficent table
-   !> @param[in] id_radius : filter halo radius
-   !-------------------------------------------------------------------
-   !> @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine filtered 2D array of value 
+   !>
+   !> @details
+   !>    loop on first and second dimension, 
+   !>    and apply coefficient 2D array on each point
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] dd_value  array of value to be filtered 
+   !> @param[in] dd_fill      fill value 
+   !> @param[in] dd_coef      filter coefficent array
+   !> @param[in] id_radius    filter halo radius
+   !-------------------------------------------------------------------
    SUBROUTINE filter__2D(dd_value, dd_fill, dd_coef, id_radius)
       IMPLICIT NONE
@@ -452,5 +500,5 @@
       INTEGER(i4), DIMENSION(2)                :: il_shape
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_value
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_area
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_halo
 
       ! loop indices
@@ -463,39 +511,37 @@
       dl_value(:,:)=dd_value(:,:)
 
-      ALLOCATE(dl_area(2*id_radius+1,2*id_radius+1))
+      ALLOCATE(dl_halo(2*id_radius+1,2*id_radius+1))
 
       DO jj=1+id_radius,il_shape(2)-id_radius
          DO ji=1+id_radius,il_shape(1)-id_radius
 
-            dl_area(:,:)=dd_fill
-            dl_area(:,:)=dl_value(ji-id_radius:ji+id_radius, &
+            dl_halo(:,:)=dd_fill
+            dl_halo(:,:)=dl_value(ji-id_radius:ji+id_radius, &
             &                     jj-id_radius:jj+id_radius)
 
-            IF( ALL(dl_area(:,:)/=dd_fill) )THEN
-               dd_value(ji,jj)=SUM(dl_area(:,:)*dd_coef(:,:))
-            ENDIF
+            dd_value(ji,jj)=SUM(dl_halo(:,:)*dd_coef(:,:))
 
          ENDDO
       ENDDO
 
-      DEALLOCATE(dl_area)
+      DEALLOCATE(dl_halo)
       DEALLOCATE(dl_value)
 
    END SUBROUTINE filter__2D
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine 
-   !
-   !> @details
-   !
+   !-------------------------------------------------------------------
+   !> @brief This subroutine filtered 1D array of value  
+   !
+   !> @details
+   !>    loop on first dimension, 
+   !>    and apply coefficient 1D array on each point
+   !>
    !> @author J.Paul
    !> - Nov, 2013- Initial Version
    !
-   !> @param[inout] dd_value : table of value to be filtered 
-   !> @param[in] dd_fill : fill value 
-   !> @param[in] dd_coef :  filter coefficent table
-   !> @param[in] id_radius : filter halo radius
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[inout] dd_value  array of value to be filtered 
+   !> @param[in] dd_fill      fill value 
+   !> @param[in] dd_coef      filter coefficent array
+   !> @param[in] id_radius    filter halo radius
+   !-------------------------------------------------------------------
    SUBROUTINE filter__1D(dd_value, dd_fill, dd_coef, id_radius)
       IMPLICIT NONE
@@ -507,5 +553,5 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(1)                :: il_shape
+      INTEGER(i4), DIMENSION(1)              :: il_shape
       REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_value
 
@@ -519,14 +565,8 @@
       DO ji=1+id_radius,il_shape(1)-id_radius
 
+         dl_value(:)=dd_fill
          dl_value(:)=dd_value(ji-id_radius:ji+id_radius)
 
-         IF( ANY(dl_value(:)==dd_fill) )THEN
-            CALL logger_error("FILTER FILL VALUE: fill value detected. "//&
-            &  " can't compute filtered value. "//&
-            &  "you should have extrapolate table before running "//&
-            &  " filter_fill_value")
-         ELSE
-            dd_value(ji)=SUM(dl_value(:)*dd_coef(:))
-         ENDIF
+         dd_value(ji)=SUM(dl_value(:)*dd_coef(:))
 
       ENDDO
@@ -535,5 +575,4 @@
 
    END SUBROUTINE filter__1D
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute filter coefficient. 
@@ -548,16 +587,15 @@
    !> - butterworth
    !> Cut-off frequency could be specify.
-   !> As well as a filter parameter for gauss an butterworth filter
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : filter name
-   !> @param[in] dd_cutoff : cut-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter 
-   !> @return table of filter coefficient
-   !-------------------------------------------------------------------
-   !> @code
+   !> As well as a filter parameter for gauss and butterworth filter
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name   filter name
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @param[in] dd_alpha  filter parameter 
+   !> @return array of filter coefficient
+   !-------------------------------------------------------------------
    FUNCTION filter__2D_coef(cd_name, dd_cutoff, id_radius, dd_alpha)
       IMPLICIT NONE
@@ -596,5 +634,4 @@
 
    END FUNCTION filter__2D_coef
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute filter coefficient. 
@@ -612,13 +649,12 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : filter name
-   !> @param[in] dd_cutoff : cut-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter 
-   !> @return table of filter coefficient
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name   filter name
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @param[in] dd_alpha  filter parameter 
+   !> @return array of filter coefficient
+   !-------------------------------------------------------------------
    FUNCTION filter__1D_coef(cd_name, dd_cutoff, id_radius, dd_alpha)
       IMPLICIT NONE
@@ -653,5 +689,4 @@
 
    END FUNCTION filter__1D_coef
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for HANN filter.
@@ -660,11 +695,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @return table of hann filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @return array of hann filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__1D_hann(dd_cutoff, id_radius)
       IMPLICIT NONE
@@ -695,5 +729,5 @@
             
             IF( dl_rad < dd_cutoff )THEN
-               filter__1D_hann(ji)=0.5 + 0.5*COS(dg_pi*dl_rad/dd_cutoff)
+               filter__1D_hann(ji)=0.5 + 0.5*COS(dp_pi*dl_rad/dd_cutoff)
             ELSE
                filter__1D_hann(ji)=0
@@ -709,5 +743,4 @@
 
    END FUNCTION filter__1D_hann
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for HANN filter.
@@ -716,11 +749,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @return table of hann filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @return array of hann filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__2D_hann(dd_cutoff, id_radius)
       IMPLICIT NONE
@@ -755,5 +787,5 @@
                
                IF( dl_rad < dd_cutoff )THEN
-                  filter__2D_hann(ji,jj)=0.5 + 0.5*COS(dg_pi*dl_rad/dd_cutoff)
+                  filter__2D_hann(ji,jj)=0.5 + 0.5*COS(dp_pi*dl_rad/dd_cutoff)
                ELSE
                   filter__2D_hann(ji,jj)=0
@@ -770,5 +802,4 @@
 
    END FUNCTION filter__2D_hann
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for HAMMING filter.
@@ -777,11 +808,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @return table of hamming filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @return array of hamming filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__1D_hamming(dd_cutoff, id_radius)
       IMPLICIT NONE
@@ -813,5 +843,5 @@
             IF( dl_rad < dd_cutoff )THEN
                filter__1D_hamming(ji)= 0.54 &
-               &                     + 0.46*COS(dg_pi*dl_rad/dd_cutoff)
+               &                     + 0.46*COS(dp_pi*dl_rad/dd_cutoff)
             ELSE
                filter__1D_hamming(ji)=0
@@ -827,5 +857,4 @@
 
    END FUNCTION filter__1D_hamming
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for HAMMING filter.
@@ -834,11 +863,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @return table of hamming filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @return array of hamming filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__2D_hamming(dd_cutoff, id_radius)
       IMPLICIT NONE
@@ -873,5 +901,5 @@
                IF( dl_rad < dd_cutoff )THEN
                   filter__2D_hamming(ji,jj)= 0.54 &
-                  &                        + 0.46*COS(dg_pi*dl_rad/dd_cutoff)
+                  &                        + 0.46*COS(dp_pi*dl_rad/dd_cutoff)
                ELSE
                   filter__2D_hamming(ji,jj)=0
@@ -888,5 +916,4 @@
 
    END FUNCTION filter__2D_hamming
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for BLACKMAN filter.
@@ -895,11 +922,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @return table of blackman filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @return array of blackman filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__1D_blackman(dd_cutoff, id_radius)
       IMPLICIT NONE
@@ -931,6 +957,6 @@
             IF( dl_rad < dd_cutoff )THEN
                filter__1D_blackman(ji)= 0.42 &
-               &                      + 0.5 *COS(  dg_pi*dl_rad/dd_cutoff) &
-               &                      + 0.08*COS(2*dg_pi*dl_rad/dd_cutoff)
+               &                      + 0.5 *COS(  dp_pi*dl_rad/dd_cutoff) &
+               &                      + 0.08*COS(2*dp_pi*dl_rad/dd_cutoff)
             ELSE
                filter__1D_blackman(ji)=0
@@ -946,18 +972,16 @@
 
    END FUNCTION filter__1D_blackman
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for BLACKMAN filter.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @return table of blackman filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @details
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @return array of blackman filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__2D_blackman(dd_cutoff, id_radius)
       IMPLICIT NONE
@@ -992,6 +1016,6 @@
                IF( dl_rad < dd_cutoff )THEN
                   filter__2D_blackman(ji,jj)= 0.42 &
-                  &                         + 0.5 *COS(  dg_pi*dl_rad/dd_cutoff) &
-                  &                         + 0.08*COS(2*dg_pi*dl_rad/dd_cutoff)
+                  &                         + 0.5 *COS(  dp_pi*dl_rad/dd_cutoff) &
+                  &                         + 0.08*COS(2*dp_pi*dl_rad/dd_cutoff)
                ELSE
                   filter__2D_blackman(ji,jj)=0
@@ -1008,19 +1032,17 @@
 
    END FUNCTION filter__2D_blackman
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for GAUSS filter.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter
-   !> @return table of gauss filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @details
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @param[in] dd_alpha  filter parameter
+   !> @return array of gauss filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__1D_gauss(dd_cutoff, id_radius, dd_alpha)
       IMPLICIT NONE
@@ -1062,19 +1084,17 @@
 
    END FUNCTION filter__1D_gauss
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for GAUSS filter.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter
-   !> @return table of gauss filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @details
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @param[in] dd_alpha  filter parameter
+   !> @return array of gauss filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__2D_gauss(dd_cutoff, id_radius, dd_alpha)
       IMPLICIT NONE
@@ -1120,19 +1140,17 @@
 
    END FUNCTION filter__2D_gauss
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for BUTTERWORTH filter.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter
-   !> @return table of butterworth filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @details
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @param[in] dd_alpha  filter parameter
+   !> @return array of butterworth filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__1D_butterworth(dd_cutoff, id_radius, dd_alpha)
       IMPLICIT NONE
@@ -1174,19 +1192,17 @@
 
    END FUNCTION filter__1D_butterworth
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function compute coefficient for BUTTERWORTH filter.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_cutoff : cuto-off frequency
-   !> @param[in] id_radius : filter halo radius
-   !> @param[in] dd_alpha : filter parameter
-   !> @return table of butterworth filter coefficient 
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @details
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] dd_cutoff cut-off frequency
+   !> @param[in] id_radius filter halo radius
+   !> @param[in] dd_alpha  filter parameter
+   !> @return array of butterworth filter coefficient 
+   !-------------------------------------------------------------------
    FUNCTION filter__2D_butterworth(dd_cutoff,  id_radius, dd_alpha)
       IMPLICIT NONE
@@ -1232,46 +1248,4 @@
 
    END FUNCTION filter__2D_butterworth
-   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief This function 
-!   !
-!   !> @details
-!   !
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   FUNCTION filter_()
-!      IMPLICIT NONE
-!      ! Argument      
-!      ! function
-!      ! local variable
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END FUNCTION filter_
-!   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief This subroutine 
-!   !
-!   !> @details
-!   !
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   SUBROUTINE filter_()
-!      IMPLICIT NONE
-!      ! Argument      
-!      ! local variable
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END SUBROUTINE filter_
-!   !> @endcode
 END MODULE filter
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/function.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/function.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/function.f90	(revision 5075)
@@ -7,14 +7,87 @@
 ! DESCRIPTION:
 !> @brief
-!> This module group some basic useful function
-!
+!> This module groups some basic useful function.
+!>
+!> @details
+!>  to get free I/O unit number:<br/>
+!> @code
+!>  il_id=fct_getunit()
+!> @endcode
+!>
+!>  to convert "numeric" to string character:<br/>
+!> @code
+!>  cl_string=fct_str(numeric)
+!> @endcode
+!>  - "numeric" could be integer, real, or logical
+!>
+!>  to concatenate "numeric" to a string character:<br/>
+!> @code
+!>  cl_str=cd_char//num
+!> @endcode
+!>  - cd_char is the string character
+!>  - num is the numeric value (integer, real or logical)  
+!>
+!>  to concatenate all the element of a character array:<br/> 
+!> @code
+!>  cl_string=fct_concat(cd_arr [,cd_sep])
+!> @endcode
+!>  - cd_arr is a 1D array of character
+!>  - cd_sep is a separator character to add between each element of cd_arr 
+!> [optional]
+!>
+!>  to convert character from lower to upper case:<br/>
+!> @code
+!>  cl_upper=fct_upper(cd_var)
+!> @endcode
+!>
+!>  to convert character from upper to lower case:<br/>
+!> @code
+!>  cl_lower=fct_lower(cd_var)
+!> @endcode
+!>
+!>  to check if character is numeric
+!> @code
+!>  ll_is_num=fct_is_num(cd_var)
+!> @endcode
+!>
+!>  to split string into substring and return one of the element:<br/>  
+!> @code
+!>  cl_str=fct_split(cd_string ,id_ind [,cd_sep])
+!> @endcode
+!>  - cd_string is a string of character
+!>  - id_ind is the indice of the lement to extract
+!>  - cd_sep is the separator use to split cd_string (default '|')
+!>
+!>  to get basename (name without path):<br/>
+!> @code
+!>  cl_str=fct_basename(cd_string [,cd_sep])
+!> @endcode
+!>  - cd_string is the string filename
+!>  - cd_sep is the separator ti be used (default '/')
+!>
+!>  to get dirname (path of the filename):<br/>
+!> @code
+!>  cl_str=fct_dirname(cd_string [,cd_sep])
+!> @endcode
+!>  - cd_string is the string filename
+!>  - cd_sep is the separator ti be used (default '/')
+!>  
+!> to create a pause statement:<br/>
+!> @code
+!> CALL fct_pause(cd_msg)
+!> @endcode
+!>    - cd_msg : message to be added [optional]
+!>
+!> to handle frotran error:<br/>
+!> @code
+!> CALL fct_err(id_status)
+!> @endcode
+!> 
+!> 
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
-!> @todo
-!> - TODO_describe_appropriate_changes - TODO_name
-!> @param MyModule_type : brief_description
+!> @date November, 2013 - Initial Version
+!> @date September, 2014 - add header
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -23,19 +96,19 @@
    USE kind                            ! F90 kind parameter
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! function and subroutine
-   PUBLIC :: OPERATOR(//)
-   PUBLIC :: fct_getunit! returns free unit number
-   PUBLIC :: fct_err    ! handle fortran error status
-   PUBLIC :: fct_str    ! convert numeric to string character
-   PUBLIC :: fct_concat ! concatenate all the element of a character table
-   PUBLIC :: fct_upper  ! convert lower character to upper case
-   PUBLIC :: fct_lower  ! convert upper character to lower case
-   PUBLIC :: fct_is_num ! check if character is numeric
-   PUBLIC :: fct_split  ! split string into substring
-   PUBLIC :: fct_basename ! return basename (name without path)
-   PUBLIC :: fct_dirname ! return dirname (path without name)
+   PUBLIC :: fct_getunit  !< returns free unit number
+   PUBLIC :: fct_str      !< convert numeric to string character
+   PUBLIC :: OPERATOR(//) !< concatenate operator
+   PUBLIC :: fct_concat   !< concatenate all the element of a character array
+   PUBLIC :: fct_upper    !< convert character from lower to upper case
+   PUBLIC :: fct_lower    !< convert character from upper to lower case
+   PUBLIC :: fct_is_num   !< check if character is numeric
+   PUBLIC :: fct_split    !< split string into substring
+   PUBLIC :: fct_basename !< return basename (name without path)
+   PUBLIC :: fct_dirname  !< return dirname (path without filename)
+   PUBLIC :: fct_pause    !< pause statement
+   PUBLIC :: fct_err      !< handle fortran error status
 
    PRIVATE :: fct__i1_str ! convert integer(1) to string character
@@ -46,5 +119,12 @@
    PRIVATE :: fct__r8_str ! convert real(8) to string character
    PRIVATE :: fct__l_str  ! convert logical to string character
-
+   PRIVATE :: fct__i1_cat ! concatenate integer(1) to string character
+   PRIVATE :: fct__i2_cat ! concatenate integer(2) to string character
+   PRIVATE :: fct__i4_cat ! concatenate integer(4) to string character
+   PRIVATE :: fct__i8_cat ! concatenate integer(8) to string character
+   PRIVATE :: fct__r4_cat ! concatenate real(4) to string character
+   PRIVATE :: fct__r8_cat ! concatenate real(8) to string character
+   PRIVATE :: fct__l_cat  ! concatenate logical to string character
+   PRIVATE :: fct__split_space ! split string into substring using space as separator
 
    INTERFACE fct_str
@@ -59,4 +139,6 @@
 
    INTERFACE OPERATOR(//)
+      MODULE PROCEDURE fct__i1_cat ! concatenate integer(1) to string character
+      MODULE PROCEDURE fct__i2_cat ! concatenate integer(2) to string character
       MODULE PROCEDURE fct__i4_cat ! concatenate integer(4) to string character
       MODULE PROCEDURE fct__i8_cat ! concatenate integer(8) to string character
@@ -68,12 +150,61 @@
 CONTAINS
    !------------------------------------------------------------------- 
-   !> @brief This routine concatenate character and integer(4) (as character). 
+   !> @brief This function concatenate character and integer(1) (as character). 
+   ! 
+   !> @author J.Paul 
+   !> - September, 2014- Initial Version 
+   ! 
+   !> @param[in] cd_char   string character
+   !> @param[in] bd_val    integer(1) variable value
+   !> @return string character 
+   !------------------------------------------------------------------- 
+   PURE CHARACTER(LEN=lc) FUNCTION fct__i1_cat(cd_char, bd_val) 
+ 
+      ! arguments
+      CHARACTER(LEN=lc), INTENT(IN) :: cd_char
+      INTEGER(i1),       INTENT(IN) :: bd_val
+
+      ! local variable
+      CHARACTER(LEN=lc) :: cl_val
+      !---------------------------------------------------------------- 
+ 
+      cl_val = fct_str(bd_val)
+      fct__i1_cat=TRIM(cd_char)//TRIM(cl_val)
+
+   END FUNCTION fct__i1_cat 
+   !------------------------------------------------------------------- 
+   !> @brief This function concatenate character and integer(2) (as character). 
+   ! 
+   !> @author J.Paul 
+   !> - September, 2014- Initial Version 
+   ! 
+   !> @param[in] cd_char   string character
+   !> @param[in] sd_val    integer(2) variable value
+   !> @return string character 
+   !------------------------------------------------------------------- 
+   PURE CHARACTER(LEN=lc) FUNCTION fct__i2_cat(cd_char, sd_val) 
+ 
+      ! arguments
+      CHARACTER(LEN=lc), INTENT(IN) :: cd_char
+      INTEGER(i2),       INTENT(IN) :: sd_val
+
+      ! local variable
+      CHARACTER(LEN=lc) :: cl_val
+      !---------------------------------------------------------------- 
+ 
+      cl_val = fct_str(sd_val)
+      fct__i2_cat=TRIM(cd_char)//TRIM(cl_val)
+
+   END FUNCTION fct__i2_cat 
+   !------------------------------------------------------------------- 
+   !> @brief This function concatenate character and integer(4) (as character). 
    ! 
    !> @author J.Paul 
    !> - Nov, 2013- Initial Version 
    ! 
+   !> @param[in] cd_char   string character
+   !> @param[in] id_val    integer(4) variable value
    !> @return string character 
    !------------------------------------------------------------------- 
-   ! @code 
    PURE CHARACTER(LEN=lc) FUNCTION fct__i4_cat(cd_char, id_val) 
  
@@ -90,14 +221,14 @@
 
    END FUNCTION fct__i4_cat 
-   ! @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This routine concatenate character and integer(8) (as character). 
+   !------------------------------------------------------------------- 
+   !> @brief This function concatenate character and integer(8) (as character). 
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
+   !> - November, 2013- Initial Version 
    ! 
+   !> @param[in] cd_char   string character
+   !> @param[in] kd_val    integer(8) variable value
    !> @return string character 
    !------------------------------------------------------------------- 
-   ! @code 
    PURE CHARACTER(LEN=lc) FUNCTION fct__i8_cat(cd_char, kd_val) 
  
@@ -114,14 +245,14 @@
 
    END FUNCTION fct__i8_cat 
-   ! @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This routine concatenate character and real(4) (as character). 
+   !------------------------------------------------------------------- 
+   !> @brief This function concatenate character and real(4) (as character). 
    ! 
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
+   !> - November, 2013- Initial Version 
    ! 
+   !> @param[in] cd_char   string character
+   !> @param[in] rd_val    real(4) variable value
    !> @return string character 
    !------------------------------------------------------------------- 
-   ! @code 
    PURE CHARACTER(LEN=lc) FUNCTION fct__r4_cat(cd_char, rd_val) 
  
@@ -138,14 +269,14 @@
 
    END FUNCTION fct__r4_cat 
-   ! @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This routine concatenate character and real(8) (as character). 
-   ! 
+   !------------------------------------------------------------------- 
+   !> @brief This function concatenate character and real(8) (as character). 
+   !>
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
+   !> - November, 2013- Initial Version 
+   !>
+   !> @param[in] cd_char   string character
+   !> @param[in] dd_val    real(8) variable value
    !> @return string character 
    !------------------------------------------------------------------- 
-   ! @code 
    PURE CHARACTER(LEN=lc) FUNCTION fct__r8_cat(cd_char, dd_val) 
  
@@ -162,14 +293,14 @@
 
    END FUNCTION fct__r8_cat 
-   ! @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This routine concatenate character and logical (as character). 
-   ! 
+   !------------------------------------------------------------------- 
+   !> @brief This function concatenate character and logical (as character). 
+   !>
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
+   !> - November, 2013- Initial Version 
+   !>
+   !> @param[in] cd_char   string character
+   !> @param[in] ld_val    logical variable value
    !> @return string character 
    !------------------------------------------------------------------- 
-   ! @code 
    PURE CHARACTER(LEN=lc) FUNCTION fct__l_cat(cd_char, ld_val) 
  
@@ -186,14 +317,12 @@
 
    END FUNCTION fct__l_cat 
-   ! @endcode
-   !------------------------------------------------------------------- 
-   !> @brief This routine returns the next available I/O unit number. 
-   ! 
+   !------------------------------------------------------------------- 
+   !> @brief This function returns the next available I/O unit number. 
+   !>
    !> @author J.Paul 
-   !> - Nov, 2013- Initial Version 
-   ! 
+   !> - November, 2013- Initial Version 
+   !>
    !> @return file id 
    !------------------------------------------------------------------- 
-   ! @code 
    INTEGER(i4) FUNCTION fct_getunit() 
  
@@ -211,12 +340,12 @@
  
    END FUNCTION fct_getunit 
-   ! @endcode
-   !-------------------------------------------------------------------
-   !> @brief This routine handle Fortran status.
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !-------------------------------------------------------------------
-   ! @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine handle Fortran status.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] id_status
+   !-------------------------------------------------------------------
    SUBROUTINE fct_err(id_status)
 
@@ -232,15 +361,35 @@
 
    END SUBROUTINE fct_err
-   ! @endcode
+   !-------------------------------------------------------------------
+   !> @brief This subroutine  create a pause statement
+   !
+   !> @author J.Paul
+   !> - November, 2014- Initial Version
+   !>
+   !> @param[in] cd_msg optional message to be added
+   !-------------------------------------------------------------------
+   SUBROUTINE fct_pause(cd_msg)
+
+      ! Argument
+      CHARACTER(LEN=*), INTENT(IN), OPTIONAL  :: cd_msg
+      !----------------------------------------------------------------
+
+      IF( PRESENT(cd_msg) )THEN
+         WRITE( *, * ) 'Press Enter to continue '//TRIM(cd_msg)
+      ELSE
+         WRITE( *, * ) 'Press Enter to continue'
+      ENDIF
+      READ( *, * )
+
+   END SUBROUTINE fct_pause
    !-------------------------------------------------------------------
    !> @brief This function convert logical to string character.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] ld_var : logical variable
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] ld_var logical variable
    !> @return character of this integer variable
    !-------------------------------------------------------------------
-   ! @code
    PURE CHARACTER(LEN=lc) FUNCTION fct__l_str(ld_var)
       IMPLICIT NONE
@@ -256,15 +405,13 @@
 
    END FUNCTION fct__l_str
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This function convert integer(1) to string character.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] bd_var : integer(1) variable
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] bd_var integer(1) variable
    !> @return character of this integer variable
    !-------------------------------------------------------------------
-   ! @code
    PURE CHARACTER(LEN=lc) FUNCTION fct__i1_str(bd_var)
       IMPLICIT NONE
@@ -280,15 +427,13 @@
 
    END FUNCTION fct__i1_str
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This function convert integer(2) to string character.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] sd_var : integer(2) variable
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] sd_var integer(2) variable
    !> @return character of this integer variable
    !-------------------------------------------------------------------
-   ! @code
    PURE CHARACTER(LEN=lc) FUNCTION fct__i2_str(sd_var)
       IMPLICIT NONE
@@ -304,15 +449,13 @@
 
    END FUNCTION fct__i2_str
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This function convert integer(4) to string character.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] id_var : integer(4) variable
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] id_var integer(4) variable
    !> @return character of this integer variable
    !-------------------------------------------------------------------
-   ! @code
    PURE CHARACTER(LEN=lc) FUNCTION fct__i4_str(id_var)
       IMPLICIT NONE
@@ -328,15 +471,13 @@
 
    END FUNCTION fct__i4_str
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This function convert integer(8) to string character.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] kd_var : integer(8) variable
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] kd_var integer(8) variable
    !> @return character of this integer variable
    !-------------------------------------------------------------------
-   ! @code
    PURE CHARACTER(LEN=lc) FUNCTION fct__i8_str(kd_var)
       IMPLICIT NONE
@@ -352,15 +493,13 @@
 
    END FUNCTION fct__i8_str
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This function convert real(4) to string character.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] rd_var : real(4) variable
-   !> @return character of this integer variable
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] rd_var real(4) variable
+   !> @return character of this real variable
+   !-------------------------------------------------------------------
    PURE CHARACTER(LEN=lc) FUNCTION fct__r4_str(rd_var)
       IMPLICIT NONE
@@ -376,15 +515,13 @@
 
    END FUNCTION fct__r4_str
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This function convert real(8) to string character.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_var : real(8) variable
-   !> @return character of this integer variable
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_var real(8) variable
+   !> @return character of this real variable
+   !-------------------------------------------------------------------
    PURE CHARACTER(LEN=lc) FUNCTION fct__r8_str(dd_var)
       IMPLICIT NONE
@@ -400,22 +537,21 @@
 
    END FUNCTION fct__r8_str
-   ! @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This function concatenate all the element of a character table 
-   !> except unknown one, in a character string.
-   !>
-   !> optionnally a separator could be added between each element
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_tab : table of character
+   !-------------------------------------------------------------------
+   !> @brief This function concatenate all the element of a character array 
+   !> in a character string.
+   !> @details
+   !> optionnally a separator could be added between each element.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_arr array of character
+   !> @param[in] cd_sep separator character
    !> @return character
    !-------------------------------------------------------------------
-   ! @code
-   PURE CHARACTER(LEN=lc) FUNCTION fct_concat(cd_tab,cd_sep)
-      IMPLICIT NONE
-      ! Argument      
-      CHARACTER(*), DIMENSION(:), INTENT(IN) :: cd_tab
+   PURE CHARACTER(LEN=lc) FUNCTION fct_concat(cd_arr,cd_sep)
+      IMPLICIT NONE
+      ! Argument      
+      CHARACTER(*), DIMENSION(:), INTENT(IN) :: cd_arr
       CHARACTER(*),               INTENT(IN), OPTIONAL :: cd_sep
 
@@ -432,13 +568,10 @@
       IF(PRESENT(cd_sep)) cl_sep=cd_sep
 
-      il_size=SIZE(cd_tab)
+      il_size=SIZE(cd_arr)
       fct_concat=''
       cl_tmp=''
       DO ji=1,il_size
 
-         !IF( TRIM(ADJUSTL(cd_tab(ji))) /= 'unknown' )THEN
-            WRITE(cl_tmp,*) TRIM(fct_concat)//TRIM(ADJUSTL(cd_tab(ji)))//TRIM(cl_sep)
-         !ENDIF
-      
+         WRITE(cl_tmp,*) TRIM(fct_concat)//TRIM(ADJUSTL(cd_arr(ji)))//TRIM(cl_sep)
          fct_concat=TRIM(ADJUSTL(cl_tmp))
       
@@ -446,5 +579,4 @@
 
    END FUNCTION fct_concat
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This function convert string character upper case to lower case.
@@ -458,10 +590,9 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_var : character
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_var character
    !> @return lower case character
    !-------------------------------------------------------------------
-   ! @code
    PURE CHARACTER(LEN=lc) FUNCTION fct_lower(cd_var)
       IMPLICIT NONE
@@ -505,5 +636,4 @@
 
    END FUNCTION fct_lower
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This function convert string character lower case to upper case.
@@ -517,10 +647,9 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_var : character
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_var character
    !> @return upper case character
    !-------------------------------------------------------------------
-   ! @code
    PURE CHARACTER(LEN=lc) FUNCTION fct_upper(cd_var)
       IMPLICIT NONE
@@ -564,17 +693,13 @@
 
    END FUNCTION fct_upper
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This function check if character is numeric.
    !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_var : character
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_var character
    !> @return character is numeric
    !-------------------------------------------------------------------
-   ! @code
    PURE LOGICAL FUNCTION fct_is_num(cd_var)
       IMPLICIT NONE
@@ -597,21 +722,17 @@
 
    END FUNCTION fct_is_num
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This function split string of character 
    !> using separator character, by default '|',
-   !> and return the element on index ind
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_string : string of character
-   !> @param[in] id_ind : indice
-   !> @param[in] cd_sep   separator character
+   !> and return the element on index ind.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_string string of character
+   !> @param[in] id_ind    indice
+   !> @param[in] cd_sep    separator character
    !> @return return the element on index id_ind
    !-------------------------------------------------------------------
-   ! @code
    PURE FUNCTION fct_split(cd_string, id_ind, cd_sep)
       IMPLICIT NONE
@@ -629,4 +750,5 @@
 
       INTEGER(i4) :: il_sep
+      INTEGER(i4) :: il_lsep
       
       ! loop indices
@@ -639,13 +761,87 @@
       ! get separator
       cl_sep='|'
-      IF( PRESENT(cd_sep) ) cl_sep=TRIM(ADJUSTL(cd_sep))
+      IF( PRESENT(cd_sep) )THEN
+         IF( cd_sep==' ')THEN
+            cl_sep=' '
+         ELSE
+            cl_sep=TRIM(ADJUSTL(cd_sep))
+         ENDIF
+      ENDIF
       
+      IF( cl_sep /= ' ' )THEN
+         ! get separator index
+         il_sep=INDEX( TRIM(cl_string), TRIM(cl_sep) )
+         il_lsep=LEN(TRIM(cl_sep)) 
+
+         IF( il_sep /= 0 )THEN
+            fct_split=TRIM(ADJUSTL(cl_string(1:il_sep-1)))
+         ELSE
+            fct_split=TRIM(ADJUSTL(cl_string))
+         ENDIF
+
+         ji=1
+         DO WHILE( il_sep /= 0 .AND. ji /= id_ind )
+            
+            ji=ji+1
+            
+            cl_string=TRIM(cl_string(il_sep+il_lsep:))
+            il_sep=INDEX( TRIM(cl_string), TRIM(cl_sep) )
+
+            IF( il_sep /= 0 )THEN
+               fct_split=TRIM(ADJUSTL(cl_string(1:il_sep-1)))
+            ELSE
+               fct_split=TRIM(ADJUSTL(cl_string))
+            ENDIF
+
+         ENDDO
+
+         IF( ji /= id_ind ) fct_split=''
+      ELSE
+         fct_split=fct__split_space(TRIM(cl_string), id_ind)
+      ENDIF
+
+   END FUNCTION fct_split
+   !-------------------------------------------------------------------
+   !> @brief This function split string of character 
+   !> using space as separator, 
+   !> and return the element on index ind.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_string string of character
+   !> @param[in] id_ind    indice
+   !> @return return the element on index id_ind
+   !-------------------------------------------------------------------
+   PURE FUNCTION fct__split_space(cd_string, id_ind)
+      IMPLICIT NONE
+      ! Argument      
+      CHARACTER(LEN=*), INTENT(IN) :: cd_string
+      INTEGER(i4)     , INTENT(IN) :: id_ind
+
+      ! function
+      CHARACTER(LEN=lc) :: fct__split_space
+
+      ! local variable
+      CHARACTER(LEN=lc) :: cl_string
+
+      INTEGER(i4) :: il_sep
+      INTEGER(i4) :: il_lsep
+      
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! initialize
+      fct__split_space=''
+      cl_string=ADJUSTL(cd_string)
+
       ! get separator index
-      il_sep=INDEX( TRIM(cl_string), TRIM(cl_sep) )
-      
+      il_sep=INDEX( TRIM(cl_string), ' ' )
+      il_lsep=LEN(' ') 
+
       IF( il_sep /= 0 )THEN
-         fct_split=TRIM(ADJUSTL(cl_string(1:il_sep-1)))
+         fct__split_space=TRIM(ADJUSTL(cl_string(1:il_sep-1)))
       ELSE
-         fct_split=TRIM(ADJUSTL(cl_string))
+         fct__split_space=TRIM(ADJUSTL(cl_string))
       ENDIF
 
@@ -655,33 +851,32 @@
          ji=ji+1
          
-         cl_string=TRIM(cl_string(il_sep+1:))
-         il_sep=INDEX( TRIM(cl_string), TRIM(cl_sep) )
+         cl_string=TRIM(cl_string(il_sep+il_lsep:))
+         il_sep=INDEX( TRIM(cl_string), ' ' )
 
          IF( il_sep /= 0 )THEN
-            fct_split=TRIM(ADJUSTL(cl_string(1:il_sep-1)))
+            fct__split_space=TRIM(ADJUSTL(cl_string(1:il_sep-1)))
          ELSE
-            fct_split=TRIM(ADJUSTL(cl_string))
+            fct__split_space=TRIM(ADJUSTL(cl_string))
          ENDIF
 
       ENDDO
 
-      IF( ji /= id_ind ) fct_split=''
-
-   END FUNCTION fct_split
-   ! @endcode
+      IF( ji /= id_ind ) fct__split_space=''
+
+   END FUNCTION fct__split_space
    !-------------------------------------------------------------------
    !> @brief This function return basename of a filename.
    !
    !> @details
-   !> actually it splits filename using sperarator '/'
-   !> and return last string character
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_string : filename
+   !> Actually it splits filename using sperarator '/'
+   !> and return last string character.<br/>
+   !> Optionally you could specify another separator.
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_string filename
+   !> @param[in] cd_sep    separator character
    !> @return basename (filename without path)
    !-------------------------------------------------------------------
-   ! @code
    PURE FUNCTION fct_basename(cd_string, cd_sep)
       IMPLICIT NONE
@@ -711,19 +906,18 @@
 
    END FUNCTION fct_basename
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This function return dirname of a filename.
    !
    !> @details
-   !> actually it splits filename using sperarator '/'
-   !> and return all exept last string character
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_string : filename
+   !> Actually it splits filename using sperarator '/'
+   !> and return all except last string character.<br/>
+   !> Optionally you could specify another separator.
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_string filename
+   !> @param[in] cd_sep    separator character
    !> @return dirname (path of the filename)
    !-------------------------------------------------------------------
-   ! @code
    PURE FUNCTION fct_dirname(cd_string, cd_sep)
       IMPLICIT NONE
@@ -757,5 +951,4 @@
 
    END FUNCTION fct_dirname
-   ! @endcode
 END MODULE fct
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/global.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/global.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/global.f90	(revision 5075)
@@ -6,11 +6,10 @@
 !
 ! DESCRIPTION:
-!> @brief This module defines global variables, and parameters that can't 
-!> be associated with a module
+!> @brief This module defines global variables and parameters.
 !
 !> @author
 !> J.paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -22,64 +21,72 @@
    IMPLICIT NONE
 
-   PUBLIC :: dg_fill !< default fill value
-   PUBLIC :: ig_nsep !< number of separator listed
-   PUBLIC :: ig_ncom !< number of comment character listed
-   PUBLIC :: cg_sep  !< list of separator
-   PUBLIC :: cg_com  !< list of comment character
+   PUBLIC :: dp_fill         !< default fill value
+   PUBLIC :: ip_nsep         !< number of separator listed
+   PUBLIC :: ip_ncom         !< number of comment character listed
+   PUBLIC :: cp_sep          !< list of separator
+   PUBLIC :: cp_com          !< list of comment character
 
-   PUBLIC :: ig_npoint
-   PUBLIC :: jp_T
-   PUBLIC :: jp_U
-   PUBLIC :: jp_V
-   PUBLIC :: jp_F
+   PUBLIC :: ip_npoint       !< number of point on ARAKAWA C-grid 
+   PUBLIC :: jp_T            !< indice for T-point on ARAKAWA C-grid
+   PUBLIC :: jp_U            !< indice for U-point on ARAKAWA C-grid
+   PUBLIC :: jp_V            !< indice for V-point on ARAKAWA C-grid
+   PUBLIC :: jp_F            !< indice for F-point on ARAKAWA C-grid
+   PUBLIC :: cp_grid_point   !< list of grid_point character
 
-   PUBLIC :: ig_ndim
-   PUBLIC :: jp_I
-   PUBLIC :: jp_J
-   PUBLIC :: jp_K
-   PUBLIC :: jp_L
+   PUBLIC :: ip_maxdim       !< maximum number of dimension to be used
+   PUBLIC :: jp_I            !< indice for I-direction
+   PUBLIC :: jp_J            !< indice for J-direction
+   PUBLIC :: jp_K            !< indice for K-direction
+   PUBLIC :: jp_L            !< indice for L-direction
+   PUBLIC :: cp_dimorder     !< dimension order
 
-   PUBLIC :: ig_maxvar  !< maximum number of variable
-   PUBLIC :: ig_maxmtx  !< matrix variable maximum dimension
-   PUBLIC :: ig_maxseg  !< maximum number of segment
-   PUBLIC :: ig_ghost   !< number of ghost cell
+   PUBLIC :: ip_maxvar       !< maximum number of variable
+   PUBLIC :: ip_maxmtx       !< matrix variable maximum dimension
+   PUBLIC :: ip_maxseg       !< maximum number of segment
+   PUBLIC :: ip_ghost        !< number of ghost cell
 
-   PUBLIC :: ig_ninterp      !< number of available interpolation method
-   PUBLIC :: cg_interp_list  !< list of interpolation name
+   PUBLIC :: ip_ninterp      !< number of available interpolation method
+   PUBLIC :: cp_interp_list  !< list of interpolation name
    
-   PUBLIC :: ig_nextrap      !< number of available extrapolation method
-   PUBLIC :: cg_extrap_list  !< list of extrapolation name
+   PUBLIC :: ip_nextrap      !< number of available extrapolation method
+   PUBLIC :: cp_extrap_list  !< list of extrapolation name
    
-   PUBLIC :: ig_nfilter      !< number of available filter
-   PUBLIC :: cg_filter_list  !< list of filter name
+   PUBLIC :: ip_nfilter      !< number of available filter
+   PUBLIC :: cp_filter_list  !< list of filter name
 
-   PRIVATE
+   PUBLIC :: ip_ncard        !< number of cardinal point
+   PUBLIC :: cp_card         !< array of cardinal point
+   PUBLIC :: jp_north        !< indice for north boundary
+   PUBLIC :: jp_south        !< indice for south boundary
+   PUBLIC :: jp_east         !< indice for east  boundary
+   PUBLIC :: jp_west         !< indice for west  boundary
+
    ! NOTE_avoid_public_variables_if_possible
 
-   INTEGER(i4)                             , PARAMETER :: ig_maxvar =200   !< maximum number of variable
-   INTEGER(i4)                             , PARAMETER :: ig_maxmtx =100   !< matrix variable maximum dimension (cf create_bathy)
-   INTEGER(i4)                             , PARAMETER :: ig_maxseg =50    !< maximum number of segment for each boundary
+   INTEGER(i4)                             , PARAMETER :: ip_maxvar =200   !< maximum number of variable
+   INTEGER(i4)                             , PARAMETER :: ip_maxmtx =100   !< matrix variable maximum dimension (cf create_bathy)
+   INTEGER(i4)                             , PARAMETER :: ip_maxseg =50    !< maximum number of segment for each boundary
 
-   INTEGER(i4)                             , PARAMETER :: ig_nsep=2  !< number of separator listed
-   CHARACTER(1)     , DIMENSION(ig_nsep)   , PARAMETER :: cg_sep = (/'.','_'/) !< list of separator 
+   INTEGER(i4)                             , PARAMETER :: ip_nsep=2        !< number of separator listed
+   CHARACTER(1)     , DIMENSION(ip_nsep)   , PARAMETER :: cp_sep = (/'.','_'/) !< list of separator 
 
-   INTEGER(i4)                             , PARAMETER :: ig_ncom=2  !< number of comment character listed
-   CHARACTER(1)     , DIMENSION(ig_ncom)   , PARAMETER :: cg_com = (/'#','!'/) !< list of comment character 
+   INTEGER(i4)                             , PARAMETER :: ip_ncom=2        !< number of comment character listed
+   CHARACTER(1)     , DIMENSION(ip_ncom)   , PARAMETER :: cp_com = (/'#','!'/) !< list of comment character 
     
-   INTEGER(i4)                             , PARAMETER :: ig_ghost=1    !< number of ghost cell
+   INTEGER(i4)                             , PARAMETER :: ip_ghost=1       !< number of ghost cell
 
-   INTEGER(i4)                             , PARAMETER :: ig_ninterp=3
-   CHARACTER(LEN=lc), DIMENSION(ig_ninterp), PARAMETER :: cg_interp_list = &
+   INTEGER(i4)                             , PARAMETER :: ip_ninterp=3
+   CHARACTER(LEN=lc), DIMENSION(ip_ninterp), PARAMETER :: cp_interp_list = &
    &  (/ 'nearest', &
    &     'cubic  ', &
    &     'linear '  /)
 
-   INTEGER(i4)                             , PARAMETER :: ig_nextrap=2
-   CHARACTER(LEN=lc), DIMENSION(ig_nextrap), PARAMETER :: cg_extrap_list = &
+   INTEGER(i4)                             , PARAMETER :: ip_nextrap=2
+   CHARACTER(LEN=lc), DIMENSION(ip_nextrap), PARAMETER :: cp_extrap_list = &
    &  (/ 'dist_weight', &
    &     'min_error  ' /)
 
-   INTEGER(i4)                             , PARAMETER :: ig_nfilter=5
-   CHARACTER(LEN=lc), DIMENSION(ig_nfilter), PARAMETER :: cg_filter_list = &
+   INTEGER(i4)                             , PARAMETER :: ip_nfilter=5
+   CHARACTER(LEN=lc), DIMENSION(ip_nfilter), PARAMETER :: cp_filter_list = &
    &  (/ 'butterworth', &
    &     'blackman   ', &
@@ -88,18 +95,35 @@
    &     'gauss      '/)
 
-   REAL(dp)                                , PARAMETER :: dg_fill=NF90_FILL_DOUBLE !< default fill value
-   INTEGER(i4)                             , PARAMETER :: ig_fill=NF90_FILL_INT    !< default fill value
+   REAL(dp)                                , PARAMETER :: dp_fill=NF90_FILL_DOUBLE !< default fill value
 
-   INTEGER(i4)                             , PARAMETER :: ig_npoint=4
+   INTEGER(i4)                             , PARAMETER :: ip_npoint=4
    INTEGER(i4)                             , PARAMETER :: jp_T=1
    INTEGER(i4)                             , PARAMETER :: jp_U=2
    INTEGER(i4)                             , PARAMETER :: jp_V=3
    INTEGER(i4)                             , PARAMETER :: jp_F=4
+   CHARACTER(LEN=1), DIMENSION(ip_npoint)  , PARAMETER :: cp_grid_point = &
+   &  (/ 'T', 'U', 'V', 'F' /)
 
-   INTEGER(i4)                             , PARAMETER :: ig_ndim=2
+
+   INTEGER(i4)                             , PARAMETER :: ip_maxdim=4
    INTEGER(i4)                             , PARAMETER :: jp_I=1
    INTEGER(i4)                             , PARAMETER :: jp_J=2
    INTEGER(i4)                             , PARAMETER :: jp_K=3
    INTEGER(i4)                             , PARAMETER :: jp_L=4
+   CHARACTER(LEN=ip_maxdim)                , PARAMETER :: cp_dimorder = 'xyzt' !< dimension order to output
+
+   INTEGER(i4), PARAMETER :: ip_ncard=4
+   CHARACTER(LEN=lc), DIMENSION(ip_ncard), PARAMETER :: cp_card = &
+   &  (/ 'north', &
+   &     'south', &
+   &     'east ', &
+   &     'west ' /)
+
+   INTEGER(i4), PARAMETER :: jp_north=1
+   INTEGER(i4), PARAMETER :: jp_south=2
+   INTEGER(i4), PARAMETER :: jp_east =3
+   INTEGER(i4), PARAMETER :: jp_west =4
+
+
 
 END MODULE global
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/grid.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/grid.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/grid.f90	(revision 5075)
@@ -6,15 +6,213 @@
 !
 ! DESCRIPTION:
-!> @brief grid manager <br/>
+!> @brief This module is grid manager.
 !>
 !> @details
-!> 
+!>    to get NEMO pivot point index:<br/>
+!> @code
+!>    il_pivot=grid_get_pivot(td_file)
+!> @endcode
+!>       - il_pivot is NEMO pivot point index F(0), T(1)
+!>       - td_file is mpp structure 
+!>
+!>    to get NEMO periodicity index:<br/>
+!> @code
+!>    il_perio=grid_get_perio(td_file)
+!> @endcode
+!>       - il_perio is NEMO periodicity index (0,1,2,3,4,5,6)
+!>       - td_file is mpp structure
+!>
+!>    to check domain validity:<br/>
+!> @code
+!>    CALL grid_check_dom(td_coord, id_imin, id_imax, id_jmin, id_jmax)
+!> @endcode
+!>       - td_coord is coordinates mpp structure
+!>       - id_imin is i-direction lower left  point indice
+!>       - id_imax is i-direction upper right point indice
+!>       - id_jmin is j-direction lower left  point indice
+!>       - id_jmax is j-direction upper right point indice
+!>
+!>    to get closest coarse grid indices of fine grid domain:<br/>
+!> @code
+!>    il_index(:,:)=grid_get_coarse_index(td_coord0, td_coord1,
+!>                                      [id_rho,] [cd_point])
+!> @endcode
+!>    or 
+!> @code
+!>    il_index(:,:)=grid_get_coarse_index(td_lon0, td_lat0, td_coord1,
+!>                                      [id_rho,] [cd_point])
+!> @endcode
+!>    or
+!> @code
+!>    il_index(:,:)=grid_get_coarse_index(td_coord0, td_lon1, td_lat1,
+!>                                      [id_rho,] [cd_point])
+!> @endcode
+!>    or
+!> @code
+!>    il_index(:,:)=grid_get_coarse_index(td_lon0, td_lat0, td_lon1, td_lat1,
+!>                                      [id_rho,] [cd_point])
+!> @endcode
+!>       - il_index(:,:) is  coarse grid indices (/ (/ imin0, imax0 /), 
+!> (/ jmin0, jmax0 /) /)
+!>       - td_coord0 is coarse grid coordinate mpp structure 
+!>       - td_coord1 is fine grid coordinate mpp structure
+!>       - td_lon0 is coarse grid longitude variable structure 
+!>       - td_lat0 is coarse grid latitude  variable structure 
+!>       - td_lon1 is fine   grid longitude variable structure 
+!>       - td_lat1 is fine   grid latitude  variable structure 
+!>       - id_rho is array of refinment factor (default 1)
+!>       - cd_point is Arakawa grid point (default 'T')
+!>
+!>    to know if grid is global:<br/>
+!> @code
+!>    ll_global=grid_is_global(td_lon, td_lat)
+!> @endcode
+!>       - td_lon is longitude variable structure
+!>       - td_lat is latitude variable structure
+!>   
+!>    to know if grid contains north fold:<br/>
+!> @code
+!>    ll_north=grid_is_north_fold(td_lat)
+!> @endcode
+!>       - td_lat is latitude variable structure    
+!>
+!>    to get coarse grid indices of the closest point from one fine grid 
+!> point:<br/>
+!> @code
+!>    il_index(:)=grid_get_closest(dd_lon0(:,:), dd_lat0(:,:), dd_lon1, dd_lat1)
+!> @endcode
+!>       - il_index(:) is  coarse grid indices (/ i0, j0 /)
+!>       - dd_lon0 is coarse grid array of longitude value (real(8))
+!>       - dd_lat0 is coarse grid array of latitude  value (real(8))
+!>       - dd_lon1 is fine grid longitude value (real(8))
+!>       - dd_lat1 is fine grid latitude  value (real(8))
+!>
+!>    to compute distance between a point A and grid points:<br/>
+!> @code
+!>    il_dist(:,:)=grid_distance(dd_lon, dd_lat, dd_lonA, dd_latA)
+!> @endcode
+!>       - il_dist(:,:) is array of distance between point A and grid points
+!>       - dd_lon is array of longitude value (real(8))
+!>       - dd_lat is array of longitude value (real(8))
+!>       - dd_lonA is longitude of point A (real(8))
+!>       - dd_latA is latitude  of point A (real(8))
+!>
+!>    to get offset between fine grid and coarse grid:<br/> 
+!> @code
+!>    il_offset(:,:)=grid_get_fine_offset(td_coord0, 
+!>                                        id_imin0, id_jmin0, id_imax0, id_jmax0,
+!>                                        td_coord1
+!>                                        [,id_rho] [,cd_point])
+!> @endcode
+!>    or
+!> @code
+!>    il_offset(:,:)=grid_get_fine_offset(dd_lon0, dd_lat0, 
+!>                                        id_imin0, id_jmin0,id_imax0, id_jmax0,
+!>                                        td_coord1 
+!>                                        [,id_rho] [,cd_point])
+!> @endcode
+!>    or
+!> @code
+!>    il_offset(:,:)=grid_get_fine_offset(td_coord0, 
+!>                                        id_imin0, id_jmin0, id_imax0, id_jmax0,
+!>                                        dd_lon1, dd_lat1 
+!>                                        [,id_rho] [,cd_point])
+!> @endcode
+!>    or
+!> @code
+!>    il_offset(:,:)=grid_get_fine_offset(dd_lon0, dd_lat0,
+!>                                        id_imin0, id_jmin0, id_imax0, id_jmax0,
+!>                                        dd_lon1, dd_lat1
+!>                                        [,id_rho] [,cd_point])
+!> @endcode
+!>       - il_offset(:,:) is offset array 
+!>    (/ (/ i_offset_left, i_offset_right /), (/ j_offset_lower, j_offset_upper /) /)
+!>       - td_coord0 is coarse grid coordinate mpp structure 
+!>       - dd_lon0  is coarse grid longitude array (real(8))
+!>       - dd_lat0  is coarse grid latitude  array (real(8))
+!>       - id_imin0 is coarse grid lower left  corner i-indice of fine grid 
+!> domain
+!>       - id_jmin0 is coarse grid lower left  corner j-indice of fine grid 
+!> domain
+!>       - id_imax0 is coarse grid upper right corner i-indice of fine grid 
+!> domain
+!>       - id_jmax0 is coarse grid upper right corner j-indice of fine grid 
+!> domain
+!>       - td_coord1 is fine grid coordinate mpp structure
+!>       - dd_lon1  is fine   grid longitude array (real(8))
+!>       - dd_lat1  is fine   grid latitude  array (real(8))
+!>       - id_rho is array of refinment factor (default 1)
+!>       - cd_point is Arakawa grid point (default 'T')
+!>
+!>    to check fine and coarse grid coincidence:<br/>
+!> @code
+!>    CALL grid_check_coincidence(td_coord0, td_coord1, 
+!>                                id_imin0, id_imax0, id_jmin0, id_jmax0
+!>                                [,id_rho])
+!> @endcode
+!>       - td_coord0 is coarse grid coordinate mpp structure
+!>       - td_coord1 is fine   grid coordinate mpp structure
+!>       - id_imin0  is coarse grid lower left  corner i-indice of fine grid 
+!> domain
+!>       - id_imax0  is coarse grid upper right corner i-indice of fine grid 
+!> domain
+!>       - id_jmin0  is coarse grid lower left  corner j-indice of fine grid 
+!> domain
+!>       - id_jmax0  is coarse grid upper right corner j-indice of fine grid 
+!> domain 
+!>       - id_rho    is array of refinement factor (default 1)
+!>
+!>    to add ghost cell at boundaries:<br/>
+!> @code
+!>    CALL grid_add_ghost(td_var, id_ghost)
+!> @endcode
+!>       - td_var is array of variable structure
+!>       - id_ghost is 2D array of ghost cell factor
+!>
+!>    to delete ghost cell at boundaries:<br/>
+!> @code
+!>    CALL grid_del_ghost(td_var, id_ghost)
+!> @endcode
+!>       - td_var is array of variable structure
+!>       - id_ghost is 2D array of ghost cell factor
+!>
+!>    to get ghost cell factor (use or not):<br/>
+!> @code
+!>    il_factor(:)= grid_get_ghost( td_var )
+!> @endcode
+!>    or
+!> @code
+!>    il_factor(:)= grid_get_ghost( td_mpp )
+!> @endcode
+!>       - il_factor(:) is  array of ghost cell factor (0 or 1)
+!>       - td_var  is variable structure
+!>       - td_mpp is mpp sturcture
+!>
+!>    to compute closed sea domain:<br/>
+!> @code
+!>    il_mask(:,:)=grid_split_domain(td_var, [id_level])
+!> @endcode
+!>       - il_mask(:,:) is domain mask
+!>       - td_var is variable strucutre
+!>       - id_level is level to be used [optional] 
+!>
+!>    to fill small closed sea with _FillValue:<br/>
+!> @code
+!>    CALL grid_fill_small_dom(td_var, id_mask, [id_minsize])
+!> @endcode
+!>       - td_var  is variable structure
+!>       - id_mask is domain mask (from grid_split_domain)
+!>       - id_minsize is minimum size of sea to be kept [optional]
+!>
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
+!> @date September, 2014
+!> - add header
+!> @date October, 2014
+!> - use mpp file structure instead of file
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
 !----------------------------------------------------------------------
 MODULE grid
@@ -24,14 +222,15 @@
    USE global                          ! global parameter
    USE phycst                          ! physical constant
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE file                            ! file manager
+   USE att                             ! attribute manager
    USE var                             ! variable manager
    USE dim                             ! dimension manager
-   USE dom                             ! domain manager
    USE iom                             ! I/O manager
    USE mpp                             ! MPP manager
+   USE dom                             ! domain manager
    USE iom_mpp                         ! MPP I/O manager
+   USE iom_dom                         ! DOM I/O manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
@@ -39,86 +238,1256 @@
 
    ! function and subroutine
-   PUBLIC :: grid_check_dom !< check domain validity 
-   PUBLIC :: grid_get_coarse_index !< get closest coarse grid indices of fine grid domain.
-   PUBLIC :: grid_is_global !< check if grid is global or not
-   PUBLIC :: grid_get_closest !< return closest coarse grid point from another point
-   PUBLIC :: grid_distance !< compute grid distance to a point
-   PUBLIC :: grid_get_fine_offset !< get fine grid offset
-   PUBLIC :: grid_check_coincidence !< check fine and coarse grid coincidence
-   PUBLIC :: grid_get_perio !< return NEMO periodicity index
-   PUBLIC :: grid_get_pivot !< return NEMO pivot point index
-   PUBLIC :: grid_add_ghost !< add ghost cell at boundaries.
-   PUBLIC :: grid_del_ghost !< delete ghost cell at boundaries.
-   PUBLIC :: grid_get_ghost !< return ghost cell factor
-   PUBLIC :: grid_split_domain !< 
-   PUBLIC :: grid_fill_small_dom !< 
-
-   PRIVATE :: grid_get_coarse_index_ff
-   PRIVATE :: grid_get_coarse_index_cf
-   PRIVATE :: grid_get_coarse_index_fc
-   PRIVATE :: grid_get_coarse_index_cc
-   PRIVATE :: grid__get_ghost_f  
-   PRIVATE :: grid__get_ghost_ll
-   PRIVATE :: grid__check_corner
+   PUBLIC :: grid_get_info             !< get information about mpp global domain (pivot, perio, ew)
+   PUBLIC :: grid_get_pivot            !< get NEMO pivot point index
+   PUBLIC :: grid_get_perio            !< get NEMO periodicity index
+   PUBLIC :: grid_get_ew_overlap       !< get East West overlap
+   PUBLIC :: grid_check_dom            !< check domain validity 
+   PUBLIC :: grid_get_coarse_index     !< get closest coarse grid indices of fine grid domain.
+   PUBLIC :: grid_is_global            !< check if grid is global or not
+   PUBLIC :: grid_is_north_fold
+   PUBLIC :: grid_get_closest          !< return closest coarse grid point from another point
+   PUBLIC :: grid_distance             !< compute grid distance to a point
+   PUBLIC :: grid_get_fine_offset      !< get fine grid offset
+   PUBLIC :: grid_check_coincidence    !< check fine and coarse grid coincidence
+   PUBLIC :: grid_add_ghost            !< add ghost cell at boundaries.
+   PUBLIC :: grid_del_ghost            !< delete ghost cell at boundaries.
+   PUBLIC :: grid_get_ghost            !< return ghost cell factor
+   PUBLIC :: grid_split_domain         !< compute closed sea domain 
+   PUBLIC :: grid_fill_small_dom       !< fill small closed sea with fill value 
+
+                                     ! get closest coarse grid indices of fine grid domain
+   PRIVATE :: grid__get_coarse_index_ff ! - using coarse and fine grid coordinates files
+   PRIVATE :: grid__get_coarse_index_cf ! - using coarse grid array of lon,lat and fine grid coordinates files
+   PRIVATE :: grid__get_coarse_index_fc ! - using coarse grid coordinates files, and fine grid array of lon,lat
+   PRIVATE :: grid__get_coarse_index_cc ! - using coarse and fine grid array of lon,lat
+
+                                     ! get offset between fine and coarse grid
+   PRIVATE :: grid__get_fine_offset_ff ! - using coarse and fine grid coordinates files
+   PRIVATE :: grid__get_fine_offset_cf ! - using coarse grid array of lon,lat and fine grid coordinates files
+   PRIVATE :: grid__get_fine_offset_fc ! - using coarse grid coordinates files, and fine grid array of lon,lat
+   PRIVATE :: grid__get_fine_offset_cc ! - using coarse and fine grid array of lon,lat
+
+                                     ! get information about global domain (pivot, perio, ew)
+   PRIVATE :: grid__get_info_mpp      ! - using mpp files structure
+   PRIVATE :: grid__get_info_file     ! - using files structure
+
+                                     ! get NEMO pivot point index
+   PRIVATE :: grid__get_pivot_mpp      ! - using mpp files structure
+   PRIVATE :: grid__get_pivot_file     ! - using files structure
+   PRIVATE :: grid__get_pivot_var      ! - using variable structure
+   PRIVATE :: grid__get_pivot_varT   ! compute NEMO pivot point index for variable on grid T 
+   PRIVATE :: grid__get_pivot_varU   ! compute NEMO pivot point index for variable on grid U
+   PRIVATE :: grid__get_pivot_varV   ! compute NEMO pivot point index for variable on grid V
+   PRIVATE :: grid__get_pivot_varF   ! compute NEMO pivot point index for variable on grid F
+
+                                     ! get NEMO periodicity index
+   PRIVATE :: grid__get_perio_mpp      ! - using mpp files structure
+   PRIVATE :: grid__get_perio_file     ! - using files structure
+   PRIVATE :: grid__get_perio_var      ! - using variable structure
+
+                                     ! get East West overlap
+   PRIVATE :: grid__get_ew_overlap_mpp  ! - using mpp files structure
+   PRIVATE :: grid__get_ew_overlap_file ! - using files structure
+   PRIVATE :: grid__get_ew_overlap_var  ! - using longitude variable structure
+
+                                    ! return ghost cell factor
+   PRIVATE :: grid__get_ghost_mpp      ! - using mpp files structure
+   PRIVATE :: grid__get_ghost_var      ! - using array of lon,lat
+   PRIVATE :: grid__check_corner    ! check that fine grid is inside coarse grid
+   PRIVATE :: grid__check_lat       ! check that fine grid latitude are inside coarse grid latitude
    
+   INTERFACE  grid_get_info
+      MODULE PROCEDURE grid__get_info_mpp
+      MODULE PROCEDURE grid__get_info_file
+   END INTERFACE grid_get_info
+
+   INTERFACE  grid_get_pivot
+      MODULE PROCEDURE grid__get_pivot_mpp
+      MODULE PROCEDURE grid__get_pivot_file
+      MODULE PROCEDURE grid__get_pivot_var
+   END INTERFACE grid_get_pivot
+
+   INTERFACE  grid_get_perio
+      MODULE PROCEDURE grid__get_perio_mpp
+      MODULE PROCEDURE grid__get_perio_file
+      MODULE PROCEDURE grid__get_perio_var
+   END INTERFACE grid_get_perio
+
+   INTERFACE  grid_get_ew_overlap
+      MODULE PROCEDURE grid__get_ew_overlap_mpp
+      MODULE PROCEDURE grid__get_ew_overlap_file
+      MODULE PROCEDURE grid__get_ew_overlap_var
+   END INTERFACE grid_get_ew_overlap
+
    INTERFACE  grid_get_ghost
-      MODULE PROCEDURE grid__get_ghost_ll
-      MODULE PROCEDURE grid__get_ghost_f
+      MODULE PROCEDURE grid__get_ghost_var
+      MODULE PROCEDURE grid__get_ghost_mpp
    END INTERFACE  grid_get_ghost
 
    INTERFACE  grid_get_coarse_index
-      MODULE PROCEDURE grid_get_coarse_index_ff
-      MODULE PROCEDURE grid_get_coarse_index_cf
-      MODULE PROCEDURE grid_get_coarse_index_fc
-      MODULE PROCEDURE grid_get_coarse_index_cc
+      MODULE PROCEDURE grid__get_coarse_index_ff
+      MODULE PROCEDURE grid__get_coarse_index_cf
+      MODULE PROCEDURE grid__get_coarse_index_fc
+      MODULE PROCEDURE grid__get_coarse_index_cc
    END INTERFACE grid_get_coarse_index
 
+   INTERFACE  grid_get_fine_offset
+      MODULE PROCEDURE grid__get_fine_offset_ff
+      MODULE PROCEDURE grid__get_fine_offset_fc
+      MODULE PROCEDURE grid__get_fine_offset_cf
+      MODULE PROCEDURE grid__get_fine_offset_cc
+   END INTERFACE grid_get_fine_offset   
+
 CONTAINS
    !-------------------------------------------------------------------
+   !> @brief This subroutine get information about global domain, given file
+   !> strucutre.
+   !>
+   !> @details
+   !> open edge files then:
+   !> - compute NEMO pivot point 
+   !> - compute NEMO periodicity
+   !> - compute East West overlap
+   !>
+   !> @note need all processor files to be there
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !>
+   !> @param[inout] td_file file structure 
+   !-------------------------------------------------------------------
+   SUBROUTINE grid__get_info_file(td_file)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TFILE), INTENT(INOUT) :: td_file
+
+      ! local variable
+      INTEGER(i4) :: il_ew
+      INTEGER(i4) :: il_pivot
+      INTEGER(i4) :: il_perio
+      INTEGER(i4) :: il_attid
+
+      TYPE(TATT)  :: tl_att
+
+      TYPE(TFILE) :: tl_file
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! intialise
+      il_pivot=-1
+      il_perio=-1
+      il_ew   =-1 
+
+      ! copy structure
+      tl_file=file_copy(td_file)
+
+      ! open file to be used
+      CALL iom_open(tl_file)
+
+      IF( td_file%i_perio >= 0 .AND. td_file%i_perio <= 6 )THEN
+         il_perio=td_file%i_perio
+      ELSE
+         ! look for attribute in file
+         il_attid=att_get_index(tl_file%t_att(:),'periodicity')
+         IF( il_attid /= 0 )THEN
+            il_perio=INT(tl_file%t_att(il_attid)%d_value(1),i4)
+         ENDIF
+      ENDIF
+
+      IF( td_file%i_ew >= 0 )THEN
+         il_ew=td_file%i_ew
+      ELSE
+         ! look for attribute in file
+         il_attid=att_get_index(tl_file%t_att(:),'ew_overlap')
+         IF( il_attid /= 0 )THEN
+            il_ew=INT(tl_file%t_att(il_attid)%d_value(1),i4)
+         ENDIF
+      ENDIF
+
+      SELECT CASE(il_perio)
+      CASE(3,4)
+         il_pivot=0
+      CASE(5,6)
+         il_pivot=1
+      CASE(0,1,2)
+         il_pivot=1
+      END SELECT
+      
+      IF( il_pivot < 0 .OR. il_pivot > 1 )THEN
+         ! get pivot
+         il_pivot=grid_get_pivot(tl_file)
+      ENDIF
+
+      IF( il_perio < 0 .OR. il_perio > 6 )THEN
+         ! get periodicity
+         il_perio=grid_get_perio(tl_file, il_pivot)
+      ENDIF
+
+      IF( il_ew < 0 )THEN
+         ! get periodicity
+         il_ew=grid_get_ew_overlap(tl_file)
+      ENDIF
+
+      ! close
+      CALL iom_close(tl_file)
+
+      !save in file structure
+      td_file%i_ew=il_ew
+      td_file%i_pivot=il_pivot
+      td_file%i_perio=il_perio
+
+      ! save in variable of file structure
+      tl_att=att_init("ew_overlap",il_ew)
+      DO ji=1,td_file%i_nvar
+         IF( td_file%t_var(ji)%t_dim(jp_I)%l_use )THEN
+            CALL var_move_att(td_file%t_var(ji),tl_att)
+         ENDIF
+      ENDDO
+
+      ! clean 
+      CALL file_clean(tl_file)
+      CALL att_clean(tl_att)
+
+      IF( td_file%i_perio == -1 )THEN
+         CALL logger_fatal("GRID GET INFO: can not read or compute "//&
+         &  "domain periodicity from file "//TRIM(td_file%c_name)//"."//&
+         &  " you have to inform periodicity in namelist.")
+      ENDIF
+
+   END SUBROUTINE grid__get_info_file
+   !-------------------------------------------------------------------
+   !> @brief This subroutine get information about global domain, given mpp
+   !> strucutre.
+   !>
+   !> @details
+   !> open edge files then:
+   !> - compute NEMO pivot point 
+   !> - compute NEMO periodicity
+   !> - compute East West overlap
+   !>
+   !> @note need all processor files to be there
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !>
+   !> @param[in] td_mpp mpp structure 
+   !-------------------------------------------------------------------
+   SUBROUTINE grid__get_info_mpp(td_mpp)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP) , INTENT(INOUT) :: td_mpp
+
+      ! local variable
+      INTEGER(i4) :: il_ew
+      INTEGER(i4) :: il_pivot
+      INTEGER(i4) :: il_perio
+      INTEGER(i4) :: il_attid
+
+      TYPE(TATT)  :: tl_att
+
+      TYPE(TMPP)  :: tl_mpp
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+      ! intialise
+      il_pivot=-1
+      il_perio=-1
+      il_ew   =-1
+
+      ! copy structure
+      tl_mpp=mpp_copy(td_mpp)
+      ! select edge files
+      CALL mpp_get_contour(tl_mpp)
+      ! open mpp file to be used
+      CALL iom_mpp_open(tl_mpp)
+
+      IF( td_mpp%i_perio >= 0 .AND. td_mpp%i_perio <= 6 )THEN
+         il_perio=td_mpp%i_perio
+      ELSE
+         ! look for attribute in mpp files
+         il_attid=att_get_index(tl_mpp%t_proc(1)%t_att(:),'periodicity')
+         IF( il_attid /= 0 )THEN
+            il_perio=INT(tl_mpp%t_proc(1)%t_att(il_attid)%d_value(1),i4)
+         ENDIF
+      ENDIF
+      
+      IF( td_mpp%i_ew >= 0 )THEN
+         il_ew=td_mpp%i_ew
+      ELSE
+         ! look for attribute in mpp files
+         il_attid=att_get_index(tl_mpp%t_proc(1)%t_att(:),'ew_overlap')
+         IF( il_attid /= 0 )THEN
+            il_ew=INT(tl_mpp%t_proc(1)%t_att(il_attid)%d_value(1),i4)
+         ENDIF
+      ENDIF
+
+      SELECT CASE(il_perio)
+      CASE(3,4)
+         il_pivot=0
+      CASE(5,6)
+         il_pivot=1
+      CASE(0,1,2)
+         il_pivot=1
+      END SELECT
+
+      IF( il_pivot < 0 .OR. il_pivot > 1 )THEN
+         ! get pivot
+         il_pivot=grid_get_pivot(tl_mpp)
+      ENDIF
+
+      IF( il_perio < 0 .OR. il_perio > 6 )THEN
+         ! get periodicity
+         il_perio=grid_get_perio(tl_mpp, il_pivot)
+      ENDIF
+
+      IF( il_ew < 0 )THEN
+         ! get periodicity
+         il_ew=grid_get_ew_overlap(tl_mpp)
+      ENDIF
+
+      ! close
+      CALL iom_mpp_close(tl_mpp)
+
+      !save in mpp structure
+      td_mpp%i_ew=il_ew
+      td_mpp%i_pivot=il_pivot
+      td_mpp%i_perio=il_perio
+
+      ! save in variable of mpp structure
+      IF( ASSOCIATED(td_mpp%t_proc) )THEN
+         tl_att=att_init("ew_overlap",il_ew)
+         DO jj=1,td_mpp%i_nproc
+            DO ji=1,td_mpp%t_proc(jj)%i_nvar
+               IF( td_mpp%t_proc(jj)%t_var(ji)%t_dim(jp_I)%l_use )THEN
+                  CALL var_move_att(td_mpp%t_proc(jj)%t_var(ji),tl_att)
+               ENDIF
+            ENDDO
+         ENDDO
+      ENDIF
+
+      ! clean 
+      CALL mpp_clean(tl_mpp)
+      CALL att_clean(tl_att)
+
+      IF( td_mpp%i_perio == -1 )THEN
+         CALL logger_fatal("GRID GET INFO: can not read or compute "//&
+         &  "domain periodicity from mpp "//TRIM(td_mpp%c_name)//"."//&
+         &  " you have to inform periodicity in namelist.")
+      ENDIF
+
+   END SUBROUTINE grid__get_info_mpp
+   !-------------------------------------------------------------------
    !> @brief 
-   !> This funtion return NEMO pivot point index of the input variable.
+   !> This function compute NEMO pivot point index of the input variable.
    !> - F-point : 0
    !> - T-point : 1
    !>
+   !> @details
+   !> check north points of latitude grid (indices jpj to jpj-3) depending on which grid point
+   !> (T,F,U,V) variable is defined
+   !> 
+   !> @note variable must be at least 2D variable, and should not be coordinate
+   !> variable (i.e lon, lat)
+   !> 
    !> @warning 
-   !> - variable must be nav_lon or nav_lat
    !> - do not work with ORCA2 grid (T-point)
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @todo 
-   !> - improve check between T or F pivot.
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] cd_varname : variable name
-   !> @return NEMO pivot point index
-   !-------------------------------------------------------------------
-   !> @code
-   INTEGER(i4) FUNCTION grid_get_pivot(td_file)
+   !> - November, 2013- Subroutine written
+   !> @date September, 2014
+   !> - add dummy loop in case variable not over right point.
+   !> @date October, 2014
+   !> - work on variable structure instead of file structure
+   !
+   !> @param[in] td_lat  latitude variable structure
+   !> @param[in] td_var  variable structure
+   !> @return pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_pivot_var(td_var)
       IMPLICIT NONE
       ! Argument      
-      TYPE(TFILE),       INTENT(IN) :: td_file
+      TYPE(TVAR), INTENT(IN) :: td_var
+
+      ! function
+      INTEGER(i4) :: grid__get_pivot_var
 
       ! local variable
-      TYPE(TVAR)                        :: tl_var
+      INTEGER(i4), DIMENSION(ip_maxdim)            :: il_dim
+
+      REAL(dp)   , DIMENSION(:,:,:,:), ALLOCATABLE :: dl_value
+
+      ! loop indices
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+      ! intitalise
+      grid__get_pivot_var=-1
+
+      IF( .NOT. ASSOCIATED(td_var%d_value) .OR. &
+      &   .NOT. ALL(td_var%t_dim(1:2)%l_use) )THEN
+         CALL logger_error("GRID GET PIVOT: can not compute pivot point"//&
+         &  " with variable "//TRIM(td_var%c_name)//"."//&
+         &  " no value associated or missing dimension.")
+      ELSE
+         il_dim(:)=td_var%t_dim(:)%i_len
+
+         ALLOCATE(dl_value(il_dim(1),4,1,1))
+         ! extract value
+         dl_value(:,:,:,:)=td_var%d_value( 1:il_dim(1),          &
+         &                                 il_dim(2)-3:il_dim(2),&
+         &                                 1:1,                  &
+         &                                 1:1 )
+
+         SELECT CASE(TRIM(td_var%c_point))
+         CASE('T')
+            grid__get_pivot_var=grid__get_pivot_varT(dl_value)
+         CASE('U')
+            grid__get_pivot_var=grid__get_pivot_varU(dl_value)
+         CASE('V')
+            grid__get_pivot_var=grid__get_pivot_varV(dl_value)
+         CASE('F')
+            grid__get_pivot_var=grid__get_pivot_varF(dl_value)
+         END SELECT
+
+         ! dummy loop in case variable not over right point 
+         ! (ex: nav_lon over U-point)
+         IF( grid__get_pivot_var == -1 )THEN
+            
+            ! no pivot point found
+            CALL logger_error("GRID GET PIVOT: something wrong "//&
+            &  "when computing pivot point with variable "//&
+            &  TRIM(td_var%c_name))
+
+            DO jj=1,ip_npoint
+               SELECT CASE(TRIM(cp_grid_point(jj)))
+               CASE('T')
+                  CALL logger_debug("GRID GET PIVOT: check variable on point T")
+                  grid__get_pivot_var=grid__get_pivot_varT(dl_value)
+               CASE('U')
+                  CALL logger_debug("GRID GET PIVOT: check variable on point U")
+                  grid__get_pivot_var=grid__get_pivot_varU(dl_value)
+               CASE('V')
+                  CALL logger_debug("GRID GET PIVOT: check variable on point V")
+                  grid__get_pivot_var=grid__get_pivot_varV(dl_value)
+               CASE('F')
+                  CALL logger_debug("GRID GET PIVOT: check variable on point F")
+                  grid__get_pivot_var=grid__get_pivot_varF(dl_value)
+               END SELECT
+
+               IF( grid__get_pivot_var /= -1 )THEN
+                  CALL logger_warn("GRID GET PIVOT: variable "//&
+                  &  TRIM(td_var%c_name)//" seems to be on grid point "//&
+                  &  TRIM(cp_grid_point(jj)) )
+                  EXIT
+               ENDIF
+
+            ENDDO
+         ENDIF
+
+         IF( grid__get_pivot_var == -1 )THEN
+            CALL logger_warn("GRID GET PIVOT: not able to found pivot point. "//&
+            &  "Force to use pivot point T.")
+            grid__get_pivot_var = 1
+         ENDIF
+
+         ! clean
+         DEALLOCATE(dl_value)
+
+      ENDIF
+
+   END FUNCTION grid__get_pivot_var
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This function compute NEMO pivot point index for variable on grid T.
+   !>
+   !> @details
+   !> - F-point : 0
+   !> - T-point : 1
+   !>
+   !> @note array of value must be only the top border of the domain.
+   !> 
+   !> @author J.Paul
+   !> - October, 2014 - Initial version
+   !
+   !> @param[in] dd_value array of value
+   !> @return pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_pivot_varT(dd_value)
+      IMPLICIT NONE
+      ! Argument      
+      REAL(dp), DIMENSION(:,:,:,:), INTENT(IN) :: dd_value
+
+      ! function
+      INTEGER(i4) :: grid__get_pivot_varT
+
+      ! local variable
+      INTEGER(i4)                       :: il_midT
+      INTEGER(i4)                       :: il_midF
+
+      INTEGER(i4)                       :: it1
+      INTEGER(i4)                       :: it2
+      INTEGER(i4)                       :: jt1
+      INTEGER(i4)                       :: jt2
+
+      INTEGER(i4)                       :: if1
+      INTEGER(i4)                       :: if2
+      INTEGER(i4)                       :: jf1
+      INTEGER(i4)                       :: jf2
+
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
+
+      LOGICAL                           :: ll_check
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! intitalise
+      grid__get_pivot_varT=-1
+
+      il_dim(:)=SHAPE(dd_value(:,:,:,:))
+
+      ! T-point pivot !case of ORCA2, ORCA025, ORCA12 grid
+      jt1=4  ; jt2=2 
+      il_midT=il_dim(1)/2+1
+
+      ! F-point pivot !case of ORCA05 grid
+      jf1=4 ; jf2=3
+      il_midF=il_dim(1)/2
+
+      ! check T-point pivot
+      DO ji=2,il_midT
+         ll_check=.TRUE.
+         it1=ji
+         it2=il_dim(1)-(ji-2)
+         IF( dd_value(it1,jt1,1,1) /= dd_value(it2,jt2,1,1) )THEN
+            ll_check=.FALSE.
+            EXIT
+         ENDIF
+      ENDDO
+
+      IF( ll_check )THEN
+         CALL logger_info("GRID GET PIVOT: T-pivot")
+         grid__get_pivot_varT=1
+      ELSE
+
+         ! check F-point pivot
+         DO ji=1,il_midF
+            ll_check=.TRUE.
+            if1=ji
+            if2=il_dim(1)-(ji-1)
+            IF( dd_value(if1,jf1,1,1) /= dd_value(if2,jf2,1,1) )THEN
+               ll_check=.FALSE.
+               EXIT
+            ENDIF
+         ENDDO
+
+         IF( ll_check )THEN
+            CALL logger_info("GRID GET PIVOT: T-pivot")
+            grid__get_pivot_varT=0
+         ENDIF
+
+      ENDIF
+
+   END FUNCTION grid__get_pivot_varT
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This function compute NEMO pivot point index for variable on grid U.
+   !>
+   !> @details
+   !> - F-point : 0
+   !> - T-point : 1
+   !>
+   !> @note array of value must be only the top border of the domain.
+   !> 
+   !> @author J.Paul
+   !> - October, 2014 - Initial version
+   !
+   !> @param[in] dd_value array of value
+   !> @return pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_pivot_varU(dd_value)
+      IMPLICIT NONE
+      ! Argument      
+      REAL(dp), DIMENSION(:,:,:,:), INTENT(IN) :: dd_value
+
+      ! function
+      INTEGER(i4) :: grid__get_pivot_varU
+
+      ! local variable
+      INTEGER(i4)                       :: il_midT
+      INTEGER(i4)                       :: il_midF
+
+      INTEGER(i4)                       :: it1
+      INTEGER(i4)                       :: it2
+      INTEGER(i4)                       :: jt1
+      INTEGER(i4)                       :: jt2
+
+      INTEGER(i4)                       :: if1
+      INTEGER(i4)                       :: if2
+      INTEGER(i4)                       :: jf1
+      INTEGER(i4)                       :: jf2
+
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
+
+      LOGICAL                           :: ll_check
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! intitalise
+      grid__get_pivot_varU=-1
+
+      il_dim(:)=SHAPE(dd_value(:,:,:,:))
+
+      ! T-point pivot !case of ORCA2, ORCA025, ORCA12 grid
+      jt1=4 ; jt2=2 
+      il_midT=il_dim(1)/2+1
+
+      ! F-point pivot !case of ORCA05 grid
+      jf1=4 ; jf2=3
+      il_midF=il_dim(1)/2
+
+      ! check T-point pivot
+      DO ji=1,il_midT
+         ll_check=.TRUE.
+         it1=ji
+         it2=il_dim(1)-(ji-2)
+         IF( dd_value(it1,jt1,1,1) /= dd_value(it2-1,jt2,1,1) )THEN
+            ll_check=.FALSE.
+            EXIT
+         ENDIF
+      ENDDO
+
+      IF( ll_check )THEN
+         CALL logger_info("GRID GET PIVOT: T-pivot")
+         grid__get_pivot_varU=1
+      ELSE
+
+         ! check F-point pivot
+         DO ji=1,il_midF
+            ll_check=.TRUE.
+            if1=ji
+            if2=il_dim(1)-(ji-1)
+            IF( dd_value(if1,jf1,1,1) /= dd_value(if2-1,jf2,1,1) )THEN
+               ll_check=.FALSE.
+               EXIT
+            ENDIF
+         ENDDO
+
+         IF( ll_check )THEN
+            CALL logger_info("GRID GET PIVOT: T-pivot")
+            grid__get_pivot_varU=0
+         ENDIF
+
+      ENDIF
+
+   END FUNCTION grid__get_pivot_varU
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This function compute NEMO pivot point index for variable on grid V.
+   !>
+   !> @details
+   !> - F-point : 0
+   !> - T-point : 1
+   !>
+   !> @note array of value must be only the top border of the domain.
+   !> 
+   !> @author J.Paul
+   !> - October, 2014 - Initial version
+   !
+   !> @param[in] dd_value array of value
+   !> @return pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_pivot_varV(dd_value)
+      IMPLICIT NONE
+      ! Argument      
+      REAL(dp), DIMENSION(:,:,:,:), INTENT(IN) :: dd_value
+
+      ! function
+      INTEGER(i4) :: grid__get_pivot_varV
+
+      ! local variable
+      INTEGER(i4)                       :: il_midT
+      INTEGER(i4)                       :: il_midF
+
+      INTEGER(i4)                       :: it1
+      INTEGER(i4)                       :: it2
+      INTEGER(i4)                       :: jt1
+      INTEGER(i4)                       :: jt2
+
+      INTEGER(i4)                       :: if1
+      INTEGER(i4)                       :: if2
+      INTEGER(i4)                       :: jf1
+      INTEGER(i4)                       :: jf2
+
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
+
+      LOGICAL                           :: ll_check
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! intitalise
+      grid__get_pivot_varV=-1
+
+      il_dim(:)=SHAPE(dd_value(:,:,:,:))
+
+      ! T-point pivot !case of ORCA2, ORCA025, ORCA12 grid
+      jt1=4 ; jt2=2 
+      il_midT=il_dim(1)/2+1
+
+      ! F-point pivot !case of ORCA05 grid
+      jf1=4 ; jf2=3
+      il_midF=il_dim(1)/2
+
+      ! check T-point pivot
+      DO ji=2,il_midT
+         ll_check=.TRUE.
+         it1=ji
+         it2=il_dim(1)-(ji-2)
+         IF( dd_value(it1,jt1,1,1) /= dd_value(it2,jt2-1,1,1) )THEN
+            ll_check=.FALSE.
+            EXIT
+         ENDIF
+      ENDDO
+
+      IF( ll_check )THEN
+         CALL logger_info("GRID GET PIVOT: T-pivot")
+         grid__get_pivot_varV=1
+      ELSE
+
+         ! check F-point pivot
+         DO ji=1,il_midF
+            ll_check=.TRUE.
+            if1=ji
+            if2=il_dim(1)-(ji-1)
+            IF( dd_value(if1,jf1,1,1) /= dd_value(if2,jf2-1,1,1) )THEN
+               ll_check=.FALSE.
+               EXIT
+            ENDIF
+         ENDDO
+
+         IF( ll_check )THEN
+            CALL logger_info("GRID GET PIVOT: T-pivot")
+            grid__get_pivot_varV=0
+         ENDIF
+
+      ENDIF
+
+   END FUNCTION grid__get_pivot_varV
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This function compute NEMO pivot point index for variable on grid F.
+   !>
+   !> @details
+   !> - F-point : 0
+   !> - T-point : 1
+   !>
+   !> @note array of value must be only the top border of the domain.
+   !> 
+   !> @author J.Paul
+   !> - October, 2014 - Initial version
+   !
+   !> @param[in] dd_value array of value
+   !> @return pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_pivot_varF(dd_value)
+      IMPLICIT NONE
+      ! Argument      
+      REAL(dp), DIMENSION(:,:,:,:), INTENT(IN) :: dd_value
+
+      ! function
+      INTEGER(i4) :: grid__get_pivot_varF
+
+      ! local variable
+      INTEGER(i4)                       :: il_midT
+      INTEGER(i4)                       :: il_midF
+
+      INTEGER(i4)                       :: it1
+      INTEGER(i4)                       :: it2
+      INTEGER(i4)                       :: jt1
+      INTEGER(i4)                       :: jt2
+
+      INTEGER(i4)                       :: if1
+      INTEGER(i4)                       :: if2
+      INTEGER(i4)                       :: jf1
+      INTEGER(i4)                       :: jf2
+
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
+
+      LOGICAL                           :: ll_check
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! intitalise
+      grid__get_pivot_varF=-1
+
+      il_dim(:)=SHAPE(dd_value(:,:,:,:))
+
+      ! T-point pivot !case of ORCA2, ORCA025, ORCA12 grid
+      jt1=4 ; jt2=2 
+      il_midT=il_dim(1)/2+1
+
+      ! F-point pivot !case of ORCA05 grid
+      jf1=4 ; jf2=3
+      il_midF=il_dim(1)/2
+
+      ! check T-point pivot
+      DO ji=1,il_midT
+         ll_check=.TRUE.
+         it1=ji
+         it2=il_dim(1)-(ji-2)
+         IF( dd_value(it1,jt1,1,1) /= dd_value(it2-1,jt2-1,1,1) )THEN
+            ll_check=.FALSE.
+            EXIT
+         ENDIF
+      ENDDO
+
+      IF( ll_check )THEN
+         CALL logger_info("GRID GET PIVOT: T-pivot")
+         grid__get_pivot_varF=1
+      ELSE
+
+         ! check F-point pivot
+         DO ji=1,il_midF
+            ll_check=.TRUE.
+            if1=ji
+            if2=il_dim(1)-(ji-1)
+            IF( dd_value(if1,jf1,1,1) /= dd_value(if2-1,jf2-1,1,1) )THEN
+               ll_check=.FALSE.
+               EXIT
+            ENDIF
+         ENDDO
+
+         IF( ll_check )THEN
+            CALL logger_info("GRID GET PIVOT: T-pivot")
+            grid__get_pivot_varF=0
+         ENDIF
+
+      ENDIF
+
+   END FUNCTION grid__get_pivot_varF
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This function compute NEMO pivot point index from input file variable.
+   !> - F-point : 0
+   !> - T-point : 1
+   !>
+   !> @details
+   !> check north points of latitude grid (indices jpj to jpj-3) depending on which grid point
+   !> (T,F,U,V) variable is defined
+   !> 
+   !> @warning 
+   !> - do not work with ORCA2 grid (T-point)
+   !>
+   !> @author J.Paul
+   !> - Ocotber, 2014- Initial version
+   !
+   !> @param[in] td_file file structure
+   !> @return pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_pivot_file(td_file)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TFILE), INTENT(IN) :: td_file
+
+      ! function
+      INTEGER(i4) :: grid__get_pivot_file
+
+      ! local variable
       INTEGER(i4)                       :: il_varid
       INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
 
+      LOGICAL                           :: ll_north
+
+      TYPE(TVAR)                        :: tl_var
+      TYPE(TVAR)                        :: tl_lat
+
       ! loop indices
       INTEGER(i4) :: ji
-
-      INTEGER(i4) :: it1
-      INTEGER(i4) :: it2
-      INTEGER(i4) :: jt1
-      INTEGER(i4) :: jt2
-
-      INTEGER(i4) :: if1
-      INTEGER(i4) :: if2
-      INTEGER(i4) :: jf1
-      INTEGER(i4) :: jf2
       !----------------------------------------------------------------
-      ! initialise
-      grid_get_pivot=-1
+      ! intitalise
+      grid__get_pivot_file=-1
+
+      ! look for north fold
+      il_varid=var_get_index(td_file%t_var(:), 'latitude')
+      IF( il_varid == 0 )THEN
+         CALL logger_error("GRID GET PIVOT: no variable with name "//&
+         &  "or standard name latitude in file structure "//&
+         &  TRIM(td_file%c_name))
+      ENDIF
+      IF( ASSOCIATED(td_file%t_var(il_varid)%d_value) )THEN
+         tl_lat=var_copy(td_file%t_var(il_varid))
+      ELSE
+         tl_lat=iom_read_var(td_file, 'latitude')
+      ENDIF
+
+      ll_north=grid_is_north_fold(tl_lat)
+      ! clean
+      CALL var_clean(tl_lat)
+
+      IF( ll_north )THEN      
+         ! look for suitable variable
+         DO ji=1,td_file%i_nvar
+            IF( .NOT. ALL(td_file%t_var(ji)%t_dim(1:2)%l_use) ) CYCLE
+
+            IF( ASSOCIATED(td_file%t_var(ji)%d_value) )THEN
+               tl_var=var_copy(td_file%t_var(ji))
+            ELSE
+               il_dim(:)=td_file%t_var(ji)%t_dim(:)%i_len
+               tl_var=iom_read_var(td_file, &
+               &                   td_file%t_var(ji)%c_name, &
+               &                   id_start=(/1,il_dim(2)-3,1,1/), &
+               &                   id_count=(/il_dim(1),4,1,1/) )
+            ENDIF
+         ENDDO
+
+         IF( ASSOCIATED(tl_var%d_value) )THEN
+
+            grid__get_pivot_file=grid_get_pivot(tl_var)
+
+         ENDIF
+
+         ! clean
+         CALL var_clean(tl_var)
+      ELSE
+         CALL logger_warn("GRID GET PIVOT: no north fold. force to use T-PIVOT")
+         grid__get_pivot_file=1
+      ENDIF
+
+   END FUNCTION grid__get_pivot_file
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This function compute NEMO pivot point index from input mpp variable.
+   !> - F-point : 0
+   !> - T-point : 1
+   !>
+   !> @details
+   !> check north points of latitude grid (indices jpj to jpj-3) depending on which grid point
+   !> (T,F,U,V) variable is defined
+   !> 
+   !> @warning 
+   !> - do not work with ORCA2 grid (T-point)
+   !>
+   !> @author J.Paul
+   !> - October, 2014 - Initial version
+   !
+   !> @param[in] td_mpp   mpp file structure
+   !> @return pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_pivot_mpp(td_mpp)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP), INTENT(IN) :: td_mpp
+
+      ! function
+      INTEGER(i4) :: grid__get_pivot_mpp
+
+      ! local variable
+      INTEGER(i4)                       :: il_varid
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
+
+      LOGICAL                           :: ll_north
+
+      TYPE(TVAR)                        :: tl_var
+      TYPE(TVAR)                        :: tl_lat
+ 
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! intitalise
+      grid__get_pivot_mpp=-1
+
+      ! look for north fold
+      il_varid=var_get_index(td_mpp%t_proc(1)%t_var(:), 'latitude')
+      IF( il_varid == 0 )THEN
+         CALL logger_error("GRID GET PIVOT: no variable with name "//&
+         &  "or standard name latitude in mpp structure "//&
+         &  TRIM(td_mpp%c_name)//". Assume there is north fold and "//&
+         &  "try to get pivot point")
+
+         ll_north=.TRUE.
+      ELSE
+         IF( ASSOCIATED(td_mpp%t_proc(1)%t_var(il_varid)%d_value) )THEN
+            ! 
+            tl_lat=mpp_recombine_var(td_mpp, 'latitude')
+         ELSE
+            tl_lat=iom_mpp_read_var(td_mpp, 'latitude')
+         ENDIF      
+
+         ll_north=grid_is_north_fold(tl_lat)
+      ENDIF
+
+      IF( ll_north )THEN
+
+         IF( ASSOCIATED(tl_lat%d_value) )THEN
+            grid__get_pivot_mpp=grid_get_pivot(tl_lat)
+         ELSE
+            ! look for suitable variable
+            DO ji=1,td_mpp%t_proc(1)%i_nvar
+               IF(.NOT. ALL(td_mpp%t_proc(1)%t_var(ji)%t_dim(1:2)%l_use)) CYCLE
+
+               IF( ASSOCIATED(td_mpp%t_proc(1)%t_var(ji)%d_value) )THEN
+                  CALL logger_debug("GRID GET PIVOT: mpp_recombine_var"//&
+                  &         TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name))
+                  tl_var=mpp_recombine_var(td_mpp, &
+                  &              TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name))
+               ELSE
+                  CALL logger_debug("GRID GET PIVOT: iom_mpp_read_var "//&
+                  &        TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name))
+                  il_dim(:)=td_mpp%t_dim(:)%i_len
+
+                  ! read variable
+                  tl_var=iom_mpp_read_var(td_mpp, &
+                  &                       td_mpp%t_proc(1)%t_var(ji)%c_name, &
+                  &                       id_start=(/1,il_dim(2)-3,1,1/), &
+                  &                       id_count=(/il_dim(1),4,1,1/) )
+               ENDIF
+               EXIT
+            ENDDO
+
+            IF( ASSOCIATED(tl_var%d_value) )THEN
+
+               grid__get_pivot_mpp=grid_get_pivot(tl_var)
+
+           ELSE
+               CALL logger_warn("GRID GET PIVOT: force to use T-PIVOT")
+               grid__get_pivot_mpp=1
+            ENDIF
+
+            ! clean
+            CALL var_clean(tl_var)
+         ENDIF
+      ELSE
+         CALL logger_warn("GRID GET PIVOT: no north fold. force to use T-PIVOT")
+         grid__get_pivot_mpp=1
+      ENDIF
+
+      CALL var_clean(tl_lat)
+   END FUNCTION grid__get_pivot_mpp
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This subroutine search NEMO periodicity index given variable structure and
+   !> pivot point index.
+   !> @details
+   !> The variable must be on T point.
+   !>
+   !> 0: closed boundaries
+   !> 1: cyclic east-west boundary
+   !> 2: symmetric boundary condition across the equator
+   !> 3: North fold boundary (with a F-point pivot)
+   !> 4: North fold boundary (with a F-point pivot) and cyclic east-west boundary
+   !> 5: North fold boundary (with a T-point pivot)
+   !> 6: North fold boundary (with a T-point pivot) and cyclic east-west boundary
+   !>
+   !> @warning pivot point should have been computed before run this script. see grid_get_pivot.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Subroutine written
+   !> @date October, 2014
+   !> - work on variable structure instead of file structure
+   !
+   !> @param[in] td_var   variable structure
+   !> @param[in] id_pivot pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_perio_var(td_var, id_pivot)
+      IMPLICIT NONE
+
+      ! Argument      
+      TYPE(TVAR) , INTENT(IN) :: td_var
+      INTEGER(i4), INTENT(IN) :: id_pivot
+
+      ! function
+      INTEGER(i4) :: grid__get_perio_var
+
+      ! local variable
+      INTEGER(i4)                       :: il_perio
+
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
+
+      ! loop indices
+      !----------------------------------------------------------------
+      ! intitalise
+      grid__get_perio_var=-1
+
+      IF( id_pivot < 0 .OR. id_pivot > 1 )THEN
+         CALL logger_error("GRID GET PERIO: invalid pivot point index. "//&
+         &  "you should use grid_get_pivot to compute it")
+      ENDIF
+
+      IF( .NOT. ASSOCIATED(td_var%d_value) .OR. &
+      &   .NOT. ALL(td_var%t_dim(1:2)%l_use) )THEN
+         CALL logger_error("GRID GET PERIO: can not compute periodicity"//&
+         &  " with variable "//TRIM(td_var%c_name)//"."//&
+         &  " no value associated or missing dimension.")
+      ELSE
+
+         il_dim(:)=td_var%t_dim(:)%i_len
+
+         CALL logger_info("GRID GET PERIO: use varibale "//TRIM(td_var%c_name))
+         CALL logger_info("GRID GET PERIO: fill value "//TRIM(fct_str(td_var%d_fill)))
+         CALL logger_info("GRID GET PERIO: fill value "//TRIM(fct_str(td_var%d_value(1,1,1,1))))
+
+         IF(ALL(td_var%d_value(    1    ,    :    ,1,1)/=td_var%d_fill).AND.&
+         &  ALL(td_var%d_value(il_dim(1),    :    ,1,1)/=td_var%d_fill).AND.&
+         &  ALL(td_var%d_value(    :    ,    1    ,1,1)/=td_var%d_fill).AND.&
+         &  ALL(td_var%d_value(    :    ,il_dim(2),1,1)/=td_var%d_fill))THEN
+         ! no boundary closed
+            CALL logger_warn("GRID GET PERIO: can't determined periodicity. "//&
+            &             "there is no boundary closed for variable "//&
+            &              TRIM(td_var%c_name) )
+         ELSE
+            ! check periodicity
+            IF(ANY(td_var%d_value(   1     ,:,1,1)/=td_var%d_fill).OR.&
+            &  ANY(td_var%d_value(il_dim(1),:,1,1)/=td_var%d_fill))THEN
+            ! East-West cyclic (1,4,6)
+
+               IF( ANY(td_var%d_value(:, 1, 1, 1) /= td_var%d_fill) )THEN
+               ! South boundary not closed 
+
+                  CALL logger_debug("GRID GET PERIO: East_West cyclic")
+                  CALL logger_debug("GRID GET PERIO: South boundary not closed")
+                  CALL logger_error("GRID GET PERIO: should have been an "//&
+                  &              "impossible case")
+
+               ELSE
+               ! South boundary closed (1,4,6)
+                  CALL logger_info("GRID GET PERIO: South boundary closed")
+
+                  IF(ANY(td_var%d_value(:,il_dim(2),1,1)/=td_var%d_fill) )THEN
+                  ! North boundary not closed (4,6)
+                     CALL logger_info("GRID GET PERIO: North boundary not closed")
+                     ! check pivot
+                     SELECT CASE(id_pivot)
+                        CASE(0)
+                           ! F pivot
+                           il_perio=6
+                        CASE(1)
+                           ! T pivot
+                           il_perio=4
+                        CASE DEFAULT
+                           CALL logger_error("GRID GET PERIO: invalid pivot ")
+                     END SELECT
+                  ELSE
+                  ! North boundary closed
+                     CALL logger_info("GRID GET PERIO: North boundary closed")
+                     il_perio=1 ! North and South boundaries closed
+                  ENDIF
+
+               ENDIF
+
+            ELSE
+            ! East-West boundaries closed (0,2,3,5)
+               CALL logger_info("GRID GET PERIO: East West boundaries closed")
+
+               IF( ANY(td_var%d_value(:, 1, 1, 1) /= td_var%d_fill) )THEN
+               ! South boundary not closed (2)
+                  CALL logger_info("GRID GET PERIO: South boundary not closed")
+
+                  IF(ANY(td_var%d_value(:,il_dim(2),1,1)/=td_var%d_fill))THEN
+                  ! North boundary not closed
+                     CALL logger_debug("GRID GET PERIO: East West boundaries "//&
+                     &              "closed")
+                     CALL logger_debug("GRID GET PERIO: South boundary not closed")
+                     CALL logger_debug("GRID GET PERIO: North boundary not closed")
+                     CALL logger_error("GRID GET PERIO: should have been "//&
+                     &              "an impossible case")
+                  ELSE
+                  ! North boundary closed
+                     il_perio=2   ! East-West and North boundaries closed 
+                  ENDIF
+
+               ELSE
+               ! South boundary closed (0,3,5)
+                  CALL logger_info("GRID GET PERIO: South boundary closed")
+
+                  IF(ANY(td_var%d_value(:,il_dim(2),1,1)/=td_var%d_fill))THEN
+                  ! North boundary not closed (3,5)
+                     CALL logger_info("GRID GET PERIO: North boundary not closed")
+                     ! check pivot
+                     SELECT CASE(id_pivot)
+                        CASE(0)
+                           ! F pivot
+                           il_perio=5
+                        CASE(1)
+                           ! T pivot
+                           il_perio=3
+                        CASE DEFAULT
+                           CALL logger_error("GRID GET PERIO: invalid pivot")
+                     END SELECT
+                  ELSE
+                  ! North boundary closed   
+                     CALL logger_info("GRID GET PERIO: North boundary closed")
+                     il_perio=0   ! all boundary closed
+                  ENDIF
+
+               ENDIF
+
+            ENDIF
+
+            grid__get_perio_var=il_perio
+
+         ENDIF
+
+      ENDIF
+
+   END FUNCTION grid__get_perio_var
+   !-------------------------------------------------------------------
+   !> @brief 
+   !> This subroutine search NEMO periodicity index given file structure, and
+   !> optionaly pivot point index.
+   !> @details
+   !> The variable used must be on T point.
+   !>
+   !> 0: closed boundaries
+   !> 1: cyclic east-west boundary
+   !> 2: symmetric boundary condition across the equator
+   !> 3: North fold boundary (with a F-point pivot)
+   !> 4: North fold boundary (with a F-point pivot) and cyclic east-west boundary
+   !> 5: North fold boundary (with a T-point pivot)
+   !> 6: North fold boundary (with a T-point pivot) and cyclic east-west boundary
+   !>
+   !> @warning pivot point should have been computed before run this script. see grid_get_pivot.
+   !>
+   !> @author J.Paul
+   !> - October, 2014 - Initial version
+   !>
+   !> @param[in] td_file   file structure
+   !> @param[in] id_pivot  pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_perio_file(td_file, id_pivot)
+      IMPLICIT NONE
+
+      ! Argument      
+      TYPE(TFILE), INTENT(IN) :: td_file
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_pivot
+
+      ! function
+      INTEGER(i4) :: grid__get_perio_file
+
+      ! local variable
+      INTEGER(i4)                       :: il_varid
+      INTEGER(i4)                       :: il_pivot
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
+
+      TYPE(TVAR)                        :: tl_var
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      !initialise
+      grid__get_perio_file=-1
+
+      IF(PRESENT(id_pivot) )THEN
+         il_pivot=id_pivot
+      ELSE
+         il_pivot=grid_get_pivot(td_file)
+      ENDIF
+
+      IF( il_pivot < 0 .OR. il_pivot > 1 )THEN
+         CALL logger_error("GRID GET PERIO: invalid pivot point index. "//&
+         &  "you should use grid_get_pivot to compute it")
+      ENDIF
 
       ! look for suitable variable
@@ -134,104 +1503,34 @@
       ENDDO
 
-      IF( il_varid/=0 )THEN
-         IF( ASSOCIATED(td_file%t_var(il_varid)%d_value) )THEN
-            CALL logger_debug("GRID GET PIVOT: ASSOCIATED")
-            tl_var=td_file%t_var(il_varid)
-         ELSE
-            ! read variable
-            il_dim(:)=td_file%t_var(il_varid)%t_dim(:)%i_len
-
-            CALL logger_debug("GRID GET PIVOT: read variable")
-            tl_var=iom_read_var(td_file, td_file%t_var(il_varid)%c_name,     &
-            &                   id_start=(/1,il_dim(2)-3,1,1/), &
-            &                   id_count=(/3,4,1,1/) )
-         ENDIF
-
-         CALL logger_debug("GRID GET PIVOT: use variable "//TRIM(tl_var%c_name))
-
-         IF( ASSOCIATED(tl_var%d_value) )THEN
-
-            CALL logger_debug("GRID GET PIVOT: point "//TRIM(tl_var%c_point))
-            ! T-point pivot !case of ORCA2, ORCA025, ORCA12 grid
-            it1=1 ; jt1=4 
-            it2=3 ; jt2=2 
-
-            ! F-point pivot !case of ORCA05 grid
-            if1=1 ; jf1=4 
-            if2=2 ; jf2=3 
-
-            SELECT CASE(TRIM(tl_var%c_point))
-            CASE('T')
-               IF( ABS(tl_var%d_value(it1,jt1,1,1)) == &
-               &   ABS(tl_var%d_value(it2,jt2,1,1)) )THEN
-                  CALL logger_info("GRID GET PIVOT: T-pivot")
-                  grid_get_pivot=1
-               ELSEIF( ABS(tl_var%d_value(if1,jf1,1,1)) == &
-               &       ABS(tl_var%d_value(if2,jf2,1,1)) )THEN
-                  CALL logger_info("GRID GET PIVOT: F-pivot")
-                  grid_get_pivot=0
-               ELSE
-                  CALL logger_error("GRID GET PIVOT: something wrong when "//&
-                  &  "computing pivot point")
-               ENDIF
-            CASE('U')
-               IF( ABS(tl_var%d_value(it1  ,jt1,1,1)) == &
-               &   ABS(tl_var%d_value(it2-1,jt2,1,1)) )THEN
-                  CALL logger_info("GRID GET PIVOT: T-pivot")
-                  grid_get_pivot=1
-               ELSEIF( ABS(tl_var%d_value(if1  ,jf1,1,1)) == &
-               &       ABS(tl_var%d_value(if2-1,jf2,1,1)) )THEN
-                  CALL logger_info("GRID GET PIVOT: F-pivot")
-                  grid_get_pivot=0
-               ELSE
-                  CALL logger_error("GRID GET PIVOT: something wrong when "//&
-                  &  "computing pivot point")
-               ENDIF
-            CASE('V')
-               IF( ABS(tl_var%d_value(it1,jt1  ,1,1)) == &
-               &   ABS(tl_var%d_value(it2,jt2-1,1,1)) )THEN
-                  CALL logger_info("GRID GET PIVOT: T-pivot")
-                  grid_get_pivot=1
-               ELSEIF( ABS(tl_var%d_value(if1,jf1  ,1,1)) == &
-               &       ABS(tl_var%d_value(if2,jf2-1,1,1)) )THEN
-                  CALL logger_info("GRID GET PIVOT: F-pivot")
-                  grid_get_pivot=0
-               ELSE
-                  CALL logger_error("GRID GET PIVOT: something wrong when "//&
-                  &  "computing pivot point")
-               ENDIF
-            CASE('F')
-               IF( ABS(tl_var%d_value(it1  ,jt1  ,1,1)) == &
-               &   ABS(tl_var%d_value(it2-1,jt2-1,1,1)) )THEN
-                  CALL logger_info("GRID GET PIVOT: T-pivot")
-                  grid_get_pivot=1
-               ELSEIF( ABS(tl_var%d_value(if1  ,jf1  ,1,1)) == &
-               &       ABS(tl_var%d_value(if2-1,jf2-1,1,1)) )THEN
-                  CALL logger_info("GRID GET PIVOT: F-pivot")
-                  grid_get_pivot=0
-               ELSE
-                  CALL logger_error("GRID GET PIVOT: something wrong when "//&
-                  &  "computing pivot point")
-               ENDIF
-            END SELECT
-         ELSE
-            CALL logger_error("GRID GET PIVOT: can't compute pivot point. "//&
-            &  "no value associated to variable "//TRIM(tl_var%c_name) )
-         ENDIF
+      IF( il_varid==0 )THEN
+      
+         CALL logger_error("GRID GET PERIO: no suitable variable to compute "//&
+         &              " periodicity in file "//TRIM(td_file%c_name))
 
       ELSE
-         CALL logger_error("GRID GET PIVOT: no suitable variable to compute "//&
-         &              "pivot point in file "//TRIM(td_file%c_name))
-      ENDIF
-
-   END FUNCTION grid_get_pivot
-   !> @endcode
+
+         il_dim(:)= td_file%t_var(il_varid)%t_dim(:)%i_len
+
+         ! read variable
+         tl_var=iom_read_var(td_file, &
+         &                   td_file%t_var(il_varid)%c_name, &
+         &                   id_start=(/1,1,1,1/), &
+         &                   id_count=(/il_dim(1),il_dim(2),1,1/) )
+
+
+         grid__get_perio_file=grid_get_perio(tl_var,il_pivot)
+ 
+         ! clean 
+         CALL var_clean(tl_var)
+
+      ENDIF
+
+   END FUNCTION grid__get_perio_file
    !-------------------------------------------------------------------
    !> @brief 
-   !> This funtion return NEMO periodicity index of the input file.
+   !> This subroutine search NEMO periodicity given mpp structure and optionaly
+   !> pivot point index.
+   !> @details
    !> The variable used must be on T point.
-   !>
-   !> @note the NEMO periodicity index can't be compute from coordinates file,
-   !> neither with mpp files.
    !>
    !> 0: closed boundaries
@@ -243,36 +1542,42 @@
    !> 6: North fold boundary (with a T-point pivot) and cyclic east-west boundary
    !>
+   !> @warning pivot point should have been computed before run this script. see grid_get_pivot.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Subroutine written
-   !
-   !> @todo 
-   !> - improve check between T or F pivot.
-   !> - manage mpp case (read only border files)
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_pivot : pivot point
-   !> @return NEMO periodicity index
-   !-------------------------------------------------------------------
-   !> @code
-   INTEGER(i4) FUNCTION grid_get_perio(td_file, id_pivot)
+   !> - October, 2014 - Initial version
+   !
+   !> @param[in] td_mpp   mpp file structure
+   !> @param[in] id_pivot pivot point index
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_perio_mpp(td_mpp, id_pivot)
       IMPLICIT NONE
 
       ! Argument      
-      TYPE(TFILE), INTENT(IN) :: td_file
-      INTEGER(i4), INTENT(IN) :: id_pivot
+      TYPE(TMPP) , INTENT(IN) :: td_mpp
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_pivot
+
+      ! function
+      INTEGER(i4) :: grid__get_perio_mpp
 
       ! local variable
+      INTEGER(i4)                       :: il_varid
+      INTEGER(i4)                       :: il_pivot
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
+
       TYPE(TVAR)                        :: tl_var
-      INTEGER(i4)                       :: il_varid
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
 
       ! loop indices
       INTEGER(i4) :: ji
       !----------------------------------------------------------------
-
       ! initialise
-      grid_get_perio=-1
-
-      IF( id_pivot < 0 .OR. id_pivot > 1 )THEN
+      grid__get_perio_mpp=-1
+
+      IF(PRESENT(id_pivot) )THEN
+         il_pivot=id_pivot
+      ELSE
+         il_pivot=grid_get_pivot(td_mpp)
+      ENDIF
+
+      IF( il_pivot < 0 .OR. il_pivot > 1 )THEN
          CALL logger_error("GRID GET PERIO: invalid pivot point index. "//&
          &  "you should use grid_get_pivot to compute it")
@@ -281,7 +1586,7 @@
       ! look for suitable variable
       il_varid=0
-      DO ji=1,td_file%i_nvar
-         IF( .NOT. ALL(td_file%t_var(ji)%t_dim(1:2)%l_use) ) CYCLE
-         SELECT CASE(TRIM(fct_lower(td_file%t_var(ji)%c_stdname)) )
+      DO ji=1,td_mpp%t_proc(1)%i_nvar
+         IF( .NOT. ALL(td_mpp%t_proc(1)%t_var(ji)%t_dim(1:2)%l_use) ) CYCLE
+         SELECT CASE(TRIM(fct_lower(td_mpp%t_proc(1)%t_var(ji)%c_stdname)) )
             CASE('longitude','latitude')
             CASE DEFAULT
@@ -292,122 +1597,289 @@
 
       IF( il_varid==0 )THEN
-
+      
          CALL logger_error("GRID GET PERIO: no suitable variable to compute "//&
-         &              " periodicity in file "//TRIM(td_file%c_name))
+         &              " periodicity in file "//TRIM(td_mpp%c_name))
       ELSE
-         il_dim(:)=td_file%t_var(il_varid)%t_dim(:)%i_len
-
-         IF( ASSOCIATED(td_file%t_var(il_varid)%d_value) )THEN
-            tl_var=td_file%t_var(il_varid)
-         ELSE
-            ! read variable
-            tl_var=iom_read_var(td_file, td_file%t_var(il_varid)%c_name, &
-            &                   id_start=(/1,1,1,1/), &
-            &                   id_count=(/il_dim(1),il_dim(2),1,1/) )
+ 
+         DO ji=1,ip_maxdim
+            IF( td_mpp%t_proc(1)%t_var(il_varid)%t_dim(ji)%l_use )THEN
+               il_dim(ji)=td_mpp%t_dim(ji)%i_len
+            ELSE
+               il_dim(ji)=1
+            ENDIF
+         ENDDO
+
+         ! read variable
+         tl_var=iom_mpp_read_var(td_mpp, &
+         &                       td_mpp%t_proc(1)%t_var(il_varid)%c_name, &
+         &                       id_start=(/1,1,1,1/), &
+         &                       id_count=(/il_dim(1),il_dim(2),1,1/) )
+
+         grid__get_perio_mpp=grid_get_perio(tl_var, il_pivot)
+
+         ! clean 
+         CALL var_clean(tl_var)
+      ENDIF
+
+   END FUNCTION grid__get_perio_mpp
+   !-------------------------------------------------------------------
+   !> @brief This function get East-West overlap.
+   !
+   !> @details
+   !> If no East-West wrap return -1, 
+   !> else return the size of the ovarlap band.
+   !> East-West overlap is computed comparing longitude value of the  
+   !> South" part of the domain, to avoid  north fold boundary.
+   !>
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !>
+   !> @param[in] td_lon longitude variable structure 
+   !> @return East West overlap
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_ew_overlap_var(td_var)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TVAR), INTENT(INOUT) :: td_var
+      ! function
+      INTEGER(i4) :: grid__get_ew_overlap_var
+
+      ! local variable
+      REAL(dp), DIMENSION(:,:), ALLOCATABLE :: dl_value
+      REAL(dp), DIMENSION(:)  , ALLOCATABLE :: dl_vare
+      REAL(dp), DIMENSION(:)  , ALLOCATABLE :: dl_varw
+
+      REAL(dp)    :: dl_delta
+      REAL(dp)    :: dl_varmax
+      REAL(dp)    :: dl_varmin
+
+      INTEGER(i4) :: il_east
+      INTEGER(i4) :: il_west
+      INTEGER(i4) :: il_jmin
+      INTEGER(i4) :: il_jmax
+
+      INTEGER(i4), PARAMETER :: il_max_overlap = 5
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! initialise
+      grid__get_ew_overlap_var=-1
+
+      IF( ASSOCIATED(td_var%d_value) )THEN
+         IF( td_var%t_dim(1)%i_len > 1 )THEN
+            il_west=1
+            il_east=td_var%t_dim(1)%i_len
+
+            ALLOCATE( dl_value(td_var%t_dim(1)%i_len, &
+            &                  td_var%t_dim(2)%i_len) )
+
+            dl_value(:,:)=td_var%d_value(:,:,1,1)
+
+            ! we do not use jmax as dimension length due to north fold boundary
+            il_jmin=1+ip_ghost
+            il_jmax=(td_var%t_dim(2)%i_len-ip_ghost)/2
+
+            ALLOCATE( dl_vare(il_jmax-il_jmin+1) )
+            ALLOCATE( dl_varw(il_jmax-il_jmin+1) )
+            
+            dl_vare(:)=dl_value(il_east,il_jmin:il_jmax)
+            dl_varw(:)=dl_value(il_west,il_jmin:il_jmax)
+            
+            IF( .NOT.(  ALL(dl_vare(:)==td_var%d_fill) .AND. &
+            &           ALL(dl_varw(:)==td_var%d_fill) ) )THEN
+         
+               IF( TRIM(td_var%c_stdname) == 'longitude' )THEN
+                  WHERE( dl_value(:,:) > 180._dp .AND. &
+                  &      dl_value(:,:) /= td_var%d_fill ) 
+                     dl_value(:,:)=360.-dl_value(:,:)
+                  END WHERE
+
+                  dl_varmax=MAXVAL(dl_value(:,il_jmin:il_jmax))
+                  dl_varmin=MINVAL(dl_value(:,il_jmin:il_jmax))
+
+                  dl_delta=(dl_varmax-dl_varmin)/td_var%t_dim(1)%i_len
+
+                  IF( ALL(ABS(dl_vare(:)) - ABS(dl_varw(:)) == dl_delta) )THEN
+                     grid__get_ew_overlap_var=0
+                  ENDIF
+               ENDIF
+
+               IF( grid__get_ew_overlap_var == -1 )THEN
+                  DO ji=0,il_max_overlap
+
+                     IF( il_east-ji == il_west )THEN
+                        ! case of small domain
+                        EXIT
+                     ELSE
+                        dl_vare(:)=dl_value(il_east-ji,il_jmin:il_jmax)
+                        
+                        IF( ALL( dl_varw(:) == dl_vare(:) ) )THEN
+                           grid__get_ew_overlap_var=ji+1
+                           EXIT
+                        ENDIF
+                     ENDIF
+
+                  ENDDO
+               ENDIF
+            ENDIF
+
          ENDIF
-
-         IF(ALL(tl_var%d_value(    1    ,    :    ,1,1)/=tl_var%d_fill).AND.&
-         &  ALL(tl_var%d_value(il_dim(1),    :    ,1,1)/=tl_var%d_fill).AND.&
-         &  ALL(tl_var%d_value(    :    ,    1    ,1,1)/=tl_var%d_fill).AND.&
-         &  ALL(tl_var%d_value(    :    ,il_dim(2),1,1)/=tl_var%d_fill))THEN
-         ! no boundary closed
-            CALL logger_warn("GRID GET PERIO: can't determined periodicity. "//&
-            &             "there is no boundary closed for variable "//&
-            &              TRIM(tl_var%c_name)//" in file "//&
-            &              TRIM(td_file%c_name) )
-         ELSE
-            ! check periodicity
-            IF(ANY(tl_var%d_value(   1     ,:,1,1)/=tl_var%d_fill).OR.&
-            &  ANY(tl_var%d_value(il_dim(1),:,1,1)/=tl_var%d_fill))THEN
-            ! East-West cyclic (1,4,6)
-
-               IF( ANY(tl_var%d_value(:, 1, 1, 1) /= tl_var%d_fill) )THEN
-               ! South boundary not closed 
-
-                  CALL logger_error("GRID GET PERIO: should have been an "//&
-                  &              "impossible case")
-                  CALL logger_debug("GRID GET PERIO: East_West cyclic")
-                  CALL logger_debug("GRID GET PERIO: South boundary not closed")
-
-               ELSE
-               ! South boundary closed (1,4,6)
-                  CALL logger_info("GRID GET PERIO: South boundary closed")
-
-                  IF(ANY(tl_var%d_value(:,il_dim(2),1,1)/=tl_var%d_fill) )THEN
-                  ! North boundary not closed (4,6)
-                     CALL logger_info("GRID GET PERIO: North boundary not closed")
-                     ! check pivot
-                     SELECT CASE(id_pivot)
-                        CASE(0)
-                           ! F pivot
-                           grid_get_perio=4
-                        CASE(1)
-                           ! T pivot
-                           grid_get_perio=6
-                        CASE DEFAULT
-                           CALL logger_error("GRID GET PERIO: invalid pivot ")
-                     END SELECT
-                  ELSE
-                  ! North boundary closed
-                     CALL logger_info("GRID GET PERIO: North boundary closed")
-                     grid_get_perio=1 ! North and South boundaries closed
-                  ENDIF
-
-               ENDIF
-
-            ELSE
-            ! East-West boundaries closed (0,2,3,5)
-               CALL logger_info("GRID GET PERIO: East West boundaries closed")
-
-               IF( ANY(tl_var%d_value(:, 1, 1, 1) /= tl_var%d_fill) )THEN
-               ! South boundary not closed (2)
-                  CALL logger_info("GRID GET PERIO: South boundary not closed")
-
-                  IF(ANY(tl_var%d_value(:,il_dim(2),1,1)/=tl_var%d_fill))THEN
-                  ! North boundary not closed
-                     CALL logger_error("GRID GET PERIO: should have been "//&
-                     &              "an impossible case")
-                     CALL logger_debug("GRID GET PERIO: East West boundaries "//&
-                     &              "closed")
-                     CALL logger_debug("GRID GET PERIO: South boundary not closed")
-                     CALL logger_debug("GRID GET PERIO: North boundary not closed")
-                  ELSE
-                  ! North boundary closed
-                     grid_get_perio=2   ! East-West and North boundaries closed 
-                  ENDIF
-
-               ELSE
-               ! South boundary closed (0,3,5)
-                  CALL logger_info("GRID GET PERIO: South boundary closed")
-
-                  IF(ANY(tl_var%d_value(:,il_dim(2),1,1)/=tl_var%d_fill))THEN
-                  ! North boundary not closed (3,5)
-                     CALL logger_info("GRID GET PERIO: North boundary not closed")
-                     ! check pivot
-                     SELECT CASE(id_pivot)
-                        CASE(0)
-                           ! F pivot
-                           grid_get_perio=3
-                        CASE(1)
-                           ! T pivot
-                           grid_get_perio=5
-                        CASE DEFAULT
-                           CALL logger_error("GRID GET PERIO: invalid pivot")
-                     END SELECT
-                  ELSE
-                  ! North boundary closed   
-                     CALL logger_info("GRID GET PERIO: North boundary closed")
-                     grid_get_perio=0   ! all boundary closed
-                  ENDIF
-
-               ENDIF
-
-            ENDIF
-
+      ELSE
+         CALL logger_error("GRID GET EW OVERLAP: input variable standard name"//&
+         &  TRIM(td_var%c_stdname)//" can not be used to compute East West "//&
+         &  "overalp. no value associated. ")
+      ENDIF
+
+   END FUNCTION grid__get_ew_overlap_var
+   !-------------------------------------------------------------------
+   !> @brief This function get East-West overlap.
+   !
+   !> @details
+   !> If no East-West wrap return -1, 
+   !> else return the size of the ovarlap band.
+   !> East-West overlap is computed comparing longitude value of the  
+   !> South" part of the domain, to avoid  north fold boundary.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !>
+   !> @param[in] td_file file structure 
+   !> @return East West overlap
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_ew_overlap_file(td_file)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TFILE), INTENT(INOUT) :: td_file
+      ! function
+      INTEGER(i4) :: grid__get_ew_overlap_file
+
+      ! local variable
+      INTEGER(i4) :: il_varid
+
+      TYPE(TVAR)  :: tl_var
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      il_varid=var_get_index(td_file%t_var(:), 'longitude')
+      IF( il_varid /= 0 )THEN
+         ! read longitude on boundary
+         tl_var=iom_read_var(td_file, 'longitude')
+      ELSE
+         DO ji=1,td_file%i_nvar
+            IF( .NOT. ALL(td_file%t_var(ji)%t_dim(1:2)%l_use) ) CYCLE
+
+            tl_var=iom_read_var(td_file, td_file%t_var(ji)%c_name)
+            EXIT
+         ENDDO
+      ENDIF
+
+      grid__get_ew_overlap_file=grid_get_ew_overlap(tl_var)
+
+      ! clean
+      CALL var_clean(tl_var)
+
+   END FUNCTION grid__get_ew_overlap_file
+   !-------------------------------------------------------------------
+   !> @brief This function get East-West overlap.
+   !
+   !> @details
+   !> If no East-West wrap return -1, 
+   !> else return the size of the ovarlap band.
+   !> East-West overlap is computed comparing longitude value of the  
+   !> South" part of the domain, to avoid  north fold boundary.
+   !>
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !>
+   !> @param[in] td_mpp mpp structure 
+   !> @return East West overlap
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_ew_overlap_mpp(td_mpp)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP), INTENT(INOUT) :: td_mpp
+      ! function
+      INTEGER(i4) :: grid__get_ew_overlap_mpp
+
+      ! local variable
+      INTEGER(i4) :: il_ew
+      INTEGER(i4) :: il_varid
+
+      TYPE(TVAR)  :: tl_var
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      ! initialise
+      grid__get_ew_overlap_mpp=td_mpp%i_ew
+
+      ! read longitude on boundary
+      il_varid=var_get_index(td_mpp%t_proc(1)%t_var(:),'longitude')
+      IF( il_varid /= 0 )THEN
+         tl_var=iom_mpp_read_var(td_mpp, 'longitude')
+      ELSE
+         DO ji=1,td_mpp%t_proc(1)%i_nvar
+            IF( .NOT. ALL(td_mpp%t_proc(1)%t_var(ji)%t_dim(1:2)%l_use) ) CYCLE
+
+            tl_var=iom_mpp_read_var(td_mpp, td_mpp%t_proc(1)%t_var(ji)%c_name)
+            EXIT
+         ENDDO         
+      ENDIF
+
+      il_ew=grid_get_ew_overlap(tl_var)
+      IF( il_ew >= 0 )THEN
+         grid__get_ew_overlap_mpp=il_ew
+      ENDIF
+
+
+      ! clean
+      CALL var_clean(tl_var)
+
+   END FUNCTION grid__get_ew_overlap_mpp
+   !-------------------------------------------------------------------
+   !> @brief This subroutine check if there is north fold.
+   !>
+   !> @details
+   !> check if maximum latitude greater than 88°N 
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] td_lat latitude variable structure 
+   !-------------------------------------------------------------------
+   LOGICAL FUNCTION grid_is_north_fold(td_lat)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TVAR), INTENT(IN) :: td_lat
+
+      ! local variable
+      ! loop indices
+      !----------------------------------------------------------------
+   
+      ! init
+      grid_is_north_fold=.FALSE.
+
+      IF( .NOT. ASSOCIATED(td_lat%d_value) )THEN
+         CALL logger_error("GRID IS NORTH FOLD: "//&
+         &                 " no value associated to latitude")
+      ELSE      
+         IF( MAXVAL(td_lat%d_value(:,:,:,:), &
+         &          td_lat%d_value(:,:,:,:)/= td_lat%d_fill) >= 88.0 )THEN
+
+            grid_is_north_fold=.TRUE.
+            
          ENDIF
       ENDIF
 
-   END FUNCTION grid_get_perio
-   !> @endcode
+   END FUNCTION grid_is_north_fold
    !-------------------------------------------------------------------
    !> @brief This subroutine check domain validity.
@@ -415,23 +1887,21 @@
    !> @details
    !> If maximum latitude greater than 88°N, program will stop. 
-   !> It is not able to manage north fold boundary for now.
+   !> @note Not able to manage north fold for now.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_coord : coordinate file 
-   !> @param[in] id_imin : i-direction lower left  point indice  
-   !> @param[in] id_imax : i-direction upper right point indice 
-   !> @param[in] id_jmin : j-direction lower left  point indice 
-   !> @param[in] id_jmax : j-direction upper right point indice 
-   !>
-   !> @todo
-   !> - use domain instead of start count
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !
+   !> @param[in] cd_coord  coordinate file 
+   !> @param[in] id_imin   i-direction lower left  point indice  
+   !> @param[in] id_imax   i-direction upper right point indice 
+   !> @param[in] id_jmin   j-direction lower left  point indice 
+   !> @param[in] id_jmax   j-direction upper right point indice 
+   !-------------------------------------------------------------------
    SUBROUTINE grid_check_dom(td_coord, id_imin, id_imax, id_jmin, id_jmax)
       IMPLICIT NONE
       ! Argument      
-      TYPE(TFILE), INTENT(IN) :: td_coord
+      TYPE(TMPP) , INTENT(IN) :: td_coord
       INTEGER(i4), INTENT(IN) :: id_imin
       INTEGER(i4), INTENT(IN) :: id_imax
@@ -440,16 +1910,13 @@
 
       ! local variable
-      TYPE(TVAR)                        :: tl_var
-
-      TYPE(TFILE)                       :: tl_coord
-
-      TYPE(TMPP)                        :: tl_mppcoord
-
-      TYPE(TDOM)                        :: tl_dom
-
+      TYPE(TVAR) :: tl_var
+
+      TYPE(TMPP) :: tl_coord
+
+      TYPE(TDOM) :: tl_dom
       ! loop indices
       !----------------------------------------------------------------
 
-      IF( id_jmin >= id_jmax )THEN
+      IF( id_jmin > id_jmax .OR. id_jmax == 0 )THEN
 
          CALL logger_fatal("GRID CHECK DOM: invalid domain. "//&
@@ -457,9 +1924,4 @@
 
       ELSE
-
-         IF( td_coord%i_id == 0 )THEN
-            CALL logger_error("GRID CHECK DOM: can not check domain. "//&
-            &  " file "//TRIM(td_coord%c_name)//" not opened." )
-         ELSE
 
             IF( id_imin == id_imax .AND. td_coord%i_ew < 0 )THEN
@@ -469,36 +1931,23 @@
             ENDIF
 
-            !1- read domain
-            tl_coord=td_coord
-            CALL iom_open(tl_coord)
-
-            !1-1 compute domain
+            ! copy structure
+            tl_coord=mpp_copy(td_coord)
+
+            ! compute domain
             tl_dom=dom_init( tl_coord,        &
-            &                 id_imin, id_imax,&
-            &                 id_jmin, id_jmax )
+            &                id_imin, id_imax,&
+            &                id_jmin, id_jmax )
             
-            !1-2 close file
-            CALL iom_close(tl_coord)
-
-            !1-3 read variables on domain (ugly way to do it, have to work on it)
-            !1-3-1 init mpp structure
-            tl_mppcoord=mpp_init(tl_coord)   
-
-            CALL file_clean(tl_coord)
-
-            !1-3-2 get processor to be used
-            CALL mpp_get_use( tl_mppcoord, tl_dom )
-
-            !1-3-3 open mpp files
-            CALL iom_mpp_open(tl_mppcoord)
-
-            !1-3-4 read variable value on domain
-            tl_var=iom_mpp_read_var(tl_mppcoord,'latitude',td_dom=tl_dom)
-
-            !1-3-5 close mpp files
-            CALL iom_mpp_close(tl_mppcoord)
-
-            !1-3-6 clean structure
-            CALL mpp_clean(tl_mppcoord)
+            ! open mpp files to be used
+            CALL iom_dom_open(tl_coord, tl_dom)
+
+            ! read variable value on domain
+            tl_var=iom_dom_read_var(tl_coord,'latitude',tl_dom)
+
+            ! close mpp files
+            CALL iom_dom_close(tl_coord)
+
+            ! clean structure
+            CALL mpp_clean(tl_coord)
 
             IF( MAXVAL(tl_var%d_value(:,:,:,:), &
@@ -513,41 +1962,49 @@
 
             ! clean
+            CALL dom_clean(tl_dom)
             CALL var_clean(tl_var)
 
-         ENDIF
-
-
       ENDIF
 
    END SUBROUTINE grid_check_dom
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function get closest coarse grid indices of fine grid domain.
    !
    !> @details
-   !>
-   !
+   !> it use coarse and fine grid coordinates files.
+   !> optionally, you could specify the array of refinment factor (default 1.)
+   !> optionally, you could specify on which Arakawa grid point you want to
+   !> work (default 'T')
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_coord0 : coarse grid coordinate structure
-   !> @param[in] td_coord1 : fine grid coordinate structure
-   !> @return coarse grid indices (/ (/imin0, imax0/), (/jmin0, jmax0/) /)
-   !> @todo
-   !> - use domain instead of start count
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION grid_get_coarse_index_ff( td_coord0, td_coord1, &
-   &                                  id_rho )
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - use grid point to read coordinates variable. 
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !>
+   !> @param[in] td_coord0 coarse grid coordinate mpp structure
+   !> @param[in] td_coord1 fine grid coordinate mpp structure
+   !> @param[in] id_rho    array of refinment factor (default 1.)
+   !> @param[in] cd_point  Arakawa grid point (default 'T').
+   !> @return coarse grid indices(/(/imin0, imax0/), (/jmin0, jmax0/)/)
+   !>                                     
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_coarse_index_ff( td_coord0, td_coord1, &
+   &                                   id_rho, cd_point )
       IMPLICIT NONE
       ! Argument
-      TYPE(TFILE), INTENT(IN) :: td_coord0
-      TYPE(TFILE), INTENT(IN) :: td_coord1
-      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      TYPE(TMPP)                    , INTENT(IN) :: td_coord0
+      TYPE(TMPP)                    , INTENT(IN) :: td_coord1
+      INTEGER(i4)     , DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      CHARACTER(LEN=*)              , INTENT(IN), OPTIONAL :: cd_point
 
       ! function
-      INTEGER(i4), DIMENSION(2,2,2) :: grid_get_coarse_index_ff
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_coarse_index_ff
 
       ! local variable
+      TYPE(TMPP) :: tl_coord0
+      TYPE(TMPP) :: tl_coord1
+
       TYPE(TVAR)  :: tl_lon0
       TYPE(TVAR)  :: tl_lat0
@@ -555,10 +2012,8 @@
       TYPE(TVAR)  :: tl_lat1
 
-      INTEGER(i4) , DIMENSION(:), ALLOCATABLE :: il_rho
-
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count
-      INTEGER(i4), DIMENSION(2)         :: il_xghost0
-      INTEGER(i4), DIMENSION(2)         :: il_xghost1
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
+
+      INTEGER(i4), DIMENSION(2,2)         :: il_xghost0
+      INTEGER(i4), DIMENSION(2,2)         :: il_xghost1
 
       INTEGER(i4) :: il_imin0
@@ -567,8 +2022,6 @@
       INTEGER(i4) :: il_jmax0
 
-      INTEGER(i4) :: il_imin1
-      INTEGER(i4) :: il_imax1
-      INTEGER(i4) :: il_jmin1
-      INTEGER(i4) :: il_jmax1
+      CHARACTER(LEN= 1) :: cl_point
+      CHARACTER(LEN=lc) :: cl_name
 
       ! loop indices
@@ -576,85 +2029,78 @@
 
       ! init
-      grid_get_coarse_index_ff(:,:,:)=0
-
-      ALLOCATE(il_rho(ig_ndim))
+      grid__get_coarse_index_ff(:,:)=0
+
+      ALLOCATE(il_rho(ip_maxdim))
       il_rho(:)=1
       IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
 
-      IF( td_coord0%i_id == 0 .OR. td_coord1%i_id == 0 )THEN
-         CALL logger_error("GRID GET COARSE INDEX: can not get corase "//&
-         &  "grid indices. file "//TRIM(td_coord0%c_name)//" and/or "//&
-         &   TRIM(td_coord1%c_name)//" not opened." )
+      cl_point='T'
+      IF( PRESENT(cd_point) ) cl_point=TRIM(fct_upper(cd_point))
+
+      ! copy structure
+      tl_coord0=mpp_copy(td_coord0)
+      tl_coord1=mpp_copy(td_coord1)
+
+      IF( .NOT. ASSOCIATED(tl_coord0%t_proc) .OR. &
+      &   .NOT. ASSOCIATED(tl_coord1%t_proc) )THEN
+         CALL logger_error("GRID GET COARSE INDEX: can not get coarse "//&
+         &  "grid indices. decompsition of mpp file "//TRIM(tl_coord0%c_name)//&
+         &  " and/or "//TRIM(tl_coord1%c_name)//" not defined." )
       ELSE
-         !1- Coarse grid
+         ! Coarse grid
+         ! get ghost cell factor on coarse grid
+         il_xghost0(:,:)=grid_get_ghost( tl_coord0 )
+
+         ! open mpp files
+         CALL iom_mpp_open(tl_coord0)
+
          ! read coarse longitue and latitude
-         tl_lon0=iom_read_var(td_coord0,'longitude')
-         tl_lat0=iom_read_var(td_coord0,'latitude')
-
-         ! get ghost cell factor on coarse grid
-         il_xghost0(:)=grid_get_ghost( tl_lon0, tl_lat0 )
-
-         il_imin0=1+il_xghost0(1)*ig_ghost
-         il_jmin0=1+il_xghost0(2)*ig_ghost
-
-         il_imax0=tl_lon0%t_dim(1)%i_len-il_xghost0(1)*ig_ghost
-         il_jmax0=tl_lon0%t_dim(2)%i_len-il_xghost0(2)*ig_ghost
-
-         CALL var_clean(tl_lon0)
-         CALL var_clean(tl_lat0)
-
-         ! read coarse longitue and latitude without ghost cell
-         il_start(:)=(/il_imin0,il_jmin0,1,1/)
-         il_count(:)=(/il_imax0-il_imin0+1, &
-         &             il_jmax0-il_jmin0+1, &
-         &             tl_lon0%t_dim(3)%i_len, &
-         &             tl_lon0%t_dim(4)%i_len /)
-
-         tl_lon0=iom_read_var(td_coord0,'longitude',il_start(:), il_count(:))
-         tl_lat0=iom_read_var(td_coord0,'latitude' ,il_start(:), il_count(:))
+         WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         tl_lon0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+         WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         tl_lat0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
          
-         !2- Fine grid
+         CALL grid_del_ghost(tl_lon0, il_xghost0(:,:))
+         CALL grid_del_ghost(tl_lat0, il_xghost0(:,:))
+
+         ! close mpp files
+         CALL iom_mpp_close(tl_coord0)
+
+         ! Fine grid
+
+         ! get ghost cell factor on fine grid
+         il_xghost1(:,:)=grid_get_ghost( tl_coord1 )
+
+         ! open mpp files
+         CALL iom_mpp_open(tl_coord1)
+
          ! read fine longitue and latitude
-         tl_lon1=iom_read_var(td_coord1,'longitude')
-         tl_lat1=iom_read_var(td_coord1,'latitude')
-
-         ! get ghost cell factor on fine grid
-         il_xghost1(:)=grid_get_ghost( tl_lon1, tl_lat1 )
-
-         il_imin1=1+il_xghost1(1)*ig_ghost
-         il_jmin1=1+il_xghost1(2)*ig_ghost
-
-         il_imax1=tl_lon1%t_dim(1)%i_len-il_xghost1(1)*ig_ghost
-         il_jmax1=tl_lon1%t_dim(2)%i_len-il_xghost1(2)*ig_ghost
-
-         CALL var_clean(tl_lon1)
-         CALL var_clean(tl_lat1)
-
-         ! read fine longitue and latitude without ghost cell
-         il_start(:)=(/il_imin1,il_jmin1,1,1/)
-         il_count(:)=(/il_imax1-il_imin1+1, &
-         &             il_jmax1-il_jmin1+1, &
-         &             tl_lon1%t_dim(3)%i_len, &
-         &             tl_lon1%t_dim(4)%i_len /)
-
-         tl_lon1=iom_read_var(td_coord1,'longitude',il_start(:), il_count(:))
-
-         tl_lat1=iom_read_var(td_coord1,'latitude' ,il_start(:), il_count(:))
+         WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         tl_lon1=iom_mpp_read_var(tl_coord1, TRIM(cl_name)) 
+         WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         tl_lat1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
  
-         !3- compute
-         
-         grid_get_coarse_index_ff(:,:,:)=grid_get_coarse_index(tl_lon0,tl_lat0,&
-         &                                                     tl_lon1,tl_lat1,&
-         &                                                     il_rho(:) )
-
-         il_imin0=grid_get_coarse_index_ff(1,1,1)-il_xghost0(1)*ig_ghost
-         il_imax0=grid_get_coarse_index_ff(1,2,1)+il_xghost0(1)*ig_ghost
-         il_jmin0=grid_get_coarse_index_ff(2,1,1)-il_xghost0(2)*ig_ghost
-         il_jmax0=grid_get_coarse_index_ff(2,2,1)+il_xghost0(2)*ig_ghost
-
-         grid_get_coarse_index_ff(1,1,1)=il_imin0
-         grid_get_coarse_index_ff(1,2,1)=il_imax0
-         grid_get_coarse_index_ff(2,1,1)=il_jmin0
-         grid_get_coarse_index_ff(2,2,1)=il_jmax0
+         CALL grid_del_ghost(tl_lon1, il_xghost1(:,:))
+         CALL grid_del_ghost(tl_lat1, il_xghost1(:,:))
+
+         ! close mpp files
+         CALL iom_mpp_close(tl_coord1)
+
+         ! compute
+         grid__get_coarse_index_ff(:,:)=grid_get_coarse_index(tl_lon0,tl_lat0,&
+         &                                                    tl_lon1,tl_lat1,&
+         &                                                    il_rho(:) )
+
+         ! add ghost cell to indices
+         il_imin0=grid__get_coarse_index_ff(1,1)+il_xghost0(jp_I,1)*ip_ghost
+         il_imax0=grid__get_coarse_index_ff(1,2)+il_xghost0(jp_I,1)*ip_ghost
+
+         il_jmin0=grid__get_coarse_index_ff(2,1)+il_xghost0(jp_J,1)*ip_ghost
+         il_jmax0=grid__get_coarse_index_ff(2,2)+il_xghost0(jp_J,1)*ip_ghost
+
+         grid__get_coarse_index_ff(jp_I,1)=il_imin0
+         grid__get_coarse_index_ff(jp_I,2)=il_imax0
+         grid__get_coarse_index_ff(jp_J,1)=il_jmin0
+         grid__get_coarse_index_ff(jp_J,2)=il_jmax0
 
          CALL var_clean(tl_lon0)
@@ -665,34 +2111,49 @@
       ENDIF
 
-   END FUNCTION grid_get_coarse_index_ff
-   !> @endcode
+      ! clean
+      CALL mpp_clean(tl_coord0)
+      CALL mpp_clean(tl_coord1)
+      DEALLOCATE(il_rho)
+
+   END FUNCTION grid__get_coarse_index_ff
    !-------------------------------------------------------------------
    !> @brief This function get closest coarse grid indices of fine grid domain.
    !
    !> @details
-   !>
-   !
+   !> it use coarse array of longitude and latitude and fine grid coordinates file.
+   !> optionaly, you could specify the array of refinment factor (default 1.)
+   !> optionally, you could specify on which Arakawa grid point you want to
+   !> work (default 'T')
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_longitude0 : coarse grid longitude
-   !> @param[in] td_latitude0  : coarse grid latitude
-   !> @param[in] td_coord1 : fine grid coordinate structure
-   !> @return coarse grid indices (/ (/imin0, imax0/), (/jmin0, jmax0/) /)
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION grid_get_coarse_index_cf( td_lon0, td_lat0, td_coord1, &
-   &                                  id_rho )
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - use grid point to read coordinates variable.
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !>
+   !> @param[in] td_longitude0   coarse grid longitude
+   !> @param[in] td_latitude0    coarse grid latitude
+   !> @param[in] td_coord1       fine grid coordinate mpp structure
+   !> @param[in] id_rho          array of refinment factor
+   !> @param[in] cd_point        Arakawa grid point (default 'T')
+   !> @return coarse grid indices (/(/imin0, imax0/), (/jmin0, jmax0/)/)
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_coarse_index_cf( td_lon0, td_lat0, td_coord1, &
+   &                                   id_rho, cd_point )
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR ), INTENT(IN) :: td_lon0
-      TYPE(TVAR ), INTENT(IN) :: td_lat0
-      TYPE(TFILE), INTENT(IN) :: td_coord1
-      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      TYPE(TVAR )                   , INTENT(IN) :: td_lon0
+      TYPE(TVAR )                   , INTENT(IN) :: td_lat0
+      TYPE(TMPP )                   , INTENT(IN) :: td_coord1
+      INTEGER(i4)     , DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      CHARACTER(LEN=*)              , INTENT(IN), OPTIONAL :: cd_point
 
       ! function
-      INTEGER(i4), DIMENSION(2,2,2) :: grid_get_coarse_index_cf
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_coarse_index_cf
 
       ! local variable
+      TYPE(TMPP)  :: tl_coord1
+
       TYPE(TVAR)  :: tl_lon1
       TYPE(TVAR)  :: tl_lat1
@@ -700,12 +2161,8 @@
       INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
 
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count
-      INTEGER(i4), DIMENSION(2)         :: il_xghost
-
-      INTEGER(i4) :: il_imin1
-      INTEGER(i4) :: il_imax1
-      INTEGER(i4) :: il_jmin1
-      INTEGER(i4) :: il_jmax1
+      INTEGER(i4), DIMENSION(2,2)       :: il_xghost
+
+      CHARACTER(LEN= 1) :: cl_point
+      CHARACTER(LEN=lc) :: cl_name
 
       ! loop indices
@@ -713,13 +2170,19 @@
 
       ! init
-      grid_get_coarse_index_cf(:,:,:)=0
-
-      ALLOCATE(il_rho(ig_ndim) )
+      grid__get_coarse_index_cf(:,:)=0
+
+      ALLOCATE(il_rho(ip_maxdim) )
       il_rho(:)=1
       IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
 
-      IF( td_coord1%i_id == 0 )THEN
-         CALL logger_error("GRID GET COARSE INDEX: file "//&
-         &   TRIM(td_coord1%c_name)//" not opened." )
+      ! copy structure
+      tl_coord1=mpp_copy(td_coord1)
+      
+      cl_point='T'
+      IF( PRESENT(cd_point) ) cl_point=TRIM(fct_upper(cd_point))
+
+      IF( .NOT. ASSOCIATED(tl_coord1%t_proc) )THEN
+         CALL logger_error("GRID GET COARSE INDEX: decompsition of mpp "//&
+         &  "file "//TRIM(tl_coord1%c_name)//" not defined." )
 
       ELSE IF( .NOT. ASSOCIATED(td_lon0%d_value) .OR. &
@@ -731,36 +2194,35 @@
       ELSE
          
-         !1- Fine grid
+         IF( TRIM(td_lon0%c_point)/='' )THEN
+            cl_point=TRIM(td_lon0%c_point)
+         ELSEIF( TRIM(td_lat0%c_point)/='' )THEN
+            cl_point=TRIM(td_lat0%c_point)
+         ENDIF
+
+         ! Fine grid
+         ! get ghost cell factor on fine grid
+         il_xghost(:,:)=grid_get_ghost( tl_coord1 )
+
+         ! open mpp files
+         CALL iom_mpp_open(tl_coord1)
+
          ! read fine longitue and latitude
-         tl_lon1=iom_read_var(td_coord1,'longitude')
-         tl_lat1=iom_read_var(td_coord1,'latitude')
-
-         ! get ghost cell factor on fine grid
-         il_xghost(:)=grid_get_ghost( tl_lon1, tl_lat1 )
-
-         il_imin1=1+il_xghost(1)*ig_ghost
-         il_jmin1=1+il_xghost(2)*ig_ghost
-
-         il_imax1=tl_lon1%t_dim(1)%i_len-il_xghost(1)*ig_ghost
-         il_jmax1=tl_lon1%t_dim(2)%i_len-il_xghost(2)*ig_ghost
-
-         CALL var_clean(tl_lon1)
-         CALL var_clean(tl_lat1)
-
-         ! read fine longitue and latitude without ghost cell
-         il_start(:)=(/il_imin1,il_jmin1,1,1/)
-         il_count(:)=(/il_imax1-il_imin1+1, &
-         &             il_jmax1-il_jmin1+1, &
-         &             tl_lon1%t_dim(3)%i_len, &
-         &             tl_lon1%t_dim(4)%i_len /)
-
-         tl_lon1=iom_read_var(td_coord1,'longitude',il_start(:), il_count(:))
-         tl_lat1=iom_read_var(td_coord1,'latitude' ,il_start(:), il_count(:))
+         WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         tl_lon1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
+         WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         tl_lat1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
          
-         !3- compute
-         grid_get_coarse_index_cf(:,:,:)=grid_get_coarse_index(td_lon0,td_lat0,&
-         &                                                     tl_lon1,tl_lat1,&
-         &                                                     il_rho(:) )
-
+         CALL grid_del_ghost(tl_lon1, il_xghost(:,:))
+         CALL grid_del_ghost(tl_lat1, il_xghost(:,:))
+
+         ! close mpp files
+         CALL iom_mpp_close(tl_coord1)
+
+         ! compute
+         grid__get_coarse_index_cf(:,:)=grid_get_coarse_index(td_lon0,td_lat0,&
+         &                                                    tl_lon1,tl_lat1,&
+         &                                                    il_rho(:), cl_point )
+
+         
          CALL var_clean(tl_lon1)
          CALL var_clean(tl_lat1)         
@@ -768,36 +2230,47 @@
       ENDIF
 
-   END FUNCTION grid_get_coarse_index_cf
-   !> @endcode
+      DEALLOCATE(il_rho)
+      CALL mpp_clean(tl_coord1)
+
+   END FUNCTION grid__get_coarse_index_cf
    !-------------------------------------------------------------------
    !> @brief This function get closest coarse grid indices of fine grid domain.
    !
    !> @details
-   !>
-   !> @warning use ghost cell so can not be used on extracted domain without
-   !> ghost cell
-   !
+   !> it use coarse grid coordinates file and fine grid array of longitude and latitude.
+   !> optionaly, you could specify the array of refinment factor (default 1.)
+   !> optionally, you could specify on which Arakawa grid point you want to
+   !> work (default 'T')
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_coord0 : coarse grid coordinate structure
-   !> @param[in] td_lon1 : fine grid longitude
-   !> @param[in] td_lat1 : fine grid latitude
-   !> @return coarse grid indices (/ (/imin0, imax0/), (/jmin0, jmax0/) /)
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION grid_get_coarse_index_fc( td_coord0, td_lon1, td_lat1, &
-   &                                  id_rho )
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - use grid point to read coordinates variable.
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !> 
+   !> @param[in] td_coord0 coarse grid coordinate mpp structure
+   !> @param[in] td_lon1   fine grid longitude
+   !> @param[in] td_lat1   fine grid latitude
+   !> @param[in] id_rho    array of refinment factor (default 1.)
+   !> @param[in] cd_point  Arakawa grid point (default 'T')
+   !> @return coarse grid indices (/(/imin0, imax0/), (/jmin0, jmax0/)/)
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_coarse_index_fc( td_coord0, td_lon1, td_lat1, &
+   &                                  id_rho, cd_point )
       IMPLICIT NONE
       ! Argument
-      TYPE(TFILE), INTENT(IN) :: td_coord0
-      TYPE(TVAR ), INTENT(IN) :: td_lon1
-      TYPE(TVAR ), INTENT(IN) :: td_lat1
-      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      TYPE(TMPP )                   , INTENT(IN) :: td_coord0
+      TYPE(TVAR )                   , INTENT(IN) :: td_lon1
+      TYPE(TVAR )                   , INTENT(IN) :: td_lat1
+      INTEGER(i4)     , DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      CHARACTER(LEN=*)              , INTENT(IN), OPTIONAL :: cd_point
 
       ! function
-      INTEGER(i4), DIMENSION(2,2,2) :: grid_get_coarse_index_fc
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_coarse_index_fc
 
       ! local variable
+      TYPE(TMPP)  :: tl_coord0
+
       TYPE(TVAR)  :: tl_lon0
       TYPE(TVAR)  :: tl_lat0
@@ -805,7 +2278,5 @@
       INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
 
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count
-      INTEGER(i4), DIMENSION(2)         :: il_xghost
+      INTEGER(i4), DIMENSION(2,2)       :: il_xghost
 
       INTEGER(i4) :: il_imin0
@@ -814,4 +2285,6 @@
       INTEGER(i4) :: il_jmax0
 
+      CHARACTER(LEN= 1) :: cl_point
+      CHARACTER(LEN=lc) :: cl_name      
 
       ! loop indices
@@ -819,13 +2292,19 @@
 
       ! init
-      grid_get_coarse_index_fc(:,:,:)=0
-
-      ALLOCATE(il_rho(ig_ndim))
+      grid__get_coarse_index_fc(:,:)=0
+
+      ALLOCATE(il_rho(ip_maxdim))
       il_rho(:)=1
       IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
 
-      IF( td_coord0%i_id == 0 )THEN
-         CALL logger_error("GRID GET COARSE INDEX: file "//&
-         &                 TRIM(td_coord0%c_name)//" not opened." )
+      cl_point='T'
+      IF( PRESENT(cd_point) ) cl_point=TRIM(fct_upper(cd_point))
+
+      ! copy structure
+      tl_coord0=mpp_copy(td_coord0)
+
+      IF( .NOT. ASSOCIATED(tl_coord0%t_proc) )THEN
+         CALL logger_error("GRID GET COARSE INDEX: decompsition of mpp "//&
+         &  "file "//TRIM(tl_coord0%c_name)//" not defined." )
 
       ELSE IF( .NOT. ASSOCIATED(td_lon1%d_value) .OR. &
@@ -836,83 +2315,95 @@
 
       ELSE
+
+         IF( TRIM(td_lon1%c_point)/='' )THEN
+            cl_point=TRIM(td_lon1%c_point)
+         ELSEIF( TRIM(td_lat1%c_point)/='' )THEN
+            cl_point=TRIM(td_lat1%c_point)
+         ENDIF
+
+         ! get ghost cell factor on coarse grid
+         il_xghost(:,:)=grid_get_ghost( tl_coord0 )
+
+         ! open mpp files
+         CALL iom_mpp_open(tl_coord0)
+
          ! read coarse longitue and latitude
-         tl_lon0=iom_read_var(td_coord0,'longitude')
-         tl_lat0=iom_read_var(td_coord0,'latitude')
-
-         ! get ghost cell factor on coarse grid
-         il_xghost(:)=grid_get_ghost( tl_lon0, tl_lat0 )
-
-         il_imin0=1+il_xghost(1)*ig_ghost
-         il_jmin0=1+il_xghost(2)*ig_ghost
-
-         il_imax0=tl_lon0%t_dim(1)%i_len-il_xghost(1)*ig_ghost
-         il_jmax0=tl_lon0%t_dim(2)%i_len-il_xghost(2)*ig_ghost
+         WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         tl_lon0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+         WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         tl_lat0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+
+         CALL grid_del_ghost(tl_lon0, il_xghost(:,:))
+         CALL grid_del_ghost(tl_lat0, il_xghost(:,:))
+
+         ! close mpp files
+         CALL iom_mpp_close(tl_coord0)
+
+         grid__get_coarse_index_fc(:,:)=grid_get_coarse_index(tl_lon0,tl_lat0,&
+         &                                                    td_lon1,td_lat1,&
+         &                                                    il_rho(:), cl_point )
+
+         ! remove ghost cell
+         il_imin0=grid__get_coarse_index_fc(1,1)+il_xghost(jp_I,1)*ip_ghost
+         il_imax0=grid__get_coarse_index_fc(1,2)+il_xghost(jp_I,1)*ip_ghost
+
+         il_jmin0=grid__get_coarse_index_fc(2,1)+il_xghost(jp_J,1)*ip_ghost
+         il_jmax0=grid__get_coarse_index_fc(2,2)+il_xghost(jp_J,1)*ip_ghost
+
+         grid__get_coarse_index_fc(1,1)=il_imin0
+         grid__get_coarse_index_fc(1,2)=il_imax0
+         grid__get_coarse_index_fc(2,1)=il_jmin0
+         grid__get_coarse_index_fc(2,2)=il_jmax0
 
          CALL var_clean(tl_lon0)
          CALL var_clean(tl_lat0)
 
-         ! read coarse longitue and latitude without ghost cell
-         il_start(:)=(/il_imin0,il_jmin0,1,1/)
-         il_count(:)=(/il_imax0-il_imin0+1, &
-         &             il_jmax0-il_jmin0+1, &
-         &             tl_lon0%t_dim(3)%i_len, &
-         &             tl_lon0%t_dim(4)%i_len /)
-
-         tl_lon0=iom_read_var(td_coord0,'longitude',il_start(:), il_count(:))
-         tl_lat0=iom_read_var(td_coord0,'latitude' ,il_start(:), il_count(:))
-
-         grid_get_coarse_index_fc(:,:,:)=grid_get_coarse_index(tl_lon0,tl_lat0,&
-         &                                                     td_lon1,td_lat1,&
-         &                                                     il_rho(:) )
-
-         ! remove ghost cell
-         il_imin0=grid_get_coarse_index_fc(1,1,1)+il_xghost(1)*ig_ghost
-         il_imax0=grid_get_coarse_index_fc(1,2,1)+il_xghost(1)*ig_ghost
-         il_jmin0=grid_get_coarse_index_fc(2,1,1)+il_xghost(2)*ig_ghost
-         il_jmax0=grid_get_coarse_index_fc(2,2,1)+il_xghost(2)*ig_ghost
-
-         grid_get_coarse_index_fc(1,1,1)=il_imin0
-         grid_get_coarse_index_fc(1,2,1)=il_imax0
-         grid_get_coarse_index_fc(2,1,1)=il_jmin0
-         grid_get_coarse_index_fc(2,2,1)=il_jmax0
-
-         CALL var_clean(tl_lon0)
-         CALL var_clean(tl_lat0)
-
-      ENDIF
-
-   END FUNCTION grid_get_coarse_index_fc
-   !> @endcode
+      ENDIF
+
+      CALL mpp_clean(tl_coord0)
+      DEALLOCATE(il_rho)
+
+   END FUNCTION grid__get_coarse_index_fc
    !-------------------------------------------------------------------
    !> @brief This function get closest coarse grid indices of fine grid domain.
    !
    !> @details
-   !>
-   !> @warning use ghost cell so can not be used on extracted domain without
-   !> ghost cell
-   !
+   !> it use coarse and fine grid array of longitude and latitude.
+   !> optionaly, you could specify the array of refinment factor (default 1.)
+   !> optionally, you could specify on which Arakawa grid point you want to
+   !> work (default 'T')
+   !>
+   !> @note do not use ghost cell
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_lon0 : coarse grid longitude
-   !> @param[in] td_lat0 : coarse grid latitude
-   !> @param[in] td_lon1 : fine grid longitude
-   !> @param[in] td_lat1 : fine grid latitude
-   !> @return coarse grid indices (/ (/imin0, imax0/), (/jmin0, jmax0/) /)
-   !>
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION grid_get_coarse_index_cc( td_lon0, td_lat0, td_lon1, td_lat1, &
-   &                                  id_rho )
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - check grid point
+   !> - take into account EW overlap
+   !>
+   !> @param[in] td_lon0   coarse grid longitude
+   !> @param[in] td_lat0   coarse grid latitude
+   !> @param[in] td_lon1   fine grid longitude
+   !> @param[in] td_lat1   fine grid latitude
+   !> @param[in] id_rho    array of refinment factor
+   !> @param[in] cd_point  Arakawa grid point ('T','U','V','F')
+   !> @return coarse grid indices (/(/imin0, imax0/), (/jmin0, jmax0/)/)
+   !>
+   !> @todo
+   !> -check case boundary domain on overlap band
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_coarse_index_cc( td_lon0, td_lat0, td_lon1, td_lat1, &
+   &                                   id_rho, cd_point )
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(IN) :: td_lon0
-      TYPE(TVAR) , INTENT(IN) :: td_lat0
-      TYPE(TVAR) , INTENT(IN) :: td_lon1
-      TYPE(TVAR) , INTENT(IN) :: td_lat1
-      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      TYPE(TVAR)                    , INTENT(IN) :: td_lon0
+      TYPE(TVAR)                    , INTENT(IN) :: td_lat0
+      TYPE(TVAR)                    , INTENT(IN) :: td_lon1
+      TYPE(TVAR)                    , INTENT(IN) :: td_lat1
+      INTEGER(i4)     , DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      CHARACTER(LEN=*)              , INTENT(IN), OPTIONAL :: cd_point
 
       ! function
-      INTEGER(i4), DIMENSION(2,2,2) :: grid_get_coarse_index_cc
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_coarse_index_cc
 
       ! local variable
@@ -927,7 +2418,4 @@
       REAL(dp)    :: dl_lat1_ur
 
-      REAL(dp)    :: dl_dlon
-      REAL(dp)    :: dl_dlat
-
       INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
 
@@ -954,18 +2442,35 @@
       INTEGER(i4) :: il_jmax      
 
-      INTEGER(i4), DIMENSION(2,2) :: il_offset
-
+      INTEGER(i4), DIMENSION(2,2) :: il_xghost0
+      INTEGER(i4), DIMENSION(2,2) :: il_yghost0
+      INTEGER(i4), DIMENSION(2,2) :: il_xghost1
+      INTEGER(i4), DIMENSION(2,2) :: il_yghost1
+
+      TYPE(TVAR) :: tl_lon0
+      TYPE(TVAR) :: tl_lat0
+      TYPE(TVAR) :: tl_lon1
+      TYPE(TVAR) :: tl_lat1
+
+      CHARACTER(LEN= 1) :: cl_point0
+      CHARACTER(LEN= 1) :: cl_point1
+      
       ! loop indices
       INTEGER(i4) :: ji
       INTEGER(i4) :: jj
       !----------------------------------------------------------------
-
       ! init
-      grid_get_coarse_index_cc(:,:,:)=0
-
-      ALLOCATE( il_rho(ig_ndim) )
+      grid__get_coarse_index_cc(:,:)=0
+
+      ALLOCATE( il_rho(ip_maxdim) )
       il_rho(:)=1
       IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
 
+      cl_point0='T'
+      cl_point1='T'
+      IF( PRESENT(cd_point) )THEN
+         cl_point0=TRIM(fct_upper(cd_point))
+         cl_point1=TRIM(fct_upper(cd_point))
+      ENDIF
+      
       IF( .NOT. ASSOCIATED(td_lon0%d_value) .OR. &
       &   .NOT. ASSOCIATED(td_lat0%d_value) .OR. &
@@ -976,10 +2481,25 @@
       ELSE
 
+         IF( TRIM(td_lon0%c_point)/='' )THEN
+            cl_point0=TRIM(td_lon0%c_point)
+         ELSEIF( TRIM(td_lat0%c_point)/='' )THEN
+            cl_point0=TRIM(td_lat0%c_point)
+         ENDIF
+         IF( TRIM(td_lon1%c_point)/='' )THEN
+            cl_point1=TRIM(td_lon1%c_point)
+         ELSEIF( TRIM(td_lat1%c_point)/='' )THEN
+            cl_point1=TRIM(td_lat1%c_point)
+         ENDIF
+         IF( cl_point0 /= cl_point1 )THEN
+            CALL logger_error("GRID GET COARSE INDEX: fine and coarse grid"//&
+         &                 " coordinate not on same grid point.")
+         ENDIF
+
          IF( grid_is_global(td_lon1, td_lat1) )THEN
 
             IF( grid_is_global(td_lon0, td_lat0) )THEN
                CALL logger_trace("GRID GET COARSE INDEX: fine grid is global ")
-               grid_get_coarse_index_cc(:,:,1) = 1
-               grid_get_coarse_index_cc(:,:,2) = 0
+               grid__get_coarse_index_cc(:,:) = 1
+               grid__get_coarse_index_cc(:,:) = 0
             ELSE
                CALL logger_error("GRID GET COARSE INDEX: fine grid is "//&
@@ -989,13 +2509,25 @@
          ELSE
 
+            il_xghost0(:,:)=grid_get_ghost( td_lon0 )
+            il_yghost0(:,:)=grid_get_ghost( td_lat0 )
+            IF( ANY(il_xghost0(:,:) /= il_yghost0(:,:)) )THEN
+               CALL logger_error("GRID GET COARSE INDEX: coarse grid "//&
+               &        "coordinate do not share same ghost cell")
+            ENDIF
+
+            tl_lon0=var_copy(td_lon0)
+            tl_lat0=var_copy(td_lat0)
+            CALL grid_del_ghost(tl_lon0, il_xghost0(:,:))
+            CALL grid_del_ghost(tl_lat0, il_xghost0(:,:))
+            
             ! "global" coarse grid indice
             il_imin0=1
             il_jmin0=1
 
-            il_imax0=td_lon0%t_dim(1)%i_len
-            il_jmax0=td_lon0%t_dim(2)%i_len
+            il_imax0=tl_lon0%t_dim(1)%i_len
+            il_jmax0=tl_lon0%t_dim(2)%i_len
 
             ! get east west overlap for coarse grid
-            il_ew0=dom_get_ew_overlap(td_lon0)
+            il_ew0=tl_lon0%i_ew
             IF( il_ew0 >= 0 )THEN
                ! last point before overlap
@@ -1003,13 +2535,25 @@
             ENDIF
 
+            il_xghost1(:,:)=grid_get_ghost( td_lon1 )
+            il_yghost1(:,:)=grid_get_ghost( td_lat1 )
+            IF( ANY(il_xghost1(:,:) /= il_yghost1(:,:)) )THEN
+               CALL logger_error("GRID GET COARSE INDEX: fine grid "//&
+               &        "coordinate do not share same ghost cell")
+            ENDIF
+
+            tl_lon1=var_copy(td_lon1)
+            tl_lat1=var_copy(td_lat1)
+            CALL grid_del_ghost(tl_lon1, il_xghost1(:,:))
+            CALL grid_del_ghost(tl_lat1, il_xghost1(:,:))
+            
             ! "global" fine grid indice
             il_imin1=1
             il_jmin1=1
 
-            il_imax1=td_lon1%t_dim(1)%i_len
-            il_jmax1=td_lon1%t_dim(2)%i_len
-
-            ! get east west overlap for coarse grid
-            il_ew1=dom_get_ew_overlap(td_lon1)
+            il_imax1=tl_lon1%t_dim(1)%i_len
+            il_jmax1=tl_lon1%t_dim(2)%i_len
+
+            ! get east west overlap for fine grid
+            il_ew1=tl_lon1%i_ew
             IF( il_ew1 >= 0 )THEN
                ! last point before overlap
@@ -1019,30 +2563,18 @@
             ! get indices for each corner
             !1- search lower left corner indices
-            dl_lon1_ll=td_lon1%d_value( il_imin1, il_jmin1, 1, 1 )
-            dl_lat1_ll=td_lat1%d_value( il_imin1, il_jmin1, 1, 1 )
-
-            dl_dlon=ABS(td_lon1%d_value(il_imin1+1,il_jmin1  ,1,1)-dl_lon1_ll)
-            dl_dlat=ABS(td_lat1%d_value(il_imin1  ,il_jmin1+1,1,1)-dl_lat1_ll)
-
-!            CALL logger_debug("GRID GET COARSE INDEX: lon1 ll "//&
-!            &  TRIM(fct_str(dl_lon1_ll)) )
-!            CALL logger_debug("GRID GET COARSE INDEX: lat1 ll "//&
-!            &  TRIM(fct_str(dl_lat1_ll)) )
-!
-!            CALL logger_debug("GRID GET COARSE INDEX: lon0 min "//&
-!            &  TRIM(fct_str(minval(td_lon0%d_value(2:,2:,:,:)))) )
-!            CALL logger_debug("GRID GET COARSE INDEX: lon0 max "//&
-!            &  TRIM(fct_str(maxval(td_lon0%d_value(2:,2:,:,:)))) )
-!
-!            CALL logger_debug("GRID GET COARSE INDEX: lat0 min "//&
-!            &  TRIM(fct_str(minval(td_lat0%d_value(2:,2:,:,:)))) )
-!            CALL logger_debug("GRID GET COARSE INDEX: lat0 max "//&
-!            &  TRIM(fct_str(maxval(td_lat0%d_value(2:,2:,:,:)))) )
-
+            dl_lon1_ll=tl_lon1%d_value( il_imin1, il_jmin1, 1, 1 )
+            dl_lat1_ll=tl_lat1%d_value( il_imin1, il_jmin1, 1, 1 )
+
+            IF( dl_lon1_ll == tl_lon1%d_fill .OR. &
+            &   dl_lat1_ll == tl_lat1%d_fill )THEN
+               CALL logger_error("GRID GET COARSE INDEX: lower left corner "//&
+               &                 "point is FillValue. remove ghost cell "//&
+               &                 "before running grid_get_coarse_index.")
+            ENDIF
             ! look for closest point on coarse grid
-            il_ill(:)= grid_get_closest(td_lon0%d_value(il_imin0:il_imax0, &
+            il_ill(:)= grid_get_closest(tl_lon0%d_value(il_imin0:il_imax0, &
             &                                           il_jmin0:il_jmax0, &
             &                                           1,1), &
-            &                           td_lat0%d_value(il_imin0:il_imax0, &
+            &                           tl_lat0%d_value(il_imin0:il_imax0, &
             &                                           il_jmin0:il_jmax0, &
             &                                           1,1), &
@@ -1053,23 +2585,44 @@
             jj = il_ill(2)
 
-            IF( ABS(td_lon0%d_value(ji,jj,1,1)-dl_lon1_ll) > dl_dlon*1.e-3 )THEN
-               IF(td_lon0%d_value(ji,jj,1,1) > dl_lon1_ll ) il_ill(1)=il_ill(1)-1
+            IF( ABS(tl_lon0%d_value(ji,jj,1,1)-dl_lon1_ll) > dp_delta )THEN
+               IF(tl_lon0%d_value(ji,jj,1,1) > dl_lon1_ll )THEN
+                  il_ill(1)=il_ill(1)-1
+                  IF( il_ill(1) <= 0 )THEN
+                     IF( tl_lon0%i_ew >= 0 )THEN
+                        il_ill(1)=tl_lon0%t_dim(jp_I)%i_len-tl_lon0%i_ew
+                     ELSE
+                        CALL logger_error("GRID GET COARSE INDEX: error "//&
+                        &                 "computing lower left corner "//&
+                        &                 "index for longitude")
+                     ENDIF
+                  ENDIF
+               ENDIF
             ENDIF
-            IF( ABS(td_lat0%d_value(ji,jj,1,1)-dl_lat1_ll) > dl_dlat*1.e-3 )THEN
-               IF(td_lat0%d_value(ji,jj,1,1) > dl_lat1_ll ) il_ill(2)=il_ill(2)-1
+            IF( ABS(tl_lat0%d_value(ji,jj,1,1)-dl_lat1_ll) > dp_delta )THEN
+               IF(tl_lat0%d_value(ji,jj,1,1) > dl_lat1_ll )THEN
+                  il_ill(2)=il_ill(2)-1
+                  IF( il_ill(2)-1 <= 0 )THEN
+                     CALL logger_error("GRID GET COARSE INDEX: error "//&
+                     &                 "computing lower left corner "//&
+                     &                 "index for latitude")
+                  ENDIF
+               ENDIF
             ENDIF
 
             !2- search upper left corner indices
-            dl_lon1_ul=td_lon1%d_value( il_imin1, il_jmax1, 1, 1 )
-            dl_lat1_ul=td_lat1%d_value( il_imin1, il_jmax1, 1, 1 )
-
-            dl_dlon=ABS(td_lon1%d_value(il_imin1+1,il_jmax1  ,1,1)-dl_lon1_ll)
-            dl_dlat=ABS(td_lat1%d_value(il_imin1  ,il_jmax1-1,1,1)-dl_lat1_ll)
-            
+            dl_lon1_ul=tl_lon1%d_value( il_imin1, il_jmax1, 1, 1 )
+            dl_lat1_ul=tl_lat1%d_value( il_imin1, il_jmax1, 1, 1 )
+
+            IF( dl_lon1_ul == tl_lon1%d_fill .OR. &
+            &   dl_lat1_ul == tl_lat1%d_fill )THEN
+               CALL logger_error("GRID GET COARSE INDEX: upper left corner "//&
+               &                 "point is FillValue. remove ghost cell "//&
+               &                 "running grid_get_coarse_index.")
+            ENDIF            
             ! look for closest point on coarse grid
-            il_iul(:)= grid_get_closest(td_lon0%d_value(il_imin0:il_imax0, &
+            il_iul(:)= grid_get_closest(tl_lon0%d_value(il_imin0:il_imax0, &
             &                                           il_jmin0:il_jmax0, &
             &                                           1,1), &
-            &                           td_lat0%d_value(il_imin0:il_imax0, &
+            &                           tl_lat0%d_value(il_imin0:il_imax0, &
             &                                           il_jmin0:il_jmax0, &
             &                                           1,1), &
@@ -1080,23 +2633,45 @@
             jj = il_iul(2)
 
-            IF( ABS(td_lon0%d_value(ji,jj,1,1)-dl_lon1_ul) > dl_dlon*1.e-3 )THEN
-               IF(td_lon0%d_value(ji,jj,1,1) > dl_lon1_ul ) il_iul(1)=il_iul(1)-1
+            IF( ABS(tl_lon0%d_value(ji,jj,1,1)-dl_lon1_ul) > dp_delta )THEN
+               IF(tl_lon0%d_value(ji,jj,1,1) > dl_lon1_ul )THEN
+                  il_iul(1)=il_iul(1)-1
+                  IF( il_iul(1) <= 0 )THEN
+                     IF( tl_lon0%i_ew >= 0 )THEN
+                        il_iul(1)=tl_lon0%t_dim(jp_I)%i_len-tl_lon0%i_ew
+                     ELSE
+                        CALL logger_error("GRID GET COARSE INDEX: error "//&
+                        &                 "computing upper left corner "//&
+                        &                 "index for longitude")
+                     ENDIF
+                  ENDIF
+               ENDIF
             ENDIF
-            IF( ABS(td_lat0%d_value(ji,jj,1,1)-dl_lat1_ul) > dl_dlat*1.e-3 )THEN
-               IF(td_lat0%d_value(ji,jj,1,1) < dl_lat1_ul ) il_iul(2)=il_iul(2)+1
+
+            IF( ABS(tl_lat0%d_value(ji,jj,1,1)-dl_lat1_ul) > dp_delta )THEN
+               IF(tl_lat0%d_value(ji,jj,1,1) < dl_lat1_ul )THEN
+                  il_iul(2)=il_iul(2)+1
+                  IF( il_ill(2) > tl_lat0%t_dim(jp_J)%i_len )THEN
+                     CALL logger_error("GRID GET COARSE INDEX: error "//&
+                     &                 "computing upper left corner "//&
+                     &                 "index for latitude")
+                  ENDIF
+               ENDIF
             ENDIF
 
             !3- search lower right corner indices
-            dl_lon1_lr=td_lon1%d_value( il_imax1, il_jmin1, 1, 1 )
-            dl_lat1_lr=td_lat1%d_value( il_imax1, il_jmin1, 1, 1 )
-
-            dl_dlon=ABS(td_lon1%d_value(il_imax1-1,il_jmin1  ,1,1)-dl_lon1_ll)
-            dl_dlat=ABS(td_lat1%d_value(il_imax1  ,il_jmin1+1,1,1)-dl_lat1_ll)
-            
+            dl_lon1_lr=tl_lon1%d_value( il_imax1, il_jmin1, 1, 1 )
+            dl_lat1_lr=tl_lat1%d_value( il_imax1, il_jmin1, 1, 1 )
+
+            IF( dl_lon1_lr == tl_lon1%d_fill .OR. &
+            &   dl_lat1_lr == tl_lat1%d_fill )THEN
+               CALL logger_error("GRID GET COARSE INDEX: lower right corner "//&
+               &                 "point is FillValue. remove ghost cell "//&
+               &                 "running grid_get_coarse_index.")
+            ENDIF            
             ! look for closest point on coarse grid
-            il_ilr(:)= grid_get_closest(td_lon0%d_value(il_imin0:il_imax0, &
+            il_ilr(:)= grid_get_closest(tl_lon0%d_value(il_imin0:il_imax0, &
             &                                           il_jmin0:il_jmax0, &
             &                                           1,1), &
-            &                           td_lat0%d_value(il_imin0:il_imax0, &
+            &                           tl_lat0%d_value(il_imin0:il_imax0, &
             &                                           il_jmin0:il_jmax0, &
             &                                           1,1), &
@@ -1106,23 +2681,44 @@
             ji = il_ilr(1)
             jj = il_ilr(2)
-            IF( ABS(td_lon0%d_value(ji,jj,1,1)-dl_lon1_lr) > dl_dlon*1.e-3 )THEN
-               IF( td_lon0%d_value(ji,jj,1,1) < dl_lon1_lr ) il_ilr(1)=il_ilr(1)+1
+            IF( ABS(tl_lon0%d_value(ji,jj,1,1)-dl_lon1_lr) > dp_delta )THEN
+               IF( tl_lon0%d_value(ji,jj,1,1) < dl_lon1_lr )THEN
+                  il_ilr(1)=il_ilr(1)+1
+                  IF( il_ilr(1) > tl_lon0%t_dim(jp_I)%i_len )THEN
+                     IF( tl_lon0%i_ew >= 0 )THEN
+                        il_ilr(1)=tl_lon0%i_ew+1
+                     ELSE
+                        CALL logger_error("GRID GET COARSE INDEX: error "//&
+                        &                 "computing lower right corner "//&
+                        &                 "index for longitude")
+                     ENDIF
+                  ENDIF
+               ENDIF
             ENDIF
-            IF( ABS(td_lat0%d_value(ji,jj,1,1)-dl_lat1_lr) > dl_dlat*1.e-3 )THEN
-               IF( td_lat0%d_value(ji,jj,1,1) > dl_lat1_lr ) il_ilr(2)=il_ilr(2)-1
+            IF( ABS(tl_lat0%d_value(ji,jj,1,1)-dl_lat1_lr) > dp_delta )THEN
+               IF( tl_lat0%d_value(ji,jj,1,1) > dl_lat1_lr )THEN
+                  il_ilr(2)=il_ilr(2)-1
+                  IF( il_ilr(2) <= 0 )THEN
+                     CALL logger_error("GRID GET COARSE INDEX: error "//&
+                     &                 "computing lower right corner "//&
+                     &                 "index for latitude")
+                  ENDIF
+               ENDIF
             ENDIF
 
             !4- search upper right corner indices
-            dl_lon1_ur=td_lon1%d_value( il_imax1, il_jmax1, 1, 1 )
-            dl_lat1_ur=td_lat1%d_value( il_imax1, il_jmax1, 1, 1 )
-
-            dl_dlon=ABS(td_lon1%d_value(il_imax1-1,il_jmax1  ,1,1)-dl_lon1_ll)
-            dl_dlat=ABS(td_lat1%d_value(il_imax1  ,il_jmax1-1,1,1)-dl_lat1_ll)
-            
+            dl_lon1_ur=tl_lon1%d_value( il_imax1, il_jmax1, 1, 1 )
+            dl_lat1_ur=tl_lat1%d_value( il_imax1, il_jmax1, 1, 1 )
+
+            IF( dl_lon1_ur == tl_lon1%d_fill .OR. &
+            &   dl_lat1_ur == tl_lat1%d_fill )THEN
+               CALL logger_error("GRID GET COARSE INDEX: upper right corner "//&
+               &                 "point is FillValue. remove ghost cell "//&
+               &                 "running grid_get_coarse_index.")
+            ENDIF            
             ! look for closest point on coarse grid
-            il_iur(:)= grid_get_closest(td_lon0%d_value(il_imin0:il_imax0, &
+            il_iur(:)= grid_get_closest(tl_lon0%d_value(il_imin0:il_imax0, &
             &                                           il_jmin0:il_jmax0, &
             &                                           1,1), &
-            &                           td_lat0%d_value(il_imin0:il_imax0, &
+            &                           tl_lat0%d_value(il_imin0:il_imax0, &
             &                                           il_jmin0:il_jmax0, &
             &                                           1,1), &
@@ -1132,9 +2728,27 @@
             ji = il_iur(1)
             jj = il_iur(2)
-            IF( ABS(td_lon0%d_value(ji,jj,1,1)-dl_lon1_ur) > dl_dlon*1.e-3 )THEN
-               IF( td_lon0%d_value(ji,jj,1,1) < dl_lon1_ur ) il_iur(1)=il_iur(1)+1
+            IF( ABS(tl_lon0%d_value(ji,jj,1,1)-dl_lon1_ur) > dp_delta )THEN
+               IF( tl_lon0%d_value(ji,jj,1,1) < dl_lon1_ur )THEN
+                  il_iur(1)=il_iur(1)+1
+                  IF( il_iur(1) > tl_lon0%t_dim(jp_I)%i_len )THEN
+                     IF( tl_lon0%i_ew >= 0 )THEN
+                        il_iur(1)=tl_lon0%i_ew+1
+                     ELSE
+                        CALL logger_error("GRID GET COARSE INDEX: error "//&
+                        &                 "computing upper right corner "//&
+                        &                 "index for longitude")
+                     ENDIF
+                  ENDIF
+               ENDIF
             ENDIF
-            IF( ABS(td_lat0%d_value(ji,jj,1,1)-dl_lat1_ur) > dl_dlat*1.e-3 )THEN
-               IF( td_lat0%d_value(ji,jj,1,1) < dl_lat1_ur ) il_iur(2)=il_iur(2)+1
+            IF( ABS(tl_lat0%d_value(ji,jj,1,1)-dl_lat1_ur) > dp_delta )THEN
+               IF( tl_lat0%d_value(ji,jj,1,1) < dl_lat1_ur )THEN
+                  il_iur(2)=il_iur(2)+1
+                  IF( il_iur(2) > tl_lat0%t_dim(jp_J)%i_len )THEN
+                     CALL logger_error("GRID GET COARSE INDEX: error "//&
+                     &                 "computing upper right corner "//&
+                     &                 "index for latitude")
+                  ENDIF
+               ENDIF
             ENDIF
 
@@ -1144,23 +2758,10 @@
 
             IF( il_imax <= il_ew0 )THEN
-               il_imax = td_lon0%t_dim(1)%i_len - il_ew0 + il_imax 
+               !il_imin = 1
+               il_imax = tl_lon0%t_dim(1)%i_len - il_ew0 + il_imax 
             ENDIF
 
             il_jmin = il_jmin0-1+MIN(il_ill(2), il_ilr(2))
             il_jmax = il_jmin0-1+MAX(il_iul(2), il_iur(2))
-
-            il_offset(:,:)= grid_get_fine_offset( td_lon0%d_value( :,:,1,1 ), &
-            &                                     td_lat0%d_value( :,:,1,1 ), &
-            &                                     il_imin, il_jmin, &
-            &                                     il_imax, il_jmax, &
-            &                                     td_lon1%d_value( :,:,1,1 ), &
-            &                                     td_lat1%d_value( :,:,1,1 ), &
-            &                                     il_rho(:) )
-
-            grid_get_coarse_index_cc(1,1,2) = il_offset(1,1)
-            grid_get_coarse_index_cc(1,2,2) = il_offset(1,2)
-
-            grid_get_coarse_index_cc(2,1,2) = il_offset(2,1)
-            grid_get_coarse_index_cc(2,2,2) = il_offset(2,2) 
 
             ! special case if east west overlap
@@ -1170,25 +2771,25 @@
 
                il_imin = 1
-               il_imax = 1
-
-               grid_get_coarse_index_cc(1,1,2) = 0
-               grid_get_coarse_index_cc(1,2,2) = 0
+               il_imax = tl_lon0%t_dim(1)%i_len
+
             ENDIF
-
          ENDIF
 
-         IF( il_imin == il_imax ) il_imax=td_lon0%t_dim(1)%i_len
-         IF( il_jmin == il_jmax ) il_jmax=td_lon0%t_dim(2)%i_len
-
-         grid_get_coarse_index_cc(1,1,1) = il_imin
-         grid_get_coarse_index_cc(1,2,1) = il_imax
-
-         grid_get_coarse_index_cc(2,1,1) = il_jmin
-         grid_get_coarse_index_cc(2,2,1) = il_jmax
+         grid__get_coarse_index_cc(1,1) = il_imin
+         grid__get_coarse_index_cc(1,2) = il_imax
+
+         grid__get_coarse_index_cc(2,1) = il_jmin
+         grid__get_coarse_index_cc(2,2) = il_jmax
  
-      ENDIF
-
-   END FUNCTION grid_get_coarse_index_cc
-   !> @endcode
+         ! clean 
+         CALL var_clean(tl_lon1)
+         CALL var_clean(tl_lat1)
+         CALL var_clean(tl_lon0)
+         CALL var_clean(tl_lat0)
+      ENDIF
+
+      DEALLOCATE( il_rho )
+
+   END FUNCTION grid__get_coarse_index_cc
    !-------------------------------------------------------------------
    !> @brief This function check if grid is global or not
@@ -1197,10 +2798,9 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_lon : longitude structure 
-   !> @param[in] td_lat : latitude structure 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_lon longitude structure 
+   !> @param[in] td_lat latitude structure 
+   !-------------------------------------------------------------------
    FUNCTION grid_is_global(td_lon, td_lat)
       IMPLICIT NONE
@@ -1233,5 +2833,5 @@
       IF( .NOT. ASSOCIATED(td_lon%d_value) .OR. &
       &   .NOT. ASSOCIATED(td_lat%d_value) )THEN
-         CALL logger_error("GRID IS GLOBAL: na value associated to "//&
+         CALL logger_error("GRID IS GLOBAL: no value associated to "//&
          &              " longitude or latitude strucutre")      
       ELSE
@@ -1256,28 +2856,23 @@
 
    END FUNCTION grid_is_global
-   !> @endcode
-
    !-------------------------------------------------------------------
    !> @brief This function return coarse grid indices of the closest point
    !> from fine grid point (lon1,lat1) 
    !> 
-   !
    !> @details
-   !
-   !> @note overlap band should have been already removed from coarse grid table 
+   !>
+   !> @note overlap band should have been already removed from coarse grid array 
    !> of longitude and latitude, before running this function
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_lon0 : coarse grid table of longitude
-   !> @param[in] dd_lat0 : coarse grid table of latitude
-   !> @param[in] dd_lon1 : fine   grid longitude
-   !> @param[in] dd_lat1 : fine   grid latitude
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_lon0   coarse grid array of longitude
+   !> @param[in] dd_lat0   coarse grid array of latitude
+   !> @param[in] dd_lon1   fine   grid longitude
+   !> @param[in] dd_lat1   fine   grid latitude
    !> @return coarse grid indices of closest point of fine grid point
    !>
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !-------------------------------------------------------------------
    FUNCTION grid_get_closest( dd_lon0, dd_lat0, dd_lon1, dd_lat1  )
       IMPLICIT NONE
@@ -1326,5 +2921,5 @@
       IF( dd_lon1 < 0 ) dl_lon1 = dd_lon1 + 360.
 
-      !1- first, use dichotomy to reduce domain
+      ! first, use dichotomy to reduce domain
       il_iinf = 1              ; il_jinf = 1
       il_isup = il_shape(1)    ; il_jsup = il_shape(2)
@@ -1336,5 +2931,5 @@
       ll_continue=.TRUE.
 
-      !1-1 look for meridian 0°/360°
+      ! look for meridian 0°/360°
       il_jmid = il_jinf + INT(il_shape(2)/2)
       il_ind(:) = MAXLOC( dl_lon0(:,il_jmid), dl_lon0(:,il_jmid) <= 360._dp )
@@ -1378,5 +2973,5 @@
       ENDIF
 
-      !1-2
+      !
       DO WHILE( ll_continue .AND. .NOT. ll_north )
 
@@ -1401,5 +2996,4 @@
 
             ENDIF
-
 
             IF( dd_lat1 > dd_lat0(il_imid,il_jmid) )THEN
@@ -1430,5 +3024,5 @@
       ENDDO
 
-      !2- then find closest point by computing distances
+      ! then find closest point by computing distances
       il_shape(1)= il_isup - il_iinf + 1
       il_shape(2)= il_jsup - il_jinf + 1
@@ -1449,20 +3043,18 @@
 
    END FUNCTION grid_get_closest
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function compute the distance between a point A and 
-   !> points of a grid  
+   !-------------------------------------------------------------------
+   !> @brief This function compute the distance between a point A and grid points.  
    !
    !> @details
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_lon : grid longitude table
-   !> @param[in] dd_lat : grid latitude  table
-   !> @param[in] dd_lonA : longitude of point A
-   !> @param[in] dd_latA : latitude  of point A
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_lon    grid longitude array
+   !> @param[in] dd_lat    grid latitude  array
+   !> @param[in] dd_lonA   longitude of point A
+   !> @param[in] dd_latA   latitude  of point A
+   !> @return array of distance between point A and grid points.
+   !-------------------------------------------------------------------
    FUNCTION grid_distance(dd_lon, dd_lat, dd_lonA, dd_latA)
       IMPLICIT NONE
@@ -1507,9 +3099,9 @@
       IF(   dd_lonA     < 0 ) dl_lonA     = dd_lonA     + 360.
       
-      dl_lonA = dd_lonA * dg_deg2rad
-      dl_latA = dd_latA * dg_deg2rad
-
-      dl_lon(:,:) = dl_lon(:,:) * dg_deg2rad
-      dl_lat(:,:) = dd_lat(:,:) * dg_deg2rad
+      dl_lonA = dd_lonA * dp_deg2rad
+      dl_latA = dd_latA * dp_deg2rad
+
+      dl_lon(:,:) = dl_lon(:,:) * dp_deg2rad
+      dl_lat(:,:) = dd_lat(:,:) * dp_deg2rad
 
       grid_distance(:,:)=NF90_FILL_DOUBLE
@@ -1518,5 +3110,5 @@
          DO ji=1,il_shape(1)
             IF( dl_lon(ji,jj) == dl_lonA .AND. &
-            &   dl_lat(ji,jj) == dl_lATA )THEN
+            &   dl_lat(ji,jj) == dl_laTA )THEN
                grid_distance(ji,jj)=0.0
             ELSE
@@ -1526,5 +3118,5 @@
                IF( dl_tmp < -1.0 ) dl_tmp = -1.0
                IF( dl_tmp >  1.0 ) dl_tmp =  1.0
-               grid_distance(ji,jj)=ACOS(dl_tmp)*dg_rearth
+               grid_distance(ji,jj)=ACOS(dl_tmp)*dp_rearth
             ENDIF
          ENDDO
@@ -1535,7 +3127,457 @@
 
    END FUNCTION grid_distance
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function get fine grid offset.
+   !-------------------------------------------------------------------
+   !> @brief This function get offset between fine grid and coarse grid.
+   !
+   !> @details
+   !> optionally, you could specify on which Arakawa grid point you want to
+   !> work (default 'T')
+   !> offset value could be 0,1,..,rho-1
+   !
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !
+   !> @param[in] td_coord0 coarse grid coordinate 
+   !> @param[in] id_imin0  coarse grid lower left corner i-indice of fine grid domain
+   !> @param[in] id_jmin0  coarse grid lower left corner j-indice of fine grid domain
+   !> @param[in] id_imax0  coarse grid upper right corner i-indice of fine grid domain
+   !> @param[in] id_jmax0  coarse grid upper right corner j-indice of fine grid domain
+   !> @param[in] td_coord1 fine   grid coordinate 
+   !> @param[in] id_rho    array of refinement factor
+   !> @param[in] cd_point  Arakawa grid point
+   !> @return offset array (/ (/i_offset_left,i_offset_right/),(/j_offset_lower,j_offset_upper/) /)
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_fine_offset_ff( td_coord0, &
+   &                                  id_imin0, id_jmin0, id_imax0, id_jmax0, &
+   &                                  td_coord1, id_rho, cd_point )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TMPP)                    , INTENT(IN) :: td_coord0
+      TYPE(TMPP)                    , INTENT(IN) :: td_coord1
+
+      INTEGER(i4)                   , INTENT(IN) :: id_imin0
+      INTEGER(i4)                   , INTENT(IN) :: id_jmin0
+      INTEGER(i4)                   , INTENT(IN) :: id_imax0
+      INTEGER(i4)                   , INTENT(IN) :: id_jmax0
+
+      INTEGER(i4)     , DIMENSION(:), INTENT(IN), OPTIONAL :: id_rho
+      CHARACTER(LEN=*)              , INTENT(IN), OPTIONAL :: cd_point
+
+      ! function
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_fine_offset_ff
+
+      ! local variable
+      INTEGER(i4) :: il_imin0
+      INTEGER(i4) :: il_jmin0
+      INTEGER(i4) :: il_imax0
+      INTEGER(i4) :: il_jmax0
+      
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
+      
+      INTEGER(i4), DIMENSION(2,2)         :: il_xghost0
+      INTEGER(i4), DIMENSION(2,2)         :: il_xghost1
+
+      CHARACTER(LEN= 1) :: cl_point
+      CHARACTER(LEN=lc) :: cl_name
+
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon0
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lat0
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon1
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lat1
+
+      TYPE(TVAR) :: tl_lon0
+      TYPE(TVAR) :: tl_lat0
+      TYPE(TVAR) :: tl_lon1
+      TYPE(TVAR) :: tl_lat1
+
+      TYPE(TMPP) :: tl_coord0
+      TYPE(TMPP) :: tl_coord1
+      
+      ! loop indices
+      !----------------------------------------------------------------
+      ! init
+      grid__get_fine_offset_ff(:,:)=-1
+
+      ALLOCATE(il_rho(ip_maxdim))
+      il_rho(:)=1
+      IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
+
+      cl_point='T'
+      IF( PRESENT(cd_point) ) cl_point=TRIM(fct_upper(cd_point))
+
+      ! copy structure
+      tl_coord0=mpp_copy(td_coord0)
+      tl_coord1=mpp_copy(td_coord1)
+
+      IF( .NOT. ASSOCIATED(tl_coord0%t_proc) .OR. &
+      &   .NOT. ASSOCIATED(tl_coord1%t_proc) )THEN
+         CALL logger_error("GRID GET FINE OFFSET: can not get coarse "//&
+         &  "grid indices. decompsition of mpp file "//TRIM(tl_coord0%c_name)//&
+         &  " and/or "//TRIM(tl_coord1%c_name)//" not defined." )
+      ELSE      
+         !1- Coarse grid
+         ! get ghost cell factor on coarse grid
+         il_xghost0(:,:)=grid_get_ghost( tl_coord0 )
+
+         ! open mpp files
+         CALL iom_mpp_open(tl_coord0)
+
+         ! read coarse longitue and latitude
+         WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         tl_lon0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+         WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         tl_lat0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+         
+         ! close mpp files
+         CALL iom_mpp_close(tl_coord0)
+
+         CALL grid_del_ghost(tl_lon0, il_xghost0(:,:))
+         CALL grid_del_ghost(tl_lat0, il_xghost0(:,:))
+
+         ALLOCATE(dl_lon0(tl_lon0%t_dim(jp_I)%i_len, &
+         &                tl_lon0%t_dim(jp_J)%i_len ))
+
+         dl_lon0(:,:)=tl_lon0%d_value(:,:,1,1)
+
+         ALLOCATE(dl_lat0(tl_lat0%t_dim(jp_I)%i_len, &
+         &                tl_lat0%t_dim(jp_J)%i_len ))
+
+         dl_lat0(:,:)=tl_lat0%d_value(:,:,1,1)
+
+         ! clean
+         CALL var_clean(tl_lon0)
+         CALL var_clean(tl_lat0)
+
+         ! adjust coarse grid indices
+         il_imin0=id_imin0-il_xghost0(jp_I,1)
+         il_imax0=id_imax0-il_xghost0(jp_I,1)
+
+         il_jmin0=id_jmin0-il_xghost0(jp_J,1)
+         il_jmax0=id_jmax0-il_xghost0(jp_J,1)
+
+         !2- Fine grid
+         ! get ghost cell factor on fine grid
+         il_xghost1(:,:)=grid_get_ghost( tl_coord1 )
+
+         ! open mpp files
+         CALL iom_mpp_open(tl_coord1)
+
+         ! read fine longitue and latitude
+         WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         tl_lon1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
+         WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         tl_lat1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
+ 
+         ! close mpp files
+         CALL iom_mpp_close(tl_coord1)
+
+         CALL grid_del_ghost(tl_lon1, il_xghost1(:,:))
+         CALL grid_del_ghost(tl_lat1, il_xghost1(:,:))
+
+         ALLOCATE(dl_lon1(tl_lon1%t_dim(jp_I)%i_len, &
+         &                tl_lon1%t_dim(jp_J)%i_len ))
+
+         dl_lon1(:,:)=tl_lon1%d_value(:,:,1,1)
+
+         ALLOCATE(dl_lat1(tl_lat1%t_dim(jp_I)%i_len, &
+         &                tl_lat1%t_dim(jp_J)%i_len ))
+
+         dl_lat1(:,:)=tl_lat1%d_value(:,:,1,1)
+
+         ! clean
+         CALL var_clean(tl_lon1)
+         CALL var_clean(tl_lat1)
+ 
+         !3- compute
+         grid__get_fine_offset_ff(:,:)=grid_get_fine_offset( &
+         &                                         dl_lon0(:,:), dl_lat0(:,:),&
+         &                                         il_imin0, il_jmin0, &
+         &                                         il_imax0, il_jmax0, &
+         &                                         dl_lon1(:,:), dl_lat1(:,:),&
+         &                                         id_rho(:) )
+ 
+         DEALLOCATE(dl_lon0, dl_lat0)
+         DEALLOCATE(dl_lon1, dl_lat1)
+      ENDIF
+
+      ! clean 
+      CALL mpp_clean(tl_coord0)
+      CALL mpp_clean(tl_coord1)
+      DEALLOCATE(il_rho)
+
+   END FUNCTION grid__get_fine_offset_ff
+   !-------------------------------------------------------------------
+   !> @brief This function get offset between fine grid and coarse grid.
+   !
+   !> @details
+   !> optionally, you could specify on which Arakawa grid point you want to
+   !> work (default 'T')
+   !> offset value could be 0,1,..,rho-1
+   !
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !
+   !> @param[in] dd_lon0   coarse grid longitude array 
+   !> @param[in] dd_lat0   coarse grid latitude  array
+   !> @param[in] id_imin0  coarse grid lower left corner i-indice of fine grid domain
+   !> @param[in] id_jmin0  coarse grid lower left corner j-indice of fine grid domain
+   !> @param[in] id_imax0  coarse grid upper right corner i-indice of fine grid domain
+   !> @param[in] id_jmax0  coarse grid upper right corner j-indice of fine grid domain
+   !> @param[in] td_coord1 fine   grid coordinate 
+   !> @param[in] id_rho    array of refinement factor
+   !> @param[in] cd_point  Arakawa grid point
+   !> @return offset array (/ (/i_offset_left,i_offset_right/),(/j_offset_lower,j_offset_upper/) /)
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_fine_offset_cf( dd_lon0, dd_lat0, &
+   &                                  id_imin0, id_jmin0, id_imax0, id_jmax0, &
+   &                                  td_coord1, id_rho, cd_point )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)       , DIMENSION(:,:), INTENT(IN) :: dd_lon0
+      REAL(dp)       , DIMENSION(:,:), INTENT(IN) :: dd_lat0
+      TYPE(TMPP)                     , INTENT(IN) :: td_coord1
+
+      INTEGER(i4)                    , INTENT(IN) :: id_imin0
+      INTEGER(i4)                    , INTENT(IN) :: id_jmin0
+      INTEGER(i4)                    , INTENT(IN) :: id_imax0
+      INTEGER(i4)                    , INTENT(IN) :: id_jmax0
+
+      INTEGER(i4)     , DIMENSION(:) , INTENT(IN), OPTIONAL :: id_rho
+      CHARACTER(LEN=*)               , INTENT(IN), OPTIONAL :: cd_point
+
+      ! function
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_fine_offset_cf
+
+      ! local variable
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
+      
+      INTEGER(i4), DIMENSION(2,2)         :: il_xghost1
+
+      CHARACTER(LEN= 1) :: cl_point
+      CHARACTER(LEN=lc) :: cl_name
+
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon1
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lat1
+
+      TYPE(TVAR) :: tl_lon1
+      TYPE(TVAR) :: tl_lat1
+
+      TYPE(TMPP) :: tl_coord1
+      ! loop indices
+      !----------------------------------------------------------------
+      ! init
+      grid__get_fine_offset_cf(:,:)=-1
+
+      ALLOCATE(il_rho(ip_maxdim))
+      il_rho(:)=1
+      IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
+
+      cl_point='T'
+      IF( PRESENT(cd_point) ) cl_point=TRIM(fct_upper(cd_point))
+
+      ! copy structure
+      tl_coord1=mpp_copy(td_coord1)
+
+      IF( .NOT. ASSOCIATED(tl_coord1%t_proc) )THEN
+         CALL logger_error("GRID GET FINE OFFSET: decompsition of mpp "//&
+         &  "file "//TRIM(tl_coord1%c_name)//" not defined." )
+      ELSE      
+
+         ! Fine grid
+         ! get ghost cell factor on fine grid
+         il_xghost1(:,:)=grid_get_ghost( tl_coord1 )
+
+         ! open mpp files
+         CALL iom_mpp_open(tl_coord1)
+
+         ! read fine longitue and latitude
+         WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         tl_lon1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
+         WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         tl_lat1=iom_mpp_read_var(tl_coord1, TRIM(cl_name))
+ 
+         ! close mpp files
+         CALL iom_mpp_close(tl_coord1)
+
+         CALL grid_del_ghost(tl_lon1, il_xghost1(:,:))
+         CALL grid_del_ghost(tl_lat1, il_xghost1(:,:))
+
+         ALLOCATE(dl_lon1(tl_lon1%t_dim(jp_I)%i_len, &
+         &                tl_lon1%t_dim(jp_J)%i_len ))
+
+         dl_lon1(:,:)=tl_lon1%d_value(:,:,1,1)
+
+         ALLOCATE(dl_lat1(tl_lat1%t_dim(jp_I)%i_len, &
+         &                tl_lat1%t_dim(jp_J)%i_len ))
+
+         dl_lat1(:,:)=tl_lat1%d_value(:,:,1,1)
+
+         ! clean
+         CALL var_clean(tl_lon1)
+         CALL var_clean(tl_lat1)
+      
+         ! compute
+         grid__get_fine_offset_cf(:,:)=grid_get_fine_offset( &
+         &                                         dd_lon0(:,:), dd_lat0(:,:),&
+         &                                         id_imin0, id_jmin0, &
+         &                                         id_imax0, id_jmax0, &
+         &                                         dl_lon1(:,:), dl_lat1(:,:),&
+         &                                         id_rho(:) )
+         
+         DEALLOCATE(dl_lon1, dl_lat1)
+      ENDIF
+
+      ! clean 
+      CALL mpp_clean(tl_coord1)
+      DEALLOCATE(il_rho)
+
+   END FUNCTION grid__get_fine_offset_cf
+   !-------------------------------------------------------------------
+   !> @brief This function get offset between fine grid and coarse grid.
+   !
+   !> @details
+   !> optionally, you could specify on which Arakawa grid point you want to
+   !> work (default 'T')
+   !> offset value could be 0,1,..,rho-1
+   !
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !
+   !> @param[in] td_coord0 coarse grid coordinate 
+   !> @param[in] id_imin0  coarse grid lower left corner i-indice of fine grid domain
+   !> @param[in] id_jmin0  coarse grid lower left corner j-indice of fine grid domain
+   !> @param[in] id_imax0  coarse grid upper right corner i-indice of fine grid domain
+   !> @param[in] id_jmax0  coarse grid upper right corner j-indice of fine grid domain
+   !> @param[in] dd_lon1   fine   grid longitude array 
+   !> @param[in] dd_lat1   fine   grid latitude  array
+   !> @param[in] id_rho    array of refinement factor
+   !> @param[in] cd_point  Arakawa grid point
+   !> @return offset array (/ (/i_offset_left,i_offset_right/),(/j_offset_lower,j_offset_upper/) /)
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_fine_offset_fc( td_coord0, &
+   &                                  id_imin0, id_jmin0, id_imax0, id_jmax0, &
+   &                                  dd_lon1, dd_lat1, &
+   &                                  id_rho, cd_point )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TMPP)                      , INTENT(IN) :: td_coord0
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN) :: dd_lon1
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN) :: dd_lat1
+
+      INTEGER(i4)                     , INTENT(IN) :: id_imin0
+      INTEGER(i4)                     , INTENT(IN) :: id_jmin0
+      INTEGER(i4)                     , INTENT(IN) :: id_imax0
+      INTEGER(i4)                     , INTENT(IN) :: id_jmax0
+
+      INTEGER(i4)     , DIMENSION(:)  , INTENT(IN), OPTIONAL :: id_rho
+      CHARACTER(LEN=*)                , INTENT(IN), OPTIONAL :: cd_point
+
+      ! function
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_fine_offset_fc
+
+      ! local variable
+      INTEGER(i4) :: il_imin0
+      INTEGER(i4) :: il_jmin0
+      INTEGER(i4) :: il_imax0
+      INTEGER(i4) :: il_jmax0
+      
+      INTEGER(i4), DIMENSION(:), ALLOCATABLE :: il_rho
+      
+      INTEGER(i4), DIMENSION(2,2)         :: il_xghost0
+
+      CHARACTER(LEN= 1) :: cl_point
+      CHARACTER(LEN=lc) :: cl_name
+
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon0
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lat0
+
+      TYPE(TVAR) :: tl_lon0
+      TYPE(TVAR) :: tl_lat0
+
+      TYPE(TMPP) :: tl_coord0
+      ! loop indices
+      !----------------------------------------------------------------
+      ! init
+      grid__get_fine_offset_fc(:,:)=-1
+
+      ALLOCATE(il_rho(ip_maxdim))
+      il_rho(:)=1
+      IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
+
+      cl_point='T'
+      IF( PRESENT(cd_point) ) cl_point=TRIM(fct_upper(cd_point))
+
+      ! copy structure
+      tl_coord0=mpp_copy(td_coord0)
+
+      IF( .NOT. ASSOCIATED(tl_coord0%t_proc) )THEN
+         CALL logger_error("GRID GET FINE OFFSET: decompsition of mpp "//&
+         &  "file "//TRIM(tl_coord0%c_name)//" not defined." )
+      ELSE      
+         !1- Coarse grid
+         ! get ghost cell factor on coarse grid
+         il_xghost0(:,:)=grid_get_ghost( tl_coord0 )
+
+         ! open mpp files
+         CALL iom_mpp_open(tl_coord0)
+
+         ! read coarse longitue and latitude
+         WRITE(cl_name,*) 'longitude_'//TRIM(cl_point)
+         tl_lon0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+         WRITE(cl_name,*) 'latitude_'//TRIM(cl_point)
+         tl_lat0=iom_mpp_read_var(tl_coord0, TRIM(cl_name))
+         
+         ! close mpp files
+         CALL iom_mpp_close(tl_coord0)
+
+         CALL grid_del_ghost(tl_lon0, il_xghost0(:,:))
+         CALL grid_del_ghost(tl_lat0, il_xghost0(:,:))
+
+         ALLOCATE(dl_lon0(tl_lon0%t_dim(jp_I)%i_len, &
+         &                tl_lon0%t_dim(jp_J)%i_len ))
+
+         dl_lon0(:,:)=tl_lon0%d_value(:,:,1,1)
+
+         ALLOCATE(dl_lat0(tl_lat0%t_dim(jp_I)%i_len, &
+         &                tl_lat0%t_dim(jp_J)%i_len ))
+
+         dl_lat0(:,:)=tl_lat0%d_value(:,:,1,1)
+
+         ! clean
+         CALL var_clean(tl_lon0)
+         CALL var_clean(tl_lat0)
+
+         ! adjust coarse grid indices
+         il_imin0=id_imin0-il_xghost0(jp_I,1)
+         il_imax0=id_imax0-il_xghost0(jp_I,1)
+
+         il_jmin0=id_jmin0-il_xghost0(jp_J,1)
+         il_jmax0=id_jmax0-il_xghost0(jp_J,1)
+
+      
+         !3- compute
+         grid__get_fine_offset_fc(:,:)=grid_get_fine_offset(&
+         &                                         dl_lon0(:,:), dl_lat0(:,:),&
+         &                                         il_imin0, il_jmin0, &
+         &                                         il_imax0, il_jmax0, &
+         &                                         dd_lon1(:,:), dd_lat1(:,:),&
+         &                                         id_rho(:) )
+         
+         DEALLOCATE(dl_lon0, dl_lat0)
+      ENDIF
+
+      ! clean
+      CALL mpp_clean(tl_coord0)
+      DEALLOCATE(il_rho)
+
+   END FUNCTION grid__get_fine_offset_fc
+   !-------------------------------------------------------------------
+   !> @brief This function get offset between fine grid and coarse grid.
    !
    !> @details
@@ -1543,22 +3585,21 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_lon0 : coarse grid longitude table 
-   !> @param[in] dd_lat0 : coarse grid latitude  table
-   !> @param[in] dd_lon1 : fine   grid longitude table 
-   !> @param[in] dd_lat1 : fine   grid latitude  table
-   !> @param[in] id_imin0 : coarse grid lower left corner i-indice of fine grid domain
-   !> @param[in] id_jmin0 : coarse grid lower left corner j-indice of fine grid domain
-   !> @param[in] id_imax0 : coarse grid upper right corner i-indice of fine grid domain
-   !> @param[in] id_jmax0 : coarse grid upper right corner j-indice of fine grid domain
-   !> @param[in] id_rhoi : i-direction refinement factor
-   !> @param[in] id_rhoj : j-direction refinement factor
-   !> @return offset table (/ (/i_offset_left,i_offset_right!/),(/j_offset_lower,j_offset_upper/) /)
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION grid_get_fine_offset( dd_lon0, dd_lat0, &
-   &                              id_imin0, id_jmin0, id_imax0, id_jmax0, &
-   &                              dd_lon1, dd_lat1, id_rho )
+   !> - November, 2013 - Initial Version
+   !> @date September, 2014 - rename from grid_get_fine_offset
+   !
+   !> @param[in] dd_lon0   coarse grid longitude array 
+   !> @param[in] dd_lat0   coarse grid latitude  array
+   !> @param[in] id_imin0  coarse grid lower left corner i-indice of fine grid domain
+   !> @param[in] id_jmin0  coarse grid lower left corner j-indice of fine grid domain
+   !> @param[in] id_imax0  coarse grid upper right corner i-indice of fine grid domain
+   !> @param[in] id_jmax0  coarse grid upper right corner j-indice of fine grid domain
+   !> @param[in] dd_lon1   fine   grid longitude array 
+   !> @param[in] dd_lat1   fine   grid latitude  array
+   !> @param[in] id_rho    array of refinement factor
+   !> @return offset array (/ (/i_offset_left,i_offset_right/),(/j_offset_lower,j_offset_upper/) /)
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_fine_offset_cc( dd_lon0, dd_lat0, &
+   &                                  id_imin0, id_jmin0, id_imax0, id_jmax0, &
+   &                                  dd_lon1, dd_lat1, id_rho )
       IMPLICIT NONE
       ! Argument
@@ -1576,5 +3617,5 @@
 
       ! function
-      INTEGER(i4), DIMENSION(2,2) :: grid_get_fine_offset
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_fine_offset_cc
 
       ! local variable
@@ -1584,7 +3625,4 @@
       REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_lon1
       
-      REAL(dp) :: dl_dlon
-      REAL(dp) :: dl_dlat
-
       ! loop indices
       INTEGER(i4) :: ji
@@ -1616,62 +3654,70 @@
       WHERE( dd_lon1(:,:) < 0 ) dl_lon1(:,:)=dd_lon1(:,:)+360.         
 
-      grid_get_fine_offset(:,:)=-1
-
-      ! look for i-direction left offset 
-      IF( dl_lon1(1,1) < dl_lon0(id_imin0+1,id_jmin0) )THEN
-         DO ji=1,id_rho(jp_I)+2
-            dl_dlon=ABS(dl_lon1(ji+1,1)-dl_lon1(ji,1))*1.e-3
-            IF( dl_lon1(ji,1) > dl_lon0(id_imin0+1,id_jmin0) + dl_dlon )THEN
-               grid_get_fine_offset(1,1)=(id_rho(jp_I)+1)-ji+MOD(id_rho(jp_I),2)
-               EXIT
-            ENDIF
-         ENDDO
+      ! init
+      grid__get_fine_offset_cc(:,:)=-1
+
+      IF( il_shape1(1) > 1 )THEN
+
+         ! look for i-direction left offset 
+         IF( dl_lon1(1,1) < dl_lon0(id_imin0+1,id_jmin0) )THEN
+            DO ji=1,id_rho(jp_I)+2
+               IF( dl_lon1(ji,1) > dl_lon0(id_imin0+1,id_jmin0) - dp_delta )THEN
+                  grid__get_fine_offset_cc(1,1)=(id_rho(jp_I)+1)-ji
+                  EXIT
+               ENDIF
+            ENDDO
+         ELSE
+            CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
+            &                 " not match fine grid lower left corner.")
+         ENDIF
+
+         ! look for i-direction right offset
+         IF( dl_lon1(il_shape1(1),1) > dl_lon0(id_imax0-1,id_jmin0) )THEN
+            DO ji=1,id_rho(jp_I)+2
+               ii=il_shape1(1)-ji+1
+               IF( dl_lon1(ii,1) < dl_lon0(id_imax0-1,id_jmin0) + dp_delta )THEN
+                  grid__get_fine_offset_cc(1,2)=(id_rho(jp_I)+1)-ji
+                  EXIT
+               ENDIF
+            ENDDO
+         ELSE
+            CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
+            &                 " not match fine grid lower right corner.")
+         ENDIF
+
       ELSE
-         CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
-         &                 " not match fine grid lower left corner.")
-      ENDIF
-
-      ! look for i-direction right offset
-      IF( dl_lon1(il_shape1(1),1) > dl_lon0(id_imax0-1,id_jmin0) )THEN
-         DO ji=1,id_rho(jp_I)+2
-            ii=il_shape1(1)-ji+1
-            dl_dlon=ABS(dl_lon1(ii,1)-dl_lon1(ii-1,1))*1.e-3
-            IF( dl_lon1(ii,1) < dl_lon0(id_imax0-1,id_jmin0) - dl_dlon )THEN
-               grid_get_fine_offset(1,2)=(id_rho(jp_I)+1)-ji+MOD(id_rho(jp_I),2)
-               EXIT
-            ENDIF
-         ENDDO
+         grid__get_fine_offset_cc(1,:)=((id_rho(jp_I)-1)/2)
+      ENDIF
+
+      IF( il_shape1(2) > 1 )THEN
+
+         ! look for j-direction lower offset 
+         IF( dd_lat1(1,1) < dd_lat0(id_imin0,id_jmin0+1) )THEN
+            DO jj=1,id_rho(jp_J)+2
+               IF( dd_lat1(1,jj) > dd_lat0(id_imin0,id_jmin0+1) - dp_delta )THEN
+                  grid__get_fine_offset_cc(2,1)=(id_rho(jp_J)+1)-jj
+                  EXIT
+               ENDIF
+            ENDDO
+         ELSE
+            CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
+            &                 " not match fine grid upper left corner.")
+         ENDIF
+
+         ! look for j-direction upper offset 
+         IF( dd_lat1(1,il_shape1(2)) > dd_lat0(id_imin0,id_jmax0-1) )THEN
+            DO jj=1,id_rho(jp_J)+2
+               ij=il_shape1(2)-jj+1
+               IF( dd_lat1(1,ij) < dd_lat0(id_imin0,id_jmax0-1) + dp_delta )THEN
+                  grid__get_fine_offset_cc(2,2)=(id_rho(jp_J)+1)-jj
+                  EXIT
+               ENDIF
+            ENDDO
+         ELSE
+            CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
+            &                 " not match fine grid upper right corner.")
+         ENDIF
       ELSE
-         CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
-         &                 " not match fine grid lower right corner.")
-      ENDIF
-
-      ! look for j-direction lower offset 
-      IF( dd_lat1(1,1) < dd_lat0(id_imin0,id_jmin0+1) )THEN
-         DO jj=1,id_rho(jp_J)+2
-            dl_dlat=ABS(dd_lat1(1,jj+1)-dd_lat1(1,jj))*1.e-3
-            IF( dd_lat1(1,jj) > dd_lat0(id_imin0,id_jmin0+1) + dl_dlat )THEN
-               grid_get_fine_offset(2,1)=(id_rho(jp_J)+1)-jj+MOD(id_rho(jp_J),2)
-               EXIT
-            ENDIF
-         ENDDO
-      ELSE
-         CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
-         &                 " not match fine grid upper left corner.")
-      ENDIF
-
-      ! look for j-direction upper offset 
-      IF( dd_lat1(1,il_shape1(2)) > dd_lat0(id_imin0,id_jmax0-1) )THEN
-         DO jj=1,id_rho(jp_J)+2
-            ij=il_shape1(2)-jj+1
-            dl_dlat=ABS(dd_lat1(1,ij)-dd_lat1(1,ij-1))*1.e-3
-            IF( dd_lat1(1,ij) < dd_lat0(id_imin0,id_jmax0-1) - dl_dlat )THEN
-               grid_get_fine_offset(2,2)=(id_rho(jp_J)+1)-jj+MOD(id_rho(jp_J),2)
-               EXIT
-            ENDIF
-         ENDDO
-      ELSE
-         CALL logger_error("GRID GET FINE OFFSET: coarse grid indices do "//&
-         &                 " not match fine grid upper right corner.")
+         grid__get_fine_offset_cc(2,:)=((id_rho(jp_J)-1)/2)
       ENDIF
 
@@ -1679,137 +3725,23 @@
       DEALLOCATE( dl_lon1 )
 
-   END FUNCTION grid_get_fine_offset
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function check if ghost cell are used or not, and return ghost
-   !> cell factor (0,1) in i- and j-direction.
+   END FUNCTION grid__get_fine_offset_cc
+   !-------------------------------------------------------------------
+   !> @brief This subroutine check fine and coarse grid coincidence.
    !
    !> @details
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_lon  : grid longitude sturcture 
-   !> @param[in] td_lat  : grid latitude  structure
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION grid__get_ghost_ll( td_lon, td_lat )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TVAR), INTENT(IN) :: td_lon
-      TYPE(TVAR), INTENT(IN) :: td_lat
-
-      ! function
-      INTEGER(i4), DIMENSION(2) :: grid__get_ghost_ll
-
-      ! local variable
-      INTEGER(i4) :: il_ew
-      ! loop indices
-      !----------------------------------------------------------------
-      ! init
-      grid__get_ghost_ll(:)=0
-
-      IF( grid_is_global(td_lon, td_lat) )THEN
-         grid__get_ghost_ll(:)=0
-      ELSE
-         grid__get_ghost_ll(2)=1
-
-         il_ew=td_lon%i_ew
-         IF( il_ew < 0 )THEN
-            grid__get_ghost_ll(1)=1
-         ELSE
-            grid__get_ghost_ll(1)=0
-         ENDIF
-      ENDIF
-
-   END FUNCTION grid__get_ghost_ll
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function check if ghost cell are used or not, and return ghost
-   !> cell factor (0,1) in i- and j-direction.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file sturcture 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION grid__get_ghost_f( td_file )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TFILE), INTENT(IN) :: td_file
-
-      ! function
-      INTEGER(i4), DIMENSION(2) :: grid__get_ghost_f
-
-      ! local variable
-      TYPE(TVAR)  :: tl_lon
-      TYPE(TVAR)  :: tl_lat
-
-      INTEGER(i4) :: il_lonid
-      INTEGER(i4) :: il_latid
-      ! loop indices
-      INTEGER(i4)  :: ji
-      !----------------------------------------------------------------
-      ! init
-      grid__get_ghost_f(:)=0
-
-      IF( td_file%i_id == 0 )THEN
-         CALL logger_error("GRID GET GHOST: file "//&
-         &                 TRIM(td_file%c_name)//" not opened." )
-
-      ELSE
-
-         IF( ASSOCIATED(td_file%t_var) )THEN
-            ! read coarse longitue and latitude
-            il_lonid=var_get_id(td_file%t_var(:),'longitude')
-            il_latid=var_get_id(td_file%t_var(:),'latitude')
-
-            print *,'file ',trim(td_file%c_name),td_file%i_ew
-            DO ji=1,td_file%i_nvar
-               print *,ji,trim(td_file%t_var(ji)%c_name),': ',td_file%t_var(ji)%i_ew
-            ENDDO
-            print *,'lonid ',il_lonid
-            print *,'latid ',il_latid
-            IF( il_lonid /=0 .AND. il_latid /= 0 )THEN
-               tl_lon=iom_read_var(td_file,il_lonid)
-               print *,'lon ',tl_lon%i_ew
-               tl_lat=iom_read_var(td_file,il_latid)
-               print *,'lat ',tl_lat%i_ew
-               ! get ghost cell factor on coarse grid
-               grid__get_ghost_f(:)=grid_get_ghost( tl_lon, tl_lat )
-            ELSE
-               CALL logger_error("GRID GET GHOST: can not find "//&
-               &           "longitude or latitude "//&
-               &           "in file "//TRIM(td_file%c_name))
-            ENDIF
-         ELSE
-           CALL logger_error("GRID GET GHOST: no variable "//&
-           &           "associated to file "//TRIM(td_file%c_name))
-         ENDIF
-
-      ENDIF
-
-   END FUNCTION grid__get_ghost_f
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine check fine and coarse grid coincidence
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_coord0 : coarse grid coordinate file structure 
-   !> @param[in] td_coord1 : fine   grid coordinate file structure 
-   !> @param[in] id_imin0 : coarse grid lower left  corner i-indice of fine grid domain 
-   !> @param[in] id_imax0 : coarse grid upper right corner i-indice of fine grid domain
-   !> @param[in] id_jmin0 : coarse grid lower left  corner j-indice of fine grid domain 
-   !> @param[in] id_jmax0 : coarse grid upper right corner j-indice of fine grid domain  
-   !> @param[in] id_rho   : table of refinement factor 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !
+   !> @param[in] td_coord0 coarse grid coordinate file structure 
+   !> @param[in] td_coord1 fine   grid coordinate file structure 
+   !> @param[in] id_imin0  coarse grid lower left  corner i-indice of fine grid domain 
+   !> @param[in] id_imax0  coarse grid upper right corner i-indice of fine grid domain
+   !> @param[in] id_jmin0  coarse grid lower left  corner j-indice of fine grid domain 
+   !> @param[in] id_jmax0  coarse grid upper right corner j-indice of fine grid domain  
+   !> @param[in] id_rho    array of refinement factor (default 1) 
+   !-------------------------------------------------------------------
    SUBROUTINE grid_check_coincidence( td_coord0, td_coord1, &
    &                                  id_imin0, id_imax0, &
@@ -1819,10 +3751,10 @@
       
       ! Argument      
-      TYPE(TFILE), INTENT(IN) :: td_coord0
-      TYPE(TFILE), INTENT(IN) :: td_coord1
-      INTEGER(i4), INTENT(IN) :: id_imin0
-      INTEGER(i4), INTENT(IN) :: id_imax0
-      INTEGER(i4), INTENT(IN) :: id_jmin0
-      INTEGER(i4), INTENT(IN) :: id_jmax0
+      TYPE(TMPP)               , INTENT(IN) :: td_coord0
+      TYPE(TMPP)               , INTENT(IN) :: td_coord1
+      INTEGER(i4)              , INTENT(IN) :: id_imin0
+      INTEGER(i4)              , INTENT(IN) :: id_imax0
+      INTEGER(i4)              , INTENT(IN) :: id_jmin0
+      INTEGER(i4)              , INTENT(IN) :: id_jmax0
       INTEGER(i4), DIMENSION(:), INTENT(IN) :: id_rho
 
@@ -1852,7 +3784,4 @@
       REAL(dp)    :: dl_lat1p
 
-      REAL(dp)    :: dl_dlon
-      REAL(dp)    :: dl_dlat
-
       LOGICAL     :: ll_coincidence
 
@@ -1862,7 +3791,6 @@
       TYPE(TVAR)  :: tl_lat1
 
-      TYPE(TFILE) :: tl_coord0
-
-      TYPE(TMPP)  :: tl_mppcoord0
+      TYPE(TMPP)  :: tl_coord0
+      TYPE(TMPP)  :: tl_coord1
 
       TYPE(TDOM)  :: tl_dom0
@@ -1875,42 +3803,41 @@
       ll_coincidence=.TRUE.
 
-      ! read coarse longitue and latitude on domain
-      tl_coord0=td_coord0
-      CALL iom_open(tl_coord0)
-
-      !2-1 compute domain
+      ! copy structure
+      tl_coord0=mpp_copy(td_coord0)
+
+      ! compute domain
       tl_dom0=dom_init( tl_coord0,         &
       &                 id_imin0, id_imax0,&
       &                 id_jmin0, id_jmax0 )
 
-      !2-2 close file
-      CALL iom_close(tl_coord0)
-
-      !2-3 read variables on domain (ugly way to do it, have to work on it)
-      !2-3-1 init mpp structure
-      tl_mppcoord0=mpp_init(tl_coord0)
-
-      CALL file_clean(tl_coord0)
-
-      !2-3-2 get processor to be used
-      CALL mpp_get_use( tl_mppcoord0, tl_dom0 )
-
-      !2-3-3 open mpp files
-      CALL iom_mpp_open(tl_mppcoord0)
-
-      !2-3-4 read variable value on domain
-      tl_lon0=iom_mpp_read_var(tl_mppcoord0,'longitude',td_dom=tl_dom0)
-      tl_lat0=iom_mpp_read_var(tl_mppcoord0,'latitude' ,td_dom=tl_dom0)
-
-      !2-3-5 close mpp files
-      CALL iom_mpp_close(tl_mppcoord0)
-
-      !2-3-6 clean structure
-      CALL mpp_clean(tl_mppcoord0)
+      ! open mpp files
+      CALL iom_dom_open(tl_coord0, tl_dom0)
+
+      ! read variable value on domain
+      tl_lon0=iom_dom_read_var(tl_coord0,'longitude',tl_dom0)
+      tl_lat0=iom_dom_read_var(tl_coord0,'latitude' ,tl_dom0)
+
+      ! close mpp files
+      CALL iom_dom_close(tl_coord0)
+
+      ! clean structure
+      CALL mpp_clean(tl_coord0)
+      CALL dom_clean(tl_dom0)
+
+      ! copy structure
+      tl_coord1=mpp_copy(td_coord1)
+
+      ! open mpp files
+      CALL iom_mpp_open(tl_coord1)
 
       ! read fine longitue and latitude
-      tl_lon1=iom_read_var(td_coord1,'longitude')
-      tl_lat1=iom_read_var(td_coord1,'latitude')
+      tl_lon1=iom_mpp_read_var(tl_coord1,'longitude')
+      tl_lat1=iom_mpp_read_var(tl_coord1,'latitude')
       
+      ! close mpp files
+      CALL iom_dom_close(tl_coord1)
+      ! clean structure
+      CALL mpp_clean(tl_coord1)
+
       CALL logger_debug("GRID CHECK COINCIDENCE:"//&
       &        " fine   grid "//TRIM(td_coord1%c_name) )
@@ -1918,6 +3845,6 @@
       &        " coarse grid "//TRIM(td_coord0%c_name) )
 
-      !1- check domain
-      !1-1 check global grid
+      ! check domain
+      ! check global grid
       IF( .NOT. grid_is_global(tl_lon0, tl_lat0) )THEN
          IF( grid_is_global(tl_lon1, tl_lat1) )THEN
@@ -1929,7 +3856,7 @@
 
          ELSE
-            !1-2 ew overlap
             il_ew1=tl_lon1%i_ew
             IF( il_ew1 >= 0 )THEN
+               ! ew overlap
 
                il_ew0=tl_lon0%i_ew
@@ -1940,19 +3867,18 @@
                ENDIF
 
-               il_jmin1=1+ig_ghost
-               il_jmax1=tl_lon1%t_dim(2)%i_len-ig_ghost
+               il_jmin1=1+ip_ghost
+               il_jmax1=tl_lon1%t_dim(2)%i_len-ip_ghost
 
                ll_coincidence=grid__check_lat(&
                &                     tl_lat0%d_value(1,:,1,1),&
-               &                     tl_lat1%d_value(1,il_jmin1:il_jmax1,1,1),&
-               &                     id_rho(jp_J) )
+               &                     tl_lat1%d_value(1,il_jmin1:il_jmax1,1,1))
 
             ELSE
-               !1-3 other case
-               il_imin1=1+ig_ghost
-               il_jmin1=1+ig_ghost
-
-               il_imax1=tl_lon1%t_dim(1)%i_len-ig_ghost
-               il_jmax1=tl_lon1%t_dim(2)%i_len-ig_ghost
+               ! other case
+               il_imin1=1+ip_ghost
+               il_jmin1=1+ip_ghost
+
+               il_imax1=tl_lon1%t_dim(1)%i_len-ip_ghost
+               il_jmax1=tl_lon1%t_dim(2)%i_len-ip_ghost
 
                ll_coincidence=grid__check_corner(&
@@ -1967,5 +3893,5 @@
 
             ENDIF
-            
+ 
          ENDIF
 
@@ -1977,9 +3903,9 @@
       ENDIF
  
-      !2- check refinement factor
+      ! check refinement factor
       ! select point in middle of fine grid
       il_imid1=INT(tl_lon1%t_dim(1)%i_len*0.5)
       il_jmid1=INT(tl_lon1%t_dim(2)%i_len*0.5)
-      
+ 
       dl_lon1=tl_lon1%d_value(il_imid1, il_jmid1,1,1)
       dl_lat1=tl_lat1%d_value(il_imid1, il_jmid1,1,1)
@@ -2000,5 +3926,5 @@
       ! look for closest fine grid point from selected coarse grid point
       il_iind(:)=MAXLOC( tl_lon1%d_value(:,:,1,1), &
-      &                  tl_lon1%d_value(:,:,1,1) <= dl_lon0)
+      &                  tl_lon1%d_value(:,:,1,1) <= dl_lon0 )
 
       il_jind(:)=MAXLOC( tl_lat1%d_value(:,:,1,1), &
@@ -2016,12 +3942,8 @@
       dl_lat1=tl_lat1%d_value(il_indF(1),il_indF(2),1,1)
 
-      !2-1 check i-direction refinement factor
+      ! check i-direction refinement factor
       DO ji=1,MIN(3,il_imid1)
 
          IF( il_indF(1)+ji*id_rho(jp_I)+1 > tl_lon1%t_dim(1)%i_len )THEN
-            CALL logger_debug("GRID CHECK COINCIDENCE: tl_lon1%t_dim(1)%i_len "//TRIM(fct_str(tl_lon1%t_dim(1)%i_len)))
-            CALL logger_debug("GRID CHECK COINCIDENCE: il_indF(1)+ji*id_rhoi+1 "//TRIM(fct_str(il_indF(1)+ji*id_rho(jp_I)+1)))
-            CALL logger_debug("GRID CHECK COINCIDENCE: il_indF(1) "//TRIM(fct_str(il_indF(1))))
-            CALL logger_debug("GRID CHECK COINCIDENCE: id_rhoi "//TRIM(fct_str(id_rho(jp_I))))
             CALL logger_warn("GRID CHECK COINCIDENCE: domain to small "//&
             &  " to check i-direction refinement factor ")
@@ -2032,6 +3954,4 @@
 
             dl_lon1p=tl_lon1%d_value(il_indF(1)+ji*id_rho(jp_I)+1,il_indF(2),1,1)
-
-            dl_dlon=ABS(dl_lon1p-dl_lon1)*1.e-3
 
             SELECT CASE(MOD(id_rho(jp_I),2))
@@ -2049,5 +3969,5 @@
             CASE DEFAULT         
             
-               IF( ABS(dl_lon1 - dl_lon0) > dl_dlon )THEN
+               IF( ABS(dl_lon1 - dl_lon0) > dp_delta )THEN
                   ll_coincidence=.FALSE.
                   CALL logger_debug("GRID CHECK COINCIDENCE: invalid "//&
@@ -2062,5 +3982,5 @@
       ENDDO
 
-      !2-2 check j-direction refinement factor
+      ! check j-direction refinement factor
       DO jj=1,MIN(3,il_jmid1)
 
@@ -2074,6 +3994,4 @@
 
             dl_lat1p=tl_lat1%d_value(il_indF(1),il_indF(2)+jj*id_rho(jp_J)+1,1,1)
-
-            dl_dlat=ABS(dl_lat1p-dl_lat1)*1.e-3
 
             SELECT CASE(MOD(id_rho(jp_J),2))
@@ -2091,5 +4009,5 @@
             CASE DEFAULT
 
-               IF( ABS(dl_lat1-dl_lat0) > dl_dlat )THEN
+               IF( ABS(dl_lat1-dl_lat0) > dp_delta )THEN
                   ll_coincidence=.FALSE.
                   CALL logger_debug("GRID CHECK COINCIDENCE: invalid "//&
@@ -2104,4 +4022,10 @@
       ENDDO
 
+      ! clean 
+      CALL var_clean(tl_lon1)
+      CALL var_clean(tl_lat1)
+      CALL var_clean(tl_lon0)
+      CALL var_clean(tl_lat0)
+
       IF( .NOT. ll_coincidence )THEN
          CALL logger_fatal("GRID CHECK COINCIDENCE: no coincidence "//&
@@ -2111,5 +4035,4 @@
 
    END SUBROUTINE grid_check_coincidence
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function check that fine grid is 
@@ -2118,17 +4041,13 @@
    !> @details
    !> 
-   !> @note deltalon and delatlat are used only to avoid issue due to 
-   !> cubic interpolation approximation on the firsts grid points  
-   !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_lon0 : table of coarse grid longitude
-   !> @param[in] dd_lat0 : table of coarse grid latitude
-   !> @param[in] dd_lon1 : table of fine   grid longitude 
-   !> @param[in] dd_lat1 : table of fine   grid latitude
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_lon0   array of coarse grid longitude
+   !> @param[in] dd_lat0   array of coarse grid latitude
+   !> @param[in] dd_lon1   array of fine   grid longitude 
+   !> @param[in] dd_lat1   array of fine   grid latitude
    !> @return logical, fine grid is inside coarse grid
    !-------------------------------------------------------------------
-   !> @code
    FUNCTION grid__check_corner(dd_lon0, dd_lat0, &
    &                           dd_lon1, dd_lat1 )
@@ -2162,7 +4081,4 @@
       REAL(dp)    :: dl_lon1
       REAL(dp)    :: dl_lat1
-
-      REAL(dp)    :: dl_dlon
-      REAL(dp)    :: dl_dlat
       ! loop indices
       !----------------------------------------------------------------
@@ -2182,15 +4098,13 @@
 
       ! check lower left corner
-      dl_lon0 = dd_lon0(il_imin0, il_jmin0  )
-      dl_lat0 = dd_lat0(il_imin0, il_jmin0  )
+      dl_lon0 = dd_lon0(il_imin0, il_jmin0)
+      dl_lat0 = dd_lat0(il_imin0, il_jmin0)
 
       dl_lon1 = dd_lon1(il_imin1, il_jmin1)
       dl_lat1 = dd_lat1(il_imin1, il_jmin1)
 
-      dl_dlon=ABS(dd_lon1(il_imin1+1,il_jmin1  )-dl_lon1)*1.e-3
-      dl_dlat=ABS(dd_lat1(il_imin1  ,il_jmin1+1)-dl_lat1)*1.e-3
-
-      IF( (ABS(dl_lon1-dl_lon0)>dl_dlon) .AND. (dl_lon1 < dl_lon0 ) .OR. & 
-      &   (ABS(dl_lat1-dl_lat0)>dl_dlat) .AND. (dl_lat1 < dl_lat0 ) )THEN
+
+      IF( (ABS(dl_lon1-dl_lon0)>dp_delta) .AND. (dl_lon1 < dl_lon0 ) .OR. & 
+      &   (ABS(dl_lat1-dl_lat0)>dp_delta) .AND. (dl_lat1 < dl_lat0 ) )THEN
 
          CALL logger_error("GRID CHECK COINCIDENCE: fine grid lower left "//&
@@ -2207,15 +4121,13 @@
 
       ! check upper left corner
-      dl_lon0 = dd_lon0(il_imin0, il_jmax0  )
-      dl_lat0 = dd_lat0(il_imin0, il_jmax0  )
+      dl_lon0 = dd_lon0(il_imin0, il_jmax0)
+      dl_lat0 = dd_lat0(il_imin0, il_jmax0)
 
       dl_lon1 = dd_lon1(il_imin1, il_jmax1)
       dl_lat1 = dd_lat1(il_imin1, il_jmax1)
 
-      dl_dlon=ABS(dd_lon1(il_imin1+1,il_jmax1  )-dl_lon1)*1.e-3
-      dl_dlat=ABS(dd_lat1(il_imin1  ,il_jmax1-1)-dl_lat1)*1.e-3
-
-      IF( (ABS(dl_lon1-dl_lon0)>dl_dlon) .AND. (dl_lon1 < dl_lon0) .OR. &
-      &   (ABS(dl_lat1-dl_lat0)>dl_dlat) .AND. (dl_lat1 > dl_lat0) )THEN
+
+      IF( (ABS(dl_lon1-dl_lon0)>dp_delta) .AND. (dl_lon1 < dl_lon0) .OR. &
+      &   (ABS(dl_lat1-dl_lat0)>dp_delta) .AND. (dl_lat1 > dl_lat0) )THEN
 
          CALL logger_error("GRID CHECK COINCIDENCE: fine grid upper left "//&
@@ -2232,18 +4144,16 @@
 
       ! check lower right corner
-      dl_lon0 = dd_lon0(il_imax0, il_jmin0  )
-      dl_lat0 = dd_lat0(il_imax0, il_jmin0  )
+      dl_lon0 = dd_lon0(il_imax0, il_jmin0)
+      dl_lat0 = dd_lat0(il_imax0, il_jmin0)
 
       dl_lon1 = dd_lon1(il_imax1, il_jmin1)
       dl_lat1 = dd_lat1(il_imax1, il_jmin1)
 
-      dl_dlon=ABS(dd_lon1(il_imax1-1,il_jmin1  )-dl_lon1)*1.e-3
-      dl_dlat=ABS(dd_lat1(il_imax1  ,il_jmin1+1)-dl_lat1)*1.e-3
-
-      IF( (ABS(dl_lon1-dl_lon0)>dl_dlon) .AND. (dl_lon1 > dl_lon0) .OR. &
-      &   (ABS(dl_lat1-dl_lat0)>dl_dlat) .AND. (dl_lat1 < dl_lat0) )THEN
+
+      IF( (ABS(dl_lon1-dl_lon0)>dp_delta) .AND. (dl_lon1 > dl_lon0) .OR. &
+      &   (ABS(dl_lat1-dl_lat0)>dp_delta) .AND. (dl_lat1 < dl_lat0) )THEN
 
          CALL logger_error("GRID CHECK COINCIDENCE: fine grid lower right "//&
-         &     "corner not north west west of coarse grid (imax,jmin) ")
+         &     "corner not north west of coarse grid (imax,jmin) ")
          CALL logger_debug(" fine   grid lower right ( "//&
          &              TRIM(fct_str(dl_lon1))//","//&
@@ -2257,15 +4167,12 @@
 
       ! check upper right corner
-      dl_lon0 = dd_lon0(il_imax0, il_jmax0  )
-      dl_lat0 = dd_lat0(il_imax0, il_jmax0  )
+      dl_lon0 = dd_lon0(il_imax0, il_jmax0)
+      dl_lat0 = dd_lat0(il_imax0, il_jmax0)
 
       dl_lon1 = dd_lon1(il_imax1, il_jmax1)
       dl_lat1 = dd_lat1(il_imax1, il_jmax1)
 
-      dl_dlon=ABS(dd_lon1(il_imax1-1,il_jmax1  )-dl_lon1)*1.e-3
-      dl_dlat=ABS(dd_lat1(il_imax1  ,il_jmax1-1)-dl_lat1)*1.e-3
-
-      IF( (ABS(dl_lon1-dl_lon0)>dl_dlon) .AND. (dl_lon1 > dl_lon0) .OR. &
-      &   (ABS(dl_lat1-dl_lat0)>dl_dlat) .AND. (dl_lat1 > dl_lat0) )THEN
+      IF( (ABS(dl_lon1-dl_lon0)>dp_delta) .AND. (dl_lon1 > dl_lon0) .OR. &
+      &   (ABS(dl_lat1-dl_lat0)>dp_delta) .AND. (dl_lat1 > dl_lat0) )THEN
 
          CALL logger_error("GRID CHECK COINCIDENCE: fine grid upper right "//&
@@ -2288,5 +4195,4 @@
 
    END FUNCTION grid__check_corner
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function check that fine grid latitude are 
@@ -2296,16 +4202,14 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] dd_lat0 : table of coarse grid latitude 
-   !> @param[in] dd_lat1 : table of fine grid latitude 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION grid__check_lat(dd_lat0, dd_lat1, id_rhoj)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] dd_lat0   array of coarse grid latitude 
+   !> @param[in] dd_lat1   array of fine grid latitude 
+   !-------------------------------------------------------------------
+   FUNCTION grid__check_lat(dd_lat0, dd_lat1)
       IMPLICIT NONE
       ! Argument 
       REAL(dp), DIMENSION(:), INTENT(IN) :: dd_lat0
       REAL(dp), DIMENSION(:), INTENT(IN) :: dd_lat1
-      INTEGER(i4)           , INTENT(IN) :: id_rhoj
 
       ! function
@@ -2321,6 +4225,4 @@
       INTEGER(i4) :: il_jmin1
       INTEGER(i4) :: il_jmax1
-
-      REAL(dp)    :: dl_dlat
       ! loop indices
       !----------------------------------------------------------------
@@ -2333,12 +4235,9 @@
 
       !1- check if fine grid inside coarse grid domain
-      il_jmin0=1+1 ; il_jmax0=il_shape0(1)-1
-
-      il_jmin1=1+id_rhoj ; il_jmax1=il_shape1(1)-id_rhoj
-
-      dl_dlat=ABS(dd_lat1(il_jmin1+1)-dd_lat1(il_jmin1))*1.e-3
+      il_jmin0=1 ; il_jmax0=il_shape0(1)
+      il_jmin1=1 ; il_jmax1=il_shape1(1)
 
       ! check lower left fine grid
-      IF( ABS(dd_lat1(il_jmin1)-dd_lat0(il_jmin0)) > dl_dlat .AND. &
+      IF( ABS(dd_lat1(il_jmin1)-dd_lat0(il_jmin0)) > dp_delta .AND. &
       &   dd_lat1(il_jmin1) < dd_lat0(il_jmin0) )THEN
 
@@ -2353,8 +4252,6 @@
       ENDIF
 
-      dl_dlat=ABS(dd_lat1(il_jmax1-1)-dd_lat1(il_jmax1))*1.e-3
-
       ! check upper left fine grid
-      IF( ABS(dd_lat1(il_jmax1)-dd_lat0(il_jmax0)) > dl_dlat .AND. &
+      IF( ABS(dd_lat1(il_jmax1)-dd_lat0(il_jmax0)) > dp_delta .AND. &
       &   dd_lat1(il_jmax1) > dd_lat0(il_jmax0) )THEN
 
@@ -2370,5 +4267,4 @@
       
    END FUNCTION grid__check_lat
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -2376,17 +4272,14 @@
    !> 
    !> @author J.Paul
-   !> - Nov, 2013-Initial version
-   !
-   !> @param[inout] td_var : table of variable structure 
-   !> @param[in] id_ighost : i-direction ghost cell factor 
-   !> @param[in] id_jghost : j-direction ghost cell factor 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE grid_add_ghost(td_var, id_ighost, id_jghost)
+   !> - November, 2013-Initial version
+   !
+   !> @param[inout] td_var array of variable structure 
+   !> @param[in] id_ghost  array of ghost cell factor 
+   !-------------------------------------------------------------------
+   SUBROUTINE grid_add_ghost(td_var, id_ghost)
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(INOUT) :: td_var
-      INTEGER(i4), INTENT(IN   ) :: id_ighost
-      INTEGER(i4), INTENT(IN   ) :: id_jghost
+      TYPE(TVAR) ,                 INTENT(INOUT) :: td_var
+      INTEGER(i4), DIMENSION(2,2), INTENT(IN   ) :: id_ghost
 
       ! local variable
@@ -2409,18 +4302,20 @@
 
          ! copy variable
-         tl_var=td_var
+         tl_var=var_copy(td_var)
 
          CALL var_del_value(td_var)
 
          ! compute indice to fill center
-         il_imin=1+id_ighost*ig_ghost
-         il_jmin=1+id_jghost*ig_ghost
-
-         il_imax=il_imin+tl_var%t_dim(1)%i_len-1
-         il_jmax=il_jmin+tl_var%t_dim(2)%i_len-1
+         il_imin=1+id_ghost(jp_I,1)*ip_ghost
+         il_jmin=1+id_ghost(jp_J,1)*ip_ghost
+
+         il_imax=tl_var%t_dim(1)%i_len+id_ghost(jp_I,1)*ip_ghost
+         il_jmax=tl_var%t_dim(2)%i_len+id_ghost(jp_J,1)*ip_ghost
 
          ! compute new dimension
-         td_var%t_dim(1)%i_len = tl_var%t_dim(1)%i_len + 2*id_ighost*ig_ghost
-         td_var%t_dim(2)%i_len = tl_var%t_dim(2)%i_len + 2*id_jghost*ig_ghost
+         td_var%t_dim(1)%i_len = tl_var%t_dim(1)%i_len + &
+         &                             SUM(id_ghost(jp_I,:))*ip_ghost
+         td_var%t_dim(2)%i_len = tl_var%t_dim(2)%i_len + &
+         &                             SUM(id_ghost(jp_J,:))*ip_ghost
 
          ALLOCATE(dl_value(td_var%t_dim(1)%i_len, &
@@ -2448,5 +4343,4 @@
 
    END SUBROUTINE grid_add_ghost
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -2454,17 +4348,14 @@
    !> 
    !> @author J.Paul
-   !> - Nov, 2013-Initial version
-   !
-   !> @param[inout] td_var : table of variable structure 
-   !> @param[in] id_ighost : i-direction ghost cell factor 
-   !> @param[in] id_jghost : j-direction ghost cell factor 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE grid_del_ghost(td_var, id_ighost, id_jghost)
+   !> - November, 2013-Initial version
+   !
+   !> @param[inout] td_var array of variable structure 
+   !> @param[in] id_ghost  array of ghost cell factor 
+   !-------------------------------------------------------------------
+   SUBROUTINE grid_del_ghost(td_var, id_ghost)
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(INOUT) :: td_var
-      INTEGER(i4), INTENT(IN   ) :: id_ighost
-      INTEGER(i4), INTENT(IN   ) :: id_jghost
+      TYPE(TVAR) ,                 INTENT(INOUT) :: td_var
+      INTEGER(i4), DIMENSION(2,2), INTENT(IN   ) :: id_ghost
 
       ! local variable
@@ -2483,22 +4374,22 @@
       IF( ALL(td_var%t_dim(1:2)%l_use) )THEN
 
-         CALL logger_warn( "DEL GHOST: dimension change in variable "//&
+         CALL logger_warn( "GRID DEL GHOST: dimension change in variable "//&
          &              TRIM(td_var%c_name) )
 
          ! copy variable
-         tl_var=td_var
+         tl_var=var_copy(td_var)
 
          CALL var_del_value(td_var)
 
          ! compute indice to get center
-         il_imin=1+id_ighost*ig_ghost
-         il_jmin=1+id_jghost*ig_ghost
-
-         il_imax=tl_var%t_dim(1)%i_len-id_ighost*ig_ghost
-         il_jmax=tl_var%t_dim(2)%i_len-id_jghost*ig_ghost
+         il_imin=1+id_ghost(jp_I,1)*ip_ghost
+         il_jmin=1+id_ghost(jp_J,1)*ip_ghost
+
+         il_imax=tl_var%t_dim(1)%i_len-id_ghost(jp_I,2)*ip_ghost
+         il_jmax=tl_var%t_dim(2)%i_len-id_ghost(jp_J,2)*ip_ghost
 
          ! compute new dimension
-         td_var%t_dim(1)%i_len = tl_var%t_dim(1)%i_len - 2*id_ighost*ig_ghost
-         td_var%t_dim(2)%i_len = tl_var%t_dim(2)%i_len - 2*id_jghost*ig_ghost
+         td_var%t_dim(1)%i_len = il_imax - il_imin +1 
+         td_var%t_dim(2)%i_len = il_jmax - il_jmin +1 
 
          ALLOCATE(dl_value(td_var%t_dim(1)%i_len, &
@@ -2526,87 +4417,220 @@
 
    END SUBROUTINE grid_del_ghost
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill small closed sea with fill value. 
+   !-------------------------------------------------------------------
+   !> @brief This function check if ghost cell are used or not, and return ghost
+   !> cell factor (0,1) in horizontal plan.
    !
    !> @details
-   !> the minimum size (nbumber of point) of closed sea to be kept could be
-   !> sepcify with id_minsize.
-   !> By default only the biggest sea is preserve.
-   !
+   !> check if domain is global, and if there is an East-West overlap.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] id_mask : domain mask (from grid_split_domain)
-   !> @param[in] id_minsize : minimum size of sea to be kept
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE grid_fill_small_dom(td_var, id_mask, id_minsize)
+   !> - September, 2014- Initial Version
+   !
+   !> @param[in] td_var variable sturcture 
+   !> @return array of ghost cell factor
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_ghost_var( td_var )
       IMPLICIT NONE
-      ! Argument      
-      TYPE(TVAR) ,                 INTENT(INOUT) :: td_var
-      INTEGER(i4), DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_mask
-      INTEGER(i4),                 INTENT(IN   ), OPTIONAL :: id_minsize
+      ! Argument
+      TYPE(TVAR), INTENT(IN) :: td_var
+
+      ! function
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_ghost_var
 
       ! local variable
-      INTEGER(i4)                              :: il_ndom
-      INTEGER(i4)                              :: il_minsize
-      INTEGER(i4), DIMENSION(2)                :: il_shape
-      INTEGER(i4), DIMENSION(:,:), ALLOCATABLE :: il_tmp
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_dim
 
       ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jk
-      INTEGER(i4) :: jl
       !----------------------------------------------------------------
-
-      il_shape(:)=SHAPE(id_mask(:,:))
-      IF( ANY(il_shape(:) /= td_var%t_dim(1:2)%i_len) )THEN
-         CALL logger_error("GRID FILL SMALL DOM: variable and mask "//&
-         &              "dimension differ")
+      ! init
+      grid__get_ghost_var(:,:)=0
+
+      IF( .NOT. ALL(td_var%t_dim(1:2)%l_use) )THEN
+         CALL logger_error("GRID GET GHOST: "//TRIM(td_var%c_name)//" is not a suitable"//&
+         &                 " variable to look for ghost cell (not 2D).")
       ELSE
-
-         il_ndom=MINVAL(id_mask(:,:))
-
-         ALLOCATE( il_tmp(il_shape(1),il_shape(2)) )
-         il_tmp(:,:)=0
-         DO ji=-1,il_ndom,-1
-            WHERE( id_mask(:,:)==ji ) 
-               il_tmp(:,:)=SUM(id_mask(:,:),id_mask(:,:)==ji)/ji
-            END WHERE
-         ENDDO
-
-         il_minsize=MAXVAL(il_tmp(:,:))
-         IF( PRESENT(id_minsize) ) il_minsize=id_minsize
-
-         DO jl=1,td_var%t_dim(4)%i_len
-            DO jk=1,td_var%t_dim(3)%i_len
-               WHERE( il_tmp(:,:) < il_minsize ) 
-                  td_var%d_value(:,:,jk,jl)=td_var%d_fill
-               END WHERE
-            ENDDO
-         ENDDO
-
-         DEALLOCATE( il_tmp )
-
-      ENDIF
-
-   END SUBROUTINE grid_fill_small_dom
-   !> @endcode
+         IF( .NOT. ASSOCIATED(td_var%d_value) )THEN
+            CALL logger_error("GRID GET GHOST: no value associated to "//TRIM(td_var%c_name)//&
+            &                 ". can't look for ghost cell.")
+         ELSE
+            il_dim(:)=td_var%t_dim(:)%i_len
+
+            IF(ALL(td_var%d_value(    1    ,    :    ,1,1)/=td_var%d_fill).AND.&
+            &  ALL(td_var%d_value(il_dim(1),    :    ,1,1)/=td_var%d_fill).AND.&
+            &  ALL(td_var%d_value(    :    ,    1    ,1,1)/=td_var%d_fill).AND.&
+            &  ALL(td_var%d_value(    :    ,il_dim(2),1,1)/=td_var%d_fill))THEN
+            ! no boundary closed
+               CALL logger_warn("GRID GET GHOST: can't determined ghost cell. "//&
+               &             "there is no boundary closed for variable "//&
+               &              TRIM(td_var%c_name))
+
+            ELSE
+               ! check periodicity
+               IF(ANY(td_var%d_value(   1     ,:,1,1)/=td_var%d_fill).OR.&
+               &  ANY(td_var%d_value(il_dim(1),:,1,1)/=td_var%d_fill))THEN
+               ! East-West cyclic (1,4,6)
+                  CALL logger_info("GRID GET GHOST: East West cyclic")
+                  grid__get_ghost_var(jp_I,:)=0
+
+                  IF( ANY(td_var%d_value(:, 1, 1, 1) /= td_var%d_fill) )THEN
+                  ! South boundary not closed 
+
+                     CALL logger_debug("GRID GET GHOST: East_West cyclic")
+                     CALL logger_debug("GRID GET GHOST: South boundary not closed")
+                     CALL logger_error("GRID GET GHOST: should have been an "//&
+                     &              "impossible case")
+
+                  ELSE
+                  ! South boundary closed (1,4,6)
+                     CALL logger_info("GRID GET GHOST: South boundary closed")
+                     grid__get_ghost_var(jp_J,1)=1
+
+                     IF(ANY(td_var%d_value(:,il_dim(2),1,1)/=td_var%d_fill) )THEN
+                     ! North boundary not closed (4,6)
+                        CALL logger_info("GRID GET GHOST: North boundary not closed")
+                        grid__get_ghost_var(jp_J,2)=0
+                     ELSE
+                     ! North boundary closed
+                        CALL logger_info("GRID GET GHOST: North boundary closed")
+                        grid__get_ghost_var(jp_J,2)=1
+                     ENDIF
+
+                  ENDIF
+
+               ELSE
+               ! East-West boundaries closed (0,2,3,5)
+                  CALL logger_info("GRID GET GHOST: East West boundaries closed")
+                  grid__get_ghost_var(jp_I,:)=1
+
+                  IF( ANY(td_var%d_value(:, 1, 1, 1) /= td_var%d_fill) )THEN
+                  ! South boundary not closed (2)
+                     CALL logger_info("GRID GET GHOST: South boundary not closed")
+                     grid__get_ghost_var(jp_J,1)=0
+
+                     IF(ANY(td_var%d_value(:,il_dim(2),1,1)/=td_var%d_fill))THEN
+                     ! North boundary not closed
+                        CALL logger_debug("GRID GET GHOST: East West boundaries "//&
+                        &              "closed")
+                        CALL logger_debug("GRID GET GHOST: South boundary not closed")
+                        CALL logger_debug("GRID GET GHOST: North boundary not closed")
+                        CALL logger_error("GRID GET GHOST: should have been "//&
+                        &              "an impossible case")
+                     ELSE
+                     ! North boundary closed
+                        grid__get_ghost_var(jp_J,2)=1
+                     ENDIF
+
+                  ELSE
+                  ! South boundary closed (0,3,5)
+                     CALL logger_info("GRID GET GHOST: South boundary closed")
+                     grid__get_ghost_var(jp_J,1)=1
+
+                     IF(ANY(td_var%d_value(:,il_dim(2),1,1)/=td_var%d_fill))THEN
+                     ! North boundary not closed (3,5)
+                        CALL logger_info("GRID GET GHOST: North boundary not closed")
+                        grid__get_ghost_var(jp_J,2)=0
+                     ELSE
+                     ! North boundary closed   
+                        CALL logger_info("GRID GET GHOST: North boundary closed")
+                        grid__get_ghost_var(jp_J,2)=1
+                     ENDIF
+
+                  ENDIF
+
+               ENDIF
+
+            ENDIF
+
+         ENDIF
+      ENDIF
+
+   END FUNCTION grid__get_ghost_var
+   !-------------------------------------------------------------------
+   !> @brief This function check if ghost cell are used or not, and return ghost
+   !> cell factor (0,1) in i- and j-direction.
+   !
+   !> @details
+   !> get longitude an latitude array, then
+   !> check if domain is global, and if there is an East-West overlap
+   !> 
+   !> @author J.Paul
+   !> - September, 2014 - Initial Version
+   !> @date October, 2014
+   !> - work on mpp file structure instead of file structure
+   !
+   !> @param[in] td_file   file sturcture
+   !> @return array of ghost cell factor
+   !-------------------------------------------------------------------
+   FUNCTION grid__get_ghost_mpp( td_mpp )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TMPP), INTENT(IN) :: td_mpp
+
+      ! function
+      INTEGER(i4), DIMENSION(2,2) :: grid__get_ghost_mpp
+
+      ! local variable
+      !TYPE(TVAR)  :: tl_lon
+      !TYPE(TVAR)  :: tl_lat
+
+      TYPE(TMPP) :: tl_mpp
+
+      !INTEGER(i4) :: il_lonid
+      !INTEGER(i4) :: il_latid
+      ! loop indices
+      !----------------------------------------------------------------
+      ! init
+      grid__get_ghost_mpp(:,:)=0
+
+      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
+         CALL logger_error("GRID GET GHOST: decomposition of mpp file "//&
+         &                 TRIM(td_mpp%c_name)//" not defined." )
+
+      ELSE
+
+         ! copy structure
+          tl_mpp=mpp_copy(td_mpp)
+
+          IF( tl_mpp%i_perio < 0 )THEN
+             ! compute NEMO periodicity index
+             CALL grid_get_info(tl_mpp)
+          ENDIF
+
+         SELECT CASE(tl_mpp%i_perio)
+            CASE(0)
+               grid__get_ghost_mpp(:,:)=1
+            CASE(1)
+               grid__get_ghost_mpp(jp_J,:)=1
+            CASE(2)
+               grid__get_ghost_mpp(jp_I,:)=1
+               grid__get_ghost_mpp(jp_J,2)=1
+            CASE(3,5)
+               grid__get_ghost_mpp(jp_I,:)=1
+               grid__get_ghost_mpp(jp_J,1)=1
+            CASE(4,6)
+               grid__get_ghost_mpp(jp_J,1)=1
+            CASE DEFAULT
+         END SELECT
+
+         ! clean 
+         CALL mpp_clean(tl_mpp)
+
+      ENDIF
+
+   END FUNCTION grid__get_ghost_mpp
    !-------------------------------------------------------------------
    !> @brief This subroutine compute closed sea domain.
    !
    !> @details
-   !> to each domain is associated a negative value id (from -1 to ...)
-   !
+   !> to each domain is associated a negative value id (from -1 to ...)<br/>
+   !> optionaly you could specify which level use (default 1)
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : variable strucutre 
-   !> @param[in] id_level : level
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var    variable strucutre 
+   !> @param[in] id_level  level
    !> @return domain mask  
    !-------------------------------------------------------------------
-   !> @code
    FUNCTION grid_split_domain(td_var, id_level)
       IMPLICIT NONE
@@ -2692,46 +4716,70 @@
 
    END FUNCTION grid_split_domain
-   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief This function 
-!   !
-!   !> @details
-!   !
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   FUNCTION grid_()
-!      IMPLICIT NONE
-!      ! Argument      
-!      ! function
-!      ! local variable
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END FUNCTION grid_
-!   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief This subroutine 
-!   !
-!   !> @details
-!   !
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   SUBROUTINE grid_()
-!      IMPLICIT NONE
-!      ! Argument      
-!      ! local variable
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END SUBROUTINE grid_
-!   !> @endcode
+   !-------------------------------------------------------------------
+   !> @brief This subroutine fill small closed sea with fill value. 
+   !>
+   !> @details
+   !> the minimum size (nbumber of point) of closed sea to be kept could be
+   !> sepcify with id_minsize.
+   !> By default only the biggest sea is preserve.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_var    variable structure
+   !> @param[in] id_mask      domain mask (from grid_split_domain)
+   !> @param[in] id_minsize   minimum size of sea to be kept
+   !-------------------------------------------------------------------
+   SUBROUTINE grid_fill_small_dom(td_var, id_mask, id_minsize)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TVAR) ,                 INTENT(INOUT) :: td_var
+      INTEGER(i4), DIMENSION(:,:), INTENT(IN   ) :: id_mask
+      INTEGER(i4),                 INTENT(IN   ), OPTIONAL :: id_minsize
+
+      ! local variable
+      INTEGER(i4)                              :: il_ndom
+      INTEGER(i4)                              :: il_minsize
+      INTEGER(i4), DIMENSION(2)                :: il_shape
+      INTEGER(i4), DIMENSION(:,:), ALLOCATABLE :: il_tmp
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jk
+      INTEGER(i4) :: jl
+      !----------------------------------------------------------------
+
+      il_shape(:)=SHAPE(id_mask(:,:))
+      IF( ANY(il_shape(:) /= td_var%t_dim(1:2)%i_len) )THEN
+         CALL logger_error("GRID FILL SMALL DOM: variable and mask "//&
+         &              "dimension differ")
+      ELSE
+
+         il_ndom=MINVAL(id_mask(:,:))
+
+         ALLOCATE( il_tmp(il_shape(1),il_shape(2)) )
+         il_tmp(:,:)=0
+         DO ji=-1,il_ndom,-1
+            WHERE( id_mask(:,:)==ji ) 
+               il_tmp(:,:)=SUM(id_mask(:,:),id_mask(:,:)==ji)/ji
+            END WHERE
+         ENDDO
+
+         il_minsize=MAXVAL(il_tmp(:,:))
+         IF( PRESENT(id_minsize) ) il_minsize=id_minsize
+
+         DO jl=1,td_var%t_dim(4)%i_len
+            DO jk=1,td_var%t_dim(3)%i_len
+               WHERE( il_tmp(:,:) < il_minsize ) 
+                  td_var%d_value(:,:,jk,jl)=td_var%d_fill
+               END WHERE
+            ENDDO
+         ENDDO
+
+         DEALLOCATE( il_tmp )
+
+      ENDIF
+
+   END SUBROUTINE grid_fill_small_dom
 END MODULE grid
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp.f90	(revision 5075)
@@ -8,19 +8,73 @@
 !> @brief 
 !> This module manage interpolation on regular grid.
-!> @note It is used to work on ORCA grid, as we work only with grid indices.
+!>
+!> @details Interpolation method to be used is specify inside variable 
+!>    strcuture, as array of string character.<br/> 
+!>    - td_var\%c_interp(1) string character is the interpolation name choose between:
+!>       - 'nearest'
+!>       - 'cubic  '
+!>       - 'linear '
+!>    - td_var\%c_interp(2) string character is an operation to be used 
+!>    on interpolated value.<br/>
+!>          operation have to be mulitplication '*' or division '/'.<br/>
+!>          coefficient have to be refinement factor following i-direction 'rhoi', 
+!>          j-direction 'rhoj', or k-direction 'rhok'.<br/>
+!>
+!>          Examples: '*rhoi', '/rhoj'.
+!> 
+!>    @note Those informations are read from namelist or variable configuration file (default).<br/>
+!>    Interplation method could be specify for each variable in namelist _namvar_,
+!>    defining string character _cn\_varinfo_.<br/>
+!>    Example:
+!>       - cn_varinfo='varname1:cubic/rhoi', 'varname2:linear' 
+!>
+!>    to create mixed grid (with coarse grid point needed to compute
+!> interpolation):<br/>
+!> @code
+!>    CALL interp_create_mixed_grid( td_var, td_mix [,id_rho] )
+!> @endcode
+!>       - td_var is coarse grid variable (should be extrapolated)
+!>       - td_mix is mixed grid variable structure [output]
+!>       - id_rho is array of refinment factor [optional]
+!>
+!>    to detected point to be interpolated:<br/>
+!> @code
+!>    il_detect(:,:,:)=interp_detect( td_mix [,id_rho] )
+!> @endcode
+!>       - il_detect(:,:,:) is 3D array of detected point to be interpolated
+!>       - td_mix is mixed grid variable
+!>       - id_rho is array of refinement factor [optional]
+!>
+!>    to interpolate variable value:<br/>
+!> @code
+!>    CALL  interp_fill_value( td_var [,id_rho] [,id_offset] )
+!> @endcode
+!>       - td_var is variable structure
+!>       - id_rho is array of refinement factor [optional]
+!>       - id_offset is array of offset between fine and coarse grid [optional]
+!>
+!>    to clean mixed grid (remove points added on mixed grid to compute interpolation):<br/>
+!> @code
+!>    CALL interp_clean_mixed_grid( td_mix, td_var, id_rho )
+!> @endcode
+!>       - td_mix is mixed grid variable structure
+!>       - td_var is variable structure [output]
+!>       - id_rho is array of refinement factor [optional]
+!>       - id_offset is array of offset between fine and coarse grid [optional]
+!>
+!> @note It use to work on ORCA grid, as we work only with grid indices.
 !>
 !> @warning due to the use of second derivative when using cubic interpolation
-!> you should add 2 extrabands
+!> you should add at least 2 extrabands.
 !>
-!> @details
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
+!> @date November, 2013 - Initial Version
+!> @date September, 2014
+!> - add header
+!> - use interpolation method modules
+!>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
-!> - interp 3D
-!> - see issue when fill value is zero for check cubic_fill..
 !----------------------------------------------------------------------
 MODULE interp
@@ -29,22 +83,17 @@
    USE global                          ! global variable
    USE kind                            ! F90 kind parameter
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE fct                             ! basic useful function
-!   USE date                            ! date manager
+   USE date                            ! date manager
    USE att                             ! attribute manager
    USE dim                             ! dimension manager
    USE var                             ! variable manager
-!   USE file                            ! file manager
-!   USE iom                             ! I/O manager
-!   USE dom                             ! domain manager
    USE grid                            ! grid manager
    USE extrap                          ! extrapolation manager
-!   USE interp                          ! interpolation manager
-!   USE filter                          ! filter manager
-!   USE mpp                             ! MPP manager
-!   USE iom_mpp                         ! MPP I/O manager
+   USE interp_cubic                    !   cubic interpolation manager
+   USE interp_linear                   !  linear interpolation manager
+   USE interp_nearest                  ! nearest interpolation manager
 
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
@@ -53,34 +102,16 @@
    ! function and subroutine
    PUBLIC :: interp_detect             !< detected point to be interpolated
-   PUBLIC :: interp_fill_value         !< interpolate value over detectected point
+   PUBLIC :: interp_fill_value         !< interpolate value
    PUBLIC :: interp_create_mixed_grid  !< create mixed grid
    PUBLIC :: interp_clean_mixed_grid   !< clean mixed grid
 
-   PRIVATE :: interp__detect           !< detected point to be interpolated
-   PRIVATE :: interp__detect_wrapper   !< detected point to be interpolated
-   PRIVATE :: interp__fill_value_wrapper !< interpolate value over detectected point
-   PRIVATE :: interp__fill_value       !< interpolate value over detectected point
-   PRIVATE :: interp__clean_even_grid  !< clean even mixed grid
-   PRIVATE :: interp__del_offset       !< remove offset from interpolated grid
-   PRIVATE :: interp__check_method     !< check if interpolation method available
-!   PRIVATE :: interp__3D               !< interpolate 3D grid
-   PRIVATE :: interp__2D               !< interpolate 2D grid
-   PRIVATE :: interp__1D               !< interpolate 1D grid 
-   PRIVATE :: interp__2D_cubic_coef    !< compute coefficient for bicubic interpolation 
-   PRIVATE :: interp__2D_cubic_fill    !< compute bicubic interpolation 
-   PRIVATE :: interp__2D_linear_coef   !< compute coefficient for bilinear interpolation
-   PRIVATE :: interp__2D_linear_fill   !< compute bilinear interpolation 
-   PRIVATE :: interp__2D_nearest_fill  !< compute nearest interpolation 
-   PRIVATE :: interp__1D_cubic_coef    !< compute coefficient for cubic interpolation 
-   PRIVATE :: interp__1D_cubic_fill    !< compute cubic interpolation 
-   PRIVATE :: interp__1D_linear_coef   !< compute coefficient for linear interpolation
-   PRIVATE :: interp__1D_linear_fill   !< compute linear interpolation 
-   PRIVATE :: interp__1D_nearest_fill  !< compute nearest interpolation 
-!   PRIVATE :: interp__longitude
+   PRIVATE :: interp__detect              ! detected point to be interpolated
+   PRIVATE :: interp__detect_wrapper      ! detected point to be interpolated
+   PRIVATE :: interp__fill_value_wrapper  ! interpolate value over detectected point
+   PRIVATE :: interp__fill_value          ! interpolate value over detectected point
+   PRIVATE :: interp__clean_even_grid     ! clean even mixed grid
+   PRIVATE :: interp__check_method        ! check if interpolation method available
    
    TYPE TINTERP
-      !CHARACTER(LEN=lc) :: c_name = 'unknown'   !< interpolation method name
-      !CHARACTER(LEN=lc) :: c_factor = 'unknown' !< interpolation factor
-      !CHARACTER(LEN=lc) :: c_divisor = 'unknown'   !< interpolation divisor
       CHARACTER(LEN=lc) :: c_name   = '' !< interpolation method name
       CHARACTER(LEN=lc) :: c_factor = '' !< interpolation factor
@@ -89,9 +120,9 @@
 
    INTERFACE interp_detect
-      MODULE PROCEDURE interp__detect_wrapper !< detected point to be interpolated
+      MODULE PROCEDURE interp__detect_wrapper 
    END INTERFACE interp_detect
 
    INTERFACE interp_fill_value
-      MODULE PROCEDURE interp__fill_value_wrapper !< detected point to be interpolated
+      MODULE PROCEDURE interp__fill_value_wrapper 
    END INTERFACE interp_fill_value
 
@@ -99,16 +130,16 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This function check if interpolation method available.
+   !> This function check if interpolation method is available.
    !> 
    !> @details 
+   !> check if name of interpolation method is present in global list of string
+   !> character cp_interp_list (see global.f90).
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[in] cd_method : interpolation method
+   !> @param[in] cd_method interpolation method
    !> @return 
-   !> @todo see extrap_detect
-   !-------------------------------------------------------------------
-   !> @code
+   !-------------------------------------------------------------------
    FUNCTION interp__check_method( cd_method )
       IMPLICIT NONE
@@ -130,6 +161,6 @@
 
       interp__check_method=.FALSE.
-      DO ji=1,ig_ninterp
-         cl_interp=fct_lower(cg_interp_list(ji))
+      DO ji=1,ip_ninterp
+         cl_interp=fct_lower(cp_interp_list(ji))
          IF( TRIM(cl_interp) == TRIM(cl_method) )THEN
             interp__check_method=.TRUE.
@@ -139,5 +170,4 @@
 
    END FUNCTION interp__check_method
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -149,11 +179,10 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mix : mixed grid variable (to interpolate)
-   !> @param[in] id_rho : table of refinement factor
-   !> @return table of detected point to be interpolated 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] td_mix mixed grid variable (to interpolate)
+   !> @param[in] id_rho array of refinement factor
+   !> @return 3D array of detected point to be interpolated 
+   !-------------------------------------------------------------------
    FUNCTION interp__detect_wrapper( td_mix, id_rho )
       IMPLICIT NONE
@@ -168,5 +197,4 @@
 
       ! local variable
-
       ! loop indices
       !----------------------------------------------------------------
@@ -208,5 +236,4 @@
 
    END FUNCTION interp__detect_wrapper
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -217,11 +244,10 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
+   !> - November, 2013- Initial Version
    !
-   !> @param[in] td_mix : mixed grid variable (to interpolate)
-   !> @param[in] id_rho : table of refinement factor
-   !> @return table of detected point to be interpolated 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] td_mix mixed grid variable (to interpolate)
+   !> @param[in] id_rho array of refinement factor
+   !> @return 3D array of detected point to be interpolated 
+   !-------------------------------------------------------------------
    FUNCTION interp__detect( td_mix, id_rho )
       IMPLICIT NONE
@@ -253,5 +279,5 @@
       ALLOCATE( il_rho(ip_maxdim) )
       il_rho(:)=1
-      IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
+      IF( PRESENT(id_rho) ) il_rho(1:SIZE(id_rho(:)))=id_rho(:)
 
       ! special case for even refinement on ARAKAWA-C grid
@@ -289,4 +315,5 @@
       il_dim(:)=td_mix%t_dim(1:3)%i_len
 
+      ! init
       interp__detect(:,:,:)=1
 
@@ -297,26 +324,32 @@
 
       ! do not compute point near fill value
-      FORALL( ji=1:il_dim(1):il_rho(jp_I), &
-      &       jj=1:il_dim(2):il_rho(jp_J), &
-      &       jk=1:il_dim(3):il_rho(jp_K), &
-      &       td_mix%d_value(ji,jj,jk,1) == td_mix%d_fill )
-
-         ! i-direction
-         interp__detect(MAX(1,ji-il_xextra):MIN(ji+il_xextra,il_dim(1)),&
-         &              MAX(1,jj-(il_rho(jp_J)-1)):MIN(jj+(il_rho(jp_J)-1),il_dim(2)),&
-         &              MAX(1,jk-(il_rho(jp_K)-1)):MIN(jk+(il_rho(jp_K)-1),il_dim(3)) )=0 
-         ! j-direction
-         interp__detect(MAX(1,ji-(il_rho(jp_I)-1)):MIN(ji+(il_rho(jp_I)-1),il_dim(1)),&
-         &              MAX(1,jj-il_yextra):MIN(jj+il_yextra,il_dim(2)),&
-         &              MAX(1,jk-(il_rho(jp_K)-1)):MIN(jk+(il_rho(jp_K)-1),il_dim(3)) )=0
-         ! k-direction
-         interp__detect(MAX(1,ji-(il_rho(jp_I)-1)):MIN(ji+(il_rho(jp_I)-1),il_dim(1)),&
-         &              MAX(1,jj-(il_rho(jp_J)-1)):MIN(jj+(il_rho(jp_J)-1),il_dim(2)),&
-         &              MAX(1,jk-il_zextra):MIN(jk+il_zextra,il_dim(3)) )=0         
-
-      END FORALL
+      DO jk=1,il_dim(3),il_rho(jp_K)
+         DO jj=1,il_dim(2),il_rho(jp_J)
+            DO ji=1,il_dim(1),il_rho(jp_I)
+
+               IF( td_mix%d_value(ji,jj,jk,1) == td_mix%d_fill )THEN
+
+                  ! i-direction
+                  interp__detect(MAX(1,ji-il_xextra):MIN(ji+il_xextra,il_dim(1)),&
+                  &              MAX(1,jj-(il_rho(jp_J)-1)):MIN(jj+(il_rho(jp_J)-1),il_dim(2)),&
+                  &              MAX(1,jk-(il_rho(jp_K)-1)):MIN(jk+(il_rho(jp_K)-1),il_dim(3)) )=0 
+                  ! j-direction
+                  interp__detect(MAX(1,ji-(il_rho(jp_I)-1)):MIN(ji+(il_rho(jp_I)-1),il_dim(1)),&
+                  &              MAX(1,jj-il_yextra):MIN(jj+il_yextra,il_dim(2)),&
+                  &              MAX(1,jk-(il_rho(jp_K)-1)):MIN(jk+(il_rho(jp_K)-1),il_dim(3)) )=0
+                  ! k-direction
+                  interp__detect(MAX(1,ji-(il_rho(jp_I)-1)):MIN(ji+(il_rho(jp_I)-1),il_dim(1)),&
+                  &              MAX(1,jj-(il_rho(jp_J)-1)):MIN(jj+(il_rho(jp_J)-1),il_dim(2)),&
+                  &              MAX(1,jk-il_zextra):MIN(jk+il_zextra,il_dim(3)) )=0         
+
+               ENDIF
+
+            ENDDO
+         ENDDO
+      ENDDO
+
+      DEALLOCATE( il_rho )
 
    END FUNCTION interp__detect
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -330,13 +363,10 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : coarse grid variable (should be extrapolated)
-   !> @param[out] td_mix : mixed grid variable
-   !> @param[in] id_rho  : table of refinment factor 
-   !>
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] td_var    coarse grid variable (should be extrapolated)
+   !> @param[out] td_mix   mixed grid variable
+   !> @param[in] id_rho    array of refinment factor (default 1) 
+   !-------------------------------------------------------------------
    SUBROUTINE interp_create_mixed_grid( td_var, td_mix, id_rho )
       IMPLICIT NONE
@@ -359,5 +389,5 @@
       ALLOCATE(il_rho(ip_maxdim))
       il_rho(:)=1
-      IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
+      IF( PRESENT(id_rho) ) il_rho(1:SIZE(id_rho(:)))=id_rho(:)
 
       ! special case for even refinement on ARAKAWA-C grid
@@ -381,5 +411,5 @@
 
       ! copy variable
-      td_mix=td_var
+      td_mix=var_copy(td_var)
 
       ! compute new dimension length
@@ -408,6 +438,7 @@
       &     td_var%d_value(:,:,:,:)
 
+      DEALLOCATE(il_rho)
+
    END SUBROUTINE interp_create_mixed_grid
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -418,16 +449,13 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]  td_mix : mixed grid variable
-   !> @param[in] id_rho  : table of refinment factor 
-   !>
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_mix mixed grid variable
+   !> @param[in] id_rho    array of refinment factor 
+   !-------------------------------------------------------------------
    SUBROUTINE interp__clean_even_grid( td_mix, id_rho )
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR) , INTENT(INOUT) :: td_mix 
+      TYPE(TVAR) ,               INTENT(INOUT) :: td_mix 
       INTEGER(I4), DIMENSION(:), INTENT(IN   ), OPTIONAL :: id_rho
 
@@ -468,9 +496,9 @@
       END SELECT
 
-      ! copy variable
-      tl_mix=td_mix
-
       ! remove some point only if refinement in some direction is even
       IF( ANY(ll_even(:)) )THEN
+
+         ! copy variable
+         tl_mix=var_copy(td_mix)
 
          ALLOCATE( ll_mask( tl_mix%t_dim(1)%i_len, &
@@ -554,5 +582,8 @@
 
             td_mix%d_value(:,:,:,:)=RESHAPE( dl_vect(:), &
-            &                                SHAPE=td_mix%t_dim(:)%i_len )
+            &                                SHAPE=(/td_mix%t_dim(1)%i_len, &
+            &                                        td_mix%t_dim(2)%i_len, &
+            &                                        td_mix%t_dim(3)%i_len, &
+            &                                        td_mix%t_dim(4)%i_len/) )
 
             DEALLOCATE( dl_vect )
@@ -562,35 +593,38 @@
          DEALLOCATE( ll_mask )
 
+         ! clean
+         CALL var_clean(tl_mix)
+
       ENDIF
 
-      CALL var_clean(tl_mix)
+      ! clean
+      DEALLOCATE(il_rho)
 
    END SUBROUTINE interp__clean_even_grid
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine save interpolated value over domain. 
-   !> And so remove points added on mixed grid 
-   !> to compute interpolation
+   !> This subroutine remove points added on mixed grid 
+   !> to compute interpolation. And save interpolated value over domain. 
    !> 
    !> @details 
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : table of mixed grid variable (to interpolate)
-   !> @param[in] id_rho : table of refinement factor
-   !> @return 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - use offset to save useful domain
+   !>
+   !> @param[in] td_mix    mixed grid variable structure
+   !> @param[out] td_var   variable structure
+   !> @param[in] id_rho    array of refinement factor (default 1)
+   !> @param[in] id_offset 2D array of offset between fine and coarse grid
+   !-------------------------------------------------------------------
    SUBROUTINE interp_clean_mixed_grid( td_mix, td_var, &
-   &                                   id_rho, &
-   &                                   id_offset )
+   &                                   id_rho, id_offset )
       IMPLICIT NONE
       ! Argument
       TYPE(TVAR)                 , INTENT(IN   ) :: td_mix
       TYPE(TVAR)                 , INTENT(  OUT) :: td_var
-      INTEGER(I4), DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_rho
-      INTEGER(I4), DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_offset
+      INTEGER(I4), DIMENSION(:)  , INTENT(IN   ) :: id_rho
+      INTEGER(I4), DIMENSION(2,2), INTENT(IN   ) :: id_offset
 
       ! local variable
@@ -605,6 +639,4 @@
       INTEGER(i4) :: il_jmax1
 
-      INTEGER(i4), DIMENSION(2,2) :: il_offset
-
       REAL(dp), DIMENSION(:,:,:,:) , ALLOCATABLE :: dl_value
 
@@ -613,15 +645,6 @@
       ! loop indices
       !----------------------------------------------------------------
-      il_offset(:,:)=0 
-      IF( PRESENT(id_offset) )THEN
-         IF( ANY( SHAPE(id_offset(:,:)) /= SHAPE(il_offset(:,:)) ) )THEN
-            CALL logger_error("INTERP CLEAN MIXED GRID: invalid dimension of"//&
-            &                 " offset table")
-         ELSE
-            il_offset(:,:)=id_offset(:,:)
-         ENDIF
-      ENDIF
       ! copy mixed variable in temporary structure
-      tl_mix=td_mix
+      tl_mix=var_copy(td_mix)
 
       ! remove unusefull points over mixed grid for even refinement
@@ -629,131 +652,62 @@
 
       ! copy cleaned mixed variable
-      td_var=tl_mix
-      IF( ALL(td_var%t_dim(1:2)%l_use) )THEN
-
-         ! delete table of value
-         CALL var_del_value(td_var)
-
-         ! compute domain indices
-         il_imin0=1  ; il_imax0=td_var%t_dim(1)%i_len
-         il_jmin0=1  ; il_jmax0=td_var%t_dim(2)%i_len
-   
-         il_imin1=il_imin0+il_offset(1,1)
-         il_jmin1=il_jmin0+il_offset(2,1)
-   
-         il_imax1=il_imax0-il_offset(1,2)
-         il_jmax1=il_jmax0-il_offset(2,2)
-
-         SELECT CASE(TRIM(td_var%c_point))
-         CASE('U')
-            il_imin1=il_imin0+(il_offset(1,1)-1)
-            il_imax1=il_imax0-(il_offset(1,2)+1)
-         CASE('V')
-            il_jmin1=il_jmin0+(il_offset(2,1)-1)
-            il_jmax1=il_jmax0-(il_offset(2,2)+1)
-         CASE('F')
-            il_imin1=il_imin0+(il_offset(1,1)-1)
-            il_imax1=il_imax0-(il_offset(1,2)+1)
-
-            il_jmin1=il_jmin0+(il_offset(2,1)-1)
-            il_jmax1=il_jmax0-(il_offset(2,2)+1)
-         END SELECT
-
-         ! compute new dimension
-         td_var%t_dim(1)%i_len=il_imax1-il_imin1+1
-         td_var%t_dim(2)%i_len=il_jmax1-il_jmin1+1
+      td_var=var_copy(tl_mix)
+
+      ! delete array of value
+      CALL var_del_value(td_var)
+
+      ! compute domain indices in i-direction
+      il_imin0=1  ; il_imax0=td_var%t_dim(1)%i_len
  
-         ALLOCATE(dl_value(td_var%t_dim(1)%i_len, &
-         &                 td_var%t_dim(2)%i_len, &
-         &                 td_var%t_dim(3)%i_len, &
-         &                 td_var%t_dim(4)%i_len) )
-
-         dl_value( 1:td_var%t_dim(1)%i_len, &
-         &         :,:,:) = tl_mix%d_value( il_imin1:il_imax1, &
-         &                                  il_jmin1:il_jmax1, &
-         &                                      :, : )
-
-         ! add variable value
-         CALL var_add_value(td_var,dl_value(:,:,:,:))
-
-         ! save variable type
-         td_var%i_type=tl_mix%i_type
-
-         DEALLOCATE(dl_value)
+      IF( td_var%t_dim(1)%l_use )THEN
+         il_imin1=il_imin0+id_offset(Jp_I,1)
+         il_imax1=il_imax0-id_offset(Jp_I,2)
+      ELSE
+
+         il_imin1=il_imin0
+         il_imax1=il_imax0
 
       ENDIF
-      
+
+      ! compute domain indices in j-direction
+      il_jmin0=1  ; il_jmax0=td_var%t_dim(2)%i_len
+ 
+      IF( td_var%t_dim(2)%l_use )THEN
+         il_jmin1=il_jmin0+id_offset(Jp_J,1)
+         il_jmax1=il_jmax0-id_offset(Jp_J,2)
+      ELSE
+
+         il_jmin1=il_jmin0
+         il_jmax1=il_jmax0
+ 
+      ENDIF
+
+      ! compute new dimension
+      td_var%t_dim(1)%i_len=il_imax1-il_imin1+1
+      td_var%t_dim(2)%i_len=il_jmax1-il_jmin1+1
+ 
+      ALLOCATE(dl_value(td_var%t_dim(1)%i_len, &
+      &                 td_var%t_dim(2)%i_len, &
+      &                 td_var%t_dim(3)%i_len, &
+      &                 td_var%t_dim(4)%i_len) )
+
+      dl_value( 1:td_var%t_dim(1)%i_len, &
+      &         1:td_var%t_dim(2)%i_len, &
+      &         :,:) = tl_mix%d_value( il_imin1:il_imax1, &
+      &                                il_jmin1:il_jmax1, &
+      &                                     :, : )
+
+      ! add variable value
+      CALL var_add_value(td_var,dl_value(:,:,:,:))
+
+      DEALLOCATE(dl_value)
+ 
+      ! clean
       CALL var_clean(tl_mix)
 
    END SUBROUTINE interp_clean_mixed_grid
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine save interpolated value over domain. 
-   !> And so remove points added on mixed grid 
-   !> to compute interpolation
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : table of mixed grid variable (to interpolate)
-   !> @param[in] id_offset : table of offset
-   !> @return 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__del_offset( td_var, id_offset )
-      IMPLICIT NONE
-      ! Argument
-      TYPE(TVAR)                 , INTENT(INOUT) :: td_var
-      INTEGER(i4), DIMENSION(:,:), INTENT(IN   ) :: id_offset
-
-      ! local variable
-      INTEGER(i4) :: il_imin1
-      INTEGER(i4) :: il_jmin1
-      INTEGER(i4) :: il_imax1
-      INTEGER(i4) :: il_jmax1
-
-      REAL(dp), DIMENSION(:,:,:,:) , ALLOCATABLE :: dl_value
-
-      ! loop indices
-      !----------------------------------------------------------------
-   
-      IF( ALL(td_var%t_dim(1:2)%l_use) )THEN
-
-         il_imin1=1+id_offset(1,1)
-         il_jmin1=1+id_offset(2,1)
-
-         il_imax1=td_var%t_dim(1)%i_len-id_offset(2,1)
-         il_jmax1=td_var%t_dim(2)%i_len-id_offset(2,2)
-
-         ! compute new dimension
-         td_var%t_dim(1)%i_len=il_imax1-il_imin1+1
-         td_var%t_dim(2)%i_len=il_jmax1-il_jmin1+1
-         ALLOCATE( dl_value( td_var%t_dim(1)%i_len, &
-         &                   td_var%t_dim(2)%i_len, &
-         &                   td_var%t_dim(3)%i_len, &
-         &                   td_var%t_dim(4)%i_len) )
-
-         dl_value(:,:,:,:)=td_var%d_value( il_imin1:il_imax1, &
-         &                                 il_jmin1:il_jmax1, &
-         &                                 :,: )
-
-         ! delete table of value
-         CALL var_del_value(td_var)
-
-         ! add variable value
-         CALL var_add_value(td_var,dl_value(:,:,:,:))
-
-         DEALLOCATE(dl_value)
-
-      ENDIF
-
-   END SUBROUTINE interp__del_offset
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine interpolate detected point.
+   !> This subroutine interpolate variable value.
    !> 
    !> @details 
@@ -762,10 +716,10 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : variable to be interpolated
-   !> @param[in] id_rho : table of refinement factor
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_var variable structure
+   !> @param[in] id_rho    array of refinement factor
+   !> @param[in] id_offset 2D array of offset between fine and coarse grid
+   !-------------------------------------------------------------------
    SUBROUTINE interp__fill_value_wrapper( td_var, & 
    &                                      id_rho, &
@@ -774,30 +728,18 @@
       ! Argument
       TYPE(TVAR) ,                 INTENT(INOUT) :: td_var
-      INTEGER(I4), DIMENSION(:),   INTENT(IN   ), OPTIONAL :: id_rho
+      INTEGER(I4), DIMENSION(:)  , INTENT(IN   ), OPTIONAL :: id_rho
       INTEGER(I4), DIMENSION(:,:), INTENT(IN   ), OPTIONAL :: id_offset
 
       ! local variable
-      CHARACTER(LEN=lc)                 :: cl_method
-      INTEGER(i4)      , DIMENSION(:), ALLOCATABLE  :: il_rho
-      INTEGER(i4)      , DIMENSION(2,2) :: il_offset
+      CHARACTER(LEN=lc)                            :: cl_method
+      INTEGER(i4)      , DIMENSION(:), ALLOCATABLE :: il_rho
+      INTEGER(i4)      , DIMENSION(2,2)            :: il_offset
 
       ! loop indices
       !----------------------------------------------------------------
 
-      SELECT CASE(TRIM(td_var%c_interp(1)))
-         CASE('cubic','linear','nearest')
-            cl_method=TRIM(td_var%c_interp(1))
-         CASE DEFAULT
-            CALL logger_warn("INTERP FILL: interpolation method unknown."//&
-            &  " use linear interpolation")
-            cl_method='linear'
-
-            ! update variable structure value
-            td_var%c_interp(1)='linear'
-      END SELECT
-
       ALLOCATE( il_rho(ip_maxdim) )
       il_rho(:)=1
-      IF( PRESENT(id_rho) ) il_rho(:)=id_rho(:)
+      IF( PRESENT(id_rho) ) il_rho(1:SIZE(id_rho(:)))=id_rho(:)
       IF( ANY(il_rho(:) < 0) )THEN
          CALL logger_error("INTERP FILL VALUE: invalid "//&
@@ -808,5 +750,5 @@
       IF( PRESENT(id_offset) )THEN
          IF( ANY(SHAPE(id_offset(:,:)) /= (/2,2/)) )THEN
-            CALL logger_error("INTERP FILL VALUE: invalid table of offset")
+            CALL logger_error("INTERP FILL VALUE: invalid array of offset")
          ELSE
             il_offset(:,:)=id_offset(:,:)
@@ -817,4 +759,15 @@
       &   (il_rho(jp_J) /= 1 .AND. td_var%t_dim(2)%l_use) .OR. &
       &   (il_rho(jp_K) /= 1 .AND. td_var%t_dim(3)%l_use) )THEN
+
+         SELECT CASE(TRIM(td_var%c_interp(1)))
+            CASE('cubic','linear','nearest')
+               cl_method=TRIM(td_var%c_interp(1))
+            CASE DEFAULT
+               CALL logger_warn("INTERP FILL VALUE: interpolation method unknown."//&
+               &  " use linear interpolation")
+               cl_method='linear'
+               ! update variable structure value
+               td_var%c_interp(1)='linear'
+         END SELECT
 
          CALL logger_info("INTERP FILL: interpolate "//TRIM(td_var%c_name)//&
@@ -826,6 +779,5 @@
  
          CALL interp__fill_value( td_var, cl_method, & 
-         &                        il_rho(:), &
-         &                        il_offset(:,:) )
+         &                        il_rho(:), il_offset(:,:) )
 
          SELECT CASE(TRIM(td_var%c_interp(2)))
@@ -864,26 +816,27 @@
          END SELECT
 
+      ELSE
+         td_var%c_interp(:)=''
       ENDIF
 
+      DEALLOCATE(il_rho)
+
    END SUBROUTINE interp__fill_value_wrapper
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !> This subroutine interpolate value over mixed grid.
    !> 
-   !> @details 
-   !> 
-   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable
-   !> @param[in] cd_method : interpolation method 
-   !> @param[in] id_rho : table of refinment factor 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - use interpolation method modules
+   !>
+   !> @param[inout] td_var variable structure
+   !> @param[in] cd_method interpolation method 
+   !> @param[in] id_rho    array of refinment factor 
+   !> @param[in] id_offset 2D array of offset between fine and coarse grid
+   !-------------------------------------------------------------------
    SUBROUTINE interp__fill_value( td_var, cd_method, &
-   &                              id_rho, &
-   &                              id_offset )
+   &                              id_rho, id_offset )
       IMPLICIT NONE
       ! Argument
@@ -891,5 +844,5 @@
       CHARACTER(LEN=*)                , INTENT(IN   ) :: cd_method
       INTEGER(I4)     , DIMENSION(:)  , INTENT(IN   ) :: id_rho
-      INTEGER(I4)     , DIMENSION(:,:), INTENT(IN   ) :: id_offset
+      INTEGER(I4)     , DIMENSION(2,2), INTENT(IN   ) :: id_offset
 
       ! local variable
@@ -908,10 +861,6 @@
 
       TYPE(TATT)                                       :: tl_att
-
+ 
       ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jj
-      INTEGER(i4) :: jk
-      INTEGER(i4) :: jl
       !----------------------------------------------------------------
 
@@ -935,4 +884,7 @@
       tl_att=att_init('interpolation',cl_interp)
       CALL var_move_att(tl_mix, tl_att)
+
+      ! clean
+      CALL att_clean(tl_att)
 
       ! special case for even refinement on ARAKAWA-C grid
@@ -972,79 +924,20 @@
 
       !3- interpolate
-      DO jl=1,tl_mix%t_dim(4)%i_len
-         IF( il_rho(jp_K) /= 1 )THEN
-!            CALL interp__3D(tl_mix%d_value(:,:,:,jl), tl_mix%d_fill, &
-!              &             il_detect(:,:,:), cd_method,             &
-!              &             il_rhoi, il_rhoj, il_rhok,               &
-!              &             ll_even(:), ll_discont )
-             CALL logger_error("INTERP FILL: can not interpolate "//&
-             &                "vertically for now ")
-         ENDIF
-
-         IF( ANY(il_detect(:,:,:)==1) )THEN
-            ! I-J plan
-            DO jk=1,tl_mix%t_dim(3)%i_len
-              CALL interp__2D(tl_mix%d_value(:,:,jk,jl), tl_mix%d_fill, &
-              &               il_detect(:,:,jk), cd_method,             &
-              &               il_rho(jp_I), il_rho(jp_J),               &
-              &               ll_even(1:2), ll_discont)
-            ENDDO
-            IF( ALL(il_detect(:,:,:)==0) ) CYCLE
-            IF( il_rho(jp_K) /= 1 )THEN
-               ! I-K plan
-               DO jj=1,tl_mix%t_dim(2)%i_len
-                  CALL interp__2D(tl_mix%d_value(:,jj,:,jl), tl_mix%d_fill, &
-                  &               il_detect(:,jj,:), cd_method,             &
-                  &               il_rho(jp_J), il_rho(jp_K),               &
-                  &               ll_even(1:3:2), ll_discont  )
-               ENDDO
-               IF( ALL(il_detect(:,:,:)==0) ) CYCLE
-               ! J-K plan
-               DO ji=1,tl_mix%t_dim(1)%i_len
-                  CALL interp__2D(tl_mix%d_value(ji,:,:,jl), tl_mix%d_fill, &
-                  &               il_detect(ji,:,:), cd_method,             &
-                  &               il_rho(jp_J), il_rho(jp_K),               &
-                  &               ll_even(2:3), ll_discont )
-               ENDDO
-
-            ENDIF
-            IF( ANY(il_detect(:,:,:)==1) )THEN
-               ! I direction
-               DO jk=1,tl_mix%t_dim(3)%i_len
-                  DO jj=1,tl_mix%t_dim(2)%i_len
-                     CALL interp__1D( tl_mix%d_value(:,jj,jk,jl),    &
-                     &                tl_mix%d_fill,                 &
-                     &                il_detect(:,jj,jk), cd_method, &
-                     &                il_rho(jp_I),                  &
-                     &                ll_even(1), ll_discont )
-                  ENDDO
-               ENDDO
-               IF( ALL(il_detect(:,:,:)==0) ) CYCLE
-               ! J direction
-               DO jk=1,tl_mix%t_dim(3)%i_len
-                  DO ji=1,tl_mix%t_dim(1)%i_len
-                     CALL interp__1D( tl_mix%d_value(ji,:,jk,jl),    &
-                     &                tl_mix%d_fill,                 &
-                     &                il_detect(ji,:,jk), cd_method, &
-                     &                il_rho(jp_J),                  &
-                     &                ll_even(2), ll_discont )
-                  ENDDO
-               ENDDO
-               IF( il_rho(jp_K) /= 1 )THEN
-                  IF( ALL(il_detect(:,:,:)==0) ) CYCLE
-                  ! K direction
-                  DO jj=1,tl_mix%t_dim(2)%i_len
-                     DO ji=1,tl_mix%t_dim(1)%i_len
-                        CALL interp__1D( tl_mix%d_value(ji,jj,:,jl),    &
-                        &                tl_mix%d_fill,                 & 
-                        &                il_detect(ji,jj,:), cd_method, &
-                        &                il_rho(jp_K),                  &
-                        &                ll_even(3), ll_discont  )
-                     ENDDO
-                  ENDDO
-               ENDIF
-            ENDIF
-         ENDIF
-      ENDDO
+      CALL logger_debug("INTERP 2D: interpolation method "//TRIM(cd_method)//&
+      &  " discont "//TRIM(fct_str(ll_discont)) )
+      SELECT CASE(TRIM(cd_method))
+      CASE('cubic')
+         CALL interp_cubic_fill(tl_mix%d_value(:,:,:,:), tl_mix%d_fill, &
+           &                    il_detect(:,:,:),                        &
+           &                    il_rho(:), ll_even(:), ll_discont )
+      CASE('nearest')
+         CALL interp_nearest_fill(tl_mix%d_value(:,:,:,:), &
+              &                   il_detect(:,:,:),         &
+              &                   il_rho(:) )
+      CASE DEFAULT ! linear
+         CALL interp_linear_fill(tl_mix%d_value(:,:,:,:), tl_mix%d_fill, &
+              &                  il_detect(:,:,:),                        &
+              &                  il_rho(:), ll_even(:), ll_discont )
+      END SELECT         
 
       IF( ANY(il_detect(:,:,:)==1) )THEN
@@ -1056,1267 +949,10 @@
       !4- save useful domain (remove offset)
       CALL interp_clean_mixed_grid( tl_mix, td_var, &
-      &                             id_rho(:),      &
-      &                             id_offset(:,:) )      
+      &                             id_rho(:), id_offset(:,:)  )  
 
       ! clean variable structure
+      DEALLOCATE(il_rho)
       CALL var_clean(tl_mix)
 
    END SUBROUTINE interp__fill_value
-   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief
-!   !> This subroutine 
-!   !> 
-!   !> @details 
-!   !>
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in]
-!   !> @param[out] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   SUBROUTINE interp__3D( dd_value,  dd_fill,   &
-!      &                   id_detect, cd_method, &
-!      &                   id_rhoi, id_rhoj, id_rhok, &
-!      &                   ld_even,  ld_discont )
-!      IMPLICIT NONE
-!      ! Argument
-!      REAL(dp)        , DIMENSION(:,:,:), INTENT(INOUT) :: dd_value 
-!      REAL(dp)                          , INTENT(IN   ) :: dd_fill 
-!      INTEGER(I4)     , DIMENSION(:,:,:), INTENT(INOUT) :: id_detect
-!      CHARACTER(LEN=*)                  , INTENT(IN   ) :: cd_method
-!      INTEGER(I4)                       , INTENT(IN   ) :: id_rhoi
-!      INTEGER(I4)                       , INTENT(IN   ) :: id_rhoj
-!      INTEGER(I4)                       , INTENT(IN   ) :: id_rhok
-!      LOGICAL         , DIMENSION(:)    , INTENT(IN   ) :: ld_even
-!      LOGICAL                           , INTENT(IN   ), OPTIONAL :: ld_discont
-!
-!      ! local variable
-!      INTEGER(i4), DIMENSION(3)                  :: il_shape
-!      INTEGER(i4), DIMENSION(3)                  :: il_dim
-!
-!      REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_coarse
-!      REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_dfdx
-!      REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_dfdy
-!      REAL(dp)   , DIMENSION(:,:,:), ALLOCATABLE :: dl_d2fdxy
-!
-!      LOGICAL                                    :: ll_discont
-!
-!      ! loop indices
-!!      INTEGER(i4) :: ji
-!!      INTEGER(i4) :: jj
-!!      INTEGER(i4) :: ii
-!!      INTEGER(i4) :: ij
-!      !----------------------------------------------------------------
-!      ll_discont=.FALSE.
-!      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
-!
-!      il_shape(:)=SHAPE(dd_value)
-!      il_dim(:)=(il_shape(:)-1)/2
-!
-!      ALLOCATE( dl_coarse(il_dim(1),il_dim(2),il_dim(3)) )
-!      ! value on coarse grid
-!      dl_coarse(:,:,:)=dd_value( 1:il_shape(1):id_rhoi, &
-!      &                        1:il_shape(2):id_rhoj, &
-!      &                        1:il_shape(3):id_rhok )
-!      SELECT CASE(TRIM(cd_method))
-!
-!         CASE('cubic')
-!            
-!            ALLOCATE( dl_dfdx(  il_dim(1),il_dim(2),il_dim(3)), &
-!            &         dl_dfdy(  il_dim(1),il_dim(2),il_dim(3)), &
-!            &         dl_d2fdxy(il_dim(1),il_dim(2),il_dim(3)) )
-!
-!!            ! compute derivative on coarse grid
-!!            dl_dfdx(:,:)=extrap_deriv_2D(dl_coarse(:,:,:), dd_fill, 'I')
-!!            dl_dfdy(:,:)=extrap_deriv_2D(dl_coarse(:,:,:), dd_fill, 'J')
-!!
-!!            ! compute cross derivative on coarse grid
-!!            dl_d2fdxy(:,:)=extrap_deriv_2D(dl_dfdx(:,:,:), dd_fill, 'J')
-!!
-!!            DO jj=1,il_shape(2)-1,id_rhoj
-!!               ij=((jj-1)/id_rhoj)+1
-!!               DO ji=1,il_shape(1)-1,id_rhoi
-!!                  ii=((ji-1)/id_rhoi)+1
-!!            
-!!                  IF( ANY(dl_coarse(ii:ii+1,ij:ij+1)==dd_fill ) ) CYCLE
-!!                  ! compute bicubic coefficient
-!!                  dl_coef(:)=interp__2D_cubic_coef(dl_coarse(ii:ii+1,ij:ij+1),&
-!!                  &                                dl_dfdx(  ii:ii+1,ij:ij+1),&
-!!                  &                                dl_dfdy(  ii:ii+1,ij:ij+1),&
-!!                  &                                dl_d2fdxy(ii:ii+1,ij:ij+1) )
-!!
-!!                  ! compute value on detetected point
-!!                  CALL interp__2D_cubic_fill(dl_coef(:), &
-!!                  &                          dd_value( ji:ji+id_rhoi,   &
-!!                  &                                    jj:jj+id_rhoj ), &
-!!                  &                          id_detect(ji:ji+id_rhoi,   &
-!!                  &                                    jj:jj+id_rhoj )  )
-!!
-!!               ENDDO
-!!            ENDDO
-!
-!            DEALLOCATE( dl_dfdx, &
-!            &           dl_dfdy, &
-!            &           dl_d2fdxy )
-!
-!         CASE('nearest')
-!
-!         CASE DEFAULT ! linear 
-!
-!!            DO jj=1,il_shape(2)-1,id_rhoj
-!!               ij=((jj-1)/id_rhoj)+1
-!!               DO ji=1,il_shape(1)-1,id_rhoi
-!!                  ii=((ji-1)/id_rhoi)+1            
-!!
-!!                  IF( ANY(dl_coarse(ii:ii+1,ij:ij+1)==dd_fill ) ) CYCLE
-!!                  ! compute bilinear coefficient
-!!                  dl_coef(:)=interp__2D_linear_coef(dl_coarse(ii:ii+1,ij:ij+1))
-!!
-!!                  ! compute value on detetected point
-!!                  CALL interp__2D_linear_fill(dl_coef(:), &
-!!                  &                          dd_value( ji:ji+id_rhoi,   &
-!!                  &                                    jj:jj+id_rhoj ), &
-!!                  &                          id_detect(ji:ji+id_rhoi,   &
-!!                  &                                    jj:jj+id_rhoj )  )
-!!
-!!               ENDDO
-!!            ENDDO
-!
-!      END SELECT
-!
-!      DEALLOCATE( dl_coarse )
-!
-!   END SUBROUTINE interp__3D
-!   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__2D( dd_value,  dd_fill,   &
-      &                   id_detect, cd_method, &
-      &                   id_rhoi, id_rhoj,     &
-      &                   ld_even,  ld_discont )
-
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)        , DIMENSION(:,:), INTENT(INOUT) :: dd_value 
-      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
-      INTEGER(I4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
-      CHARACTER(LEN=*)                , INTENT(IN   ) :: cd_method
-      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
-      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoj
-      LOGICAL         , DIMENSION(:)  , INTENT(IN   ) :: ld_even
-      LOGICAL                         , INTENT(IN   ), OPTIONAL :: ld_discont
-
-      ! local variable
-      INTEGER(I4)                              :: il_xextra
-      INTEGER(I4)                              :: il_yextra
-      INTEGER(i4), DIMENSION(2)                :: il_shape
-      INTEGER(i4), DIMENSION(2)                :: il_dim
-
-      REAL(dp)                                 :: dl_min 
-      REAL(dp)                                 :: dl_max 
-      REAL(dp)   , DIMENSION(:)  , ALLOCATABLE :: dl_coef
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_coarse
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_tmp
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_dfdx
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_dfdy
-      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_d2fdxy
-
-      LOGICAL                                  :: ll_discont
-      ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jj
-      INTEGER(i4) :: ii
-      INTEGER(i4) :: ij
-
-      !----------------------------------------------------------------
-      ll_discont=.FALSE.
-      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
-
-      CALL logger_debug("INTERP 2D: interpolation method "//TRIM(cd_method)//&
-      &  " discont "//TRIM(fct_str(ll_discont)) )
-
-      il_shape(:)=SHAPE(dd_value)
-
-      ! compute coarse grid dimension
-      il_xextra=id_rhoi-1
-      il_dim(1)=(il_shape(1)+il_xextra)/id_rhoi
-
-      il_yextra=id_rhoj-1
-      il_dim(2)=(il_shape(2)+il_yextra)/id_rhoj
-
-      ALLOCATE( dl_coarse(il_dim(1),il_dim(2)) )
-
-      ! value on coarse grid
-      dl_coarse(:,:)=dd_value( 1:il_shape(1):id_rhoi, &
-      &                        1:il_shape(2):id_rhoj )
-
-      SELECT CASE(TRIM(cd_method))
-
-         CASE('cubic')
-            
-            ALLOCATE( dl_dfdx(  il_dim(1),il_dim(2)), &
-            &         dl_dfdy(  il_dim(1),il_dim(2)), &
-            &         dl_d2fdxy(il_dim(1),il_dim(2)) )
-
-            ! compute derivative on coarse grid
-            dl_dfdx(:,:)=extrap_deriv_2D(dl_coarse(:,:), dd_fill, 'I', ll_discont)
-            dl_dfdy(:,:)=extrap_deriv_2D(dl_coarse(:,:), dd_fill, 'J', ll_discont)
-
-            ! compute cross derivative on coarse grid
-            dl_d2fdxy(:,:)=extrap_deriv_2D(dl_dfdx(:,:), dd_fill, 'J', ll_discont)
-
-            ALLOCATE( dl_tmp(2,2) )
-            ALLOCATE( dl_coef(16) )
-
-            DO jj=1,il_shape(2)-1,id_rhoj
-               ij=((jj-1)/id_rhoj)+1
-               DO ji=1,il_shape(1)-1,id_rhoi
-                  ii=((ji-1)/id_rhoi)+1
-            
-                  IF( ANY(dl_coarse(ii:ii+1,ij:ij+1)==dd_fill) .OR. &
-                  &   ANY(  dl_dfdx(ii:ii+1,ij:ij+1)==dd_fill) .OR. &
-                  &   ANY(  dl_dfdy(ii:ii+1,ij:ij+1)==dd_fill) .OR. &
-                  &   ANY(dl_d2fdxy(ii:ii+1,ij:ij+1)==dd_fill) ) CYCLE
-
-                  dl_tmp(:,:)=dl_coarse(ii:ii+1,ij:ij+1)
-                  IF( ll_discont )THEN
-
-                     dl_min=MINVAL( dl_tmp(:,:), dl_tmp(:,:)/=dd_fill )
-                     dl_max=MAXVAL( dl_tmp(:,:), dl_tmp(:,:)/=dd_fill )
-                     IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                        WHERE( dl_tmp(:,:) < 0_dp ) 
-                           dl_tmp(:,:) = dl_tmp(:,:)+360._dp
-                        END WHERE
-                     ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                        WHERE( dl_tmp(:,:) > 180_dp ) 
-                           dl_tmp(:,:) = dl_tmp(:,:)-180._dp
-                        END WHERE
-                     ENDIF
-                  ENDIF
-
-                  ! compute bicubic coefficient
-                  dl_coef(:)=interp__2D_cubic_coef(dl_tmp(:,:),&
-                  &                                dl_dfdx(   ii:ii+1,ij:ij+1),&
-                  &                                dl_dfdy(   ii:ii+1,ij:ij+1),&
-                  &                                dl_d2fdxy( ii:ii+1,ij:ij+1),&
-                  &                                dd_fill )
-
-                  ! compute value on detetected point
-                  CALL interp__2D_cubic_fill(dd_value( ji:ji+id_rhoi,   &
-                  &                                    jj:jj+id_rhoj ), &
-                  &                          id_detect(ji:ji+id_rhoi,   &
-                  &                                    jj:jj+id_rhoj ), &
-                  &                          dl_coef(:), dd_fill,       &
-                  &                          ld_even(:), id_rhoi, id_rhoj )
-
-                  IF( ll_discont )THEN
-                     WHERE( dd_value( ji:ji+id_rhoi, &
-                        &             jj:jj+id_rhoj ) >= 180._dp .AND. &
-                        &   dd_value( ji:ji+id_rhoi, &
-                        &             jj:jj+id_rhoj ) /= dd_fill )
-                        dd_value( ji:ji+id_rhoi, &
-                        &         jj:jj+id_rhoj ) = &
-                        &           dd_value( ji:ji+id_rhoi, &
-                        &                     jj:jj+id_rhoj ) - 360._dp
-                     END WHERE
-                  ENDIF
-
-               ENDDO
-            ENDDO
-
-            DEALLOCATE(dl_coef)
-            DEALLOCATE(dl_tmp )
-
-            DEALLOCATE(dl_dfdx, &
-            &          dl_dfdy, &
-            &          dl_d2fdxy )
-
-         CASE('nearest') 
-
-            DO jj=1,il_shape(2)-1,id_rhoj
-               ij=((jj-1)/id_rhoj)+1
-               DO ji=1,il_shape(1)-1,id_rhoi
-                  ii=((ji-1)/id_rhoi)+1            
-
-                  ! compute value on detetected point
-                  CALL interp__2D_nearest_fill(dd_value( ji:ji+id_rhoi,   &
-                  &                                      jj:jj+id_rhoj ), &
-                  &                            id_detect(ji:ji+id_rhoi,   &
-                  &                                      jj:jj+id_rhoj )  )
-
-               ENDDO
-            ENDDO
-
-         CASE DEFAULT ! linear 
-
-            ALLOCATE( dl_coef(4)  )
-            ALLOCATE( dl_tmp(2,2) )
-
-            DO jj=1,il_shape(2)-1,id_rhoj
-               ij=((jj-1)/id_rhoj)+1
-               DO ji=1,il_shape(1)-1,id_rhoi
-                  ii=((ji-1)/id_rhoi)+1            
-
-                  IF( ANY(dl_coarse(ii:ii+1,ij:ij+1)==dd_fill ) ) CYCLE
-
-                  dl_tmp(:,:)=dl_coarse(ii:ii+1,ij:ij+1)
-                  IF( ll_discont )THEN
-
-                     dl_min=MINVAL( dl_tmp(:,:), dl_tmp(:,:)/=dd_fill )
-                     dl_max=MAXVAL( dl_tmp(:,:), dl_tmp(:,:)/=dd_fill )
-                     IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                        WHERE( dl_tmp(:,:) < 0_dp ) 
-                           dl_tmp(:,:) = dl_tmp(:,:)+360._dp
-                        END WHERE
-                     ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                        WHERE( dl_tmp(:,:) > 180_dp ) 
-                           dl_tmp(:,:) = dl_tmp(:,:)-180._dp
-                        END WHERE
-                     ENDIF
-                  ENDIF
-
-                  ! compute bilinear coefficient
-                  dl_coef(:)=interp__2D_linear_coef(dl_tmp(:,:), dd_fill)
-
-                  ! compute value on detetected point
-                  CALL interp__2D_linear_fill(dd_value( ji:ji+id_rhoi,   &
-                  &                                     jj:jj+id_rhoj ), &
-                  &                           id_detect(ji:ji+id_rhoi,   &
-                  &                                     jj:jj+id_rhoj ), &
-                  &                           dl_coef(:), dd_fill,       &
-                  &                           ld_even(:), id_rhoi, id_rhoj )
-
-                  IF( ll_discont )THEN
-                     WHERE( dd_value( ji:ji+id_rhoi, &
-                        &             jj:jj+id_rhoj ) >= 180._dp .AND. &
-                        &   dd_value( ji:ji+id_rhoi, &
-                        &             jj:jj+id_rhoj ) /= dd_fill )
-                        dd_value( ji:ji+id_rhoi, &
-                        &         jj:jj+id_rhoj ) = &
-                        &           dd_value( ji:ji+id_rhoi, &
-                        &                     jj:jj+id_rhoj ) - 360._dp
-                     END WHERE
-                  ENDIF
-
-               ENDDO
-            ENDDO
-
-            DEALLOCATE(dl_coef)
-            DEALLOCATE(dl_tmp )
-
-      END SELECT
-
-      DEALLOCATE( dl_coarse )
-
-   END SUBROUTINE interp__2D
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__1D( dd_value,  dd_fill,   &
-      &                   id_detect, cd_method, &
-      &                   id_rhoi,              &
-      &                   ld_even, ld_discont )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)        , DIMENSION(:), INTENT(INOUT) :: dd_value 
-      REAL(dp)                      , INTENT(IN   ) :: dd_fill 
-      INTEGER(I4)     , DIMENSION(:), INTENT(INOUT) :: id_detect
-      CHARACTER(LEN=*)              , INTENT(IN   ) :: cd_method
-      INTEGER(I4)                   , INTENT(IN   ) :: id_rhoi
-      LOGICAL                       , INTENT(IN   ) :: ld_even
-      LOGICAL                       , INTENT(IN   ), OPTIONAL :: ld_discont
-
-      ! local variable
-      INTEGER(i4), DIMENSION(1)              :: il_shape
-      INTEGER(i4), DIMENSION(1)              :: il_dim
-      INTEGER(I4)                            :: il_xextra
-
-      REAL(dp)                               :: dl_min 
-      REAL(dp)                               :: dl_max 
-      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_coarse
-      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_tmp
-      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_dfdx
-
-      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_coef
-
-      LOGICAL                                :: ll_discont
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: ii
-      !----------------------------------------------------------------
-      ll_discont=.FALSE.
-      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
-
-      CALL logger_debug("INTERP 1D: interpolation method "//TRIM(cd_method)//&
-      &  " discont "//TRIM(fct_str(ll_discont)) )
-
-      il_shape(:)=SHAPE(dd_value)
-
-      il_xextra=id_rhoi-1
-      il_dim(1)=(il_shape(1)+il_xextra)/id_rhoi
-
-      ALLOCATE( dl_coarse(il_dim(1)) )
-      ! value on coarse grid
-      dl_coarse(:)=dd_value( 1:il_shape(1):id_rhoi )
-
-      SELECT CASE(TRIM(cd_method))
-
-         CASE('cubic')
-            
-            ALLOCATE( dl_dfdx( il_dim(1)) )
-
-            ! compute derivative on coarse grid
-            dl_dfdx(:)=extrap_deriv_1D(dl_coarse(:), dd_fill, ll_discont)
-
-            ALLOCATE( dl_coef(4))
-            ALLOCATE( dl_tmp(2) )
-
-            DO ji=1,il_shape(1)-1,id_rhoi
-               ii=((ji-1)/id_rhoi)+1
-            
-               IF( ANY( dl_tmp(:)==dd_fill ) .OR. &
-               &   ANY(dl_dfdx(:)==dd_fill ) ) CYCLE
-
-               dl_tmp(:)=dl_coarse(ii:ii+1)
-               IF( ll_discont )THEN
-
-                  dl_min=MINVAL( dl_tmp(:), dl_tmp(:)/=dd_fill )
-                  dl_max=MAXVAL( dl_tmp(:), dl_tmp(:)/=dd_fill )
-                  IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                     WHERE( dl_tmp(:) < 0_dp ) 
-                        dl_tmp(:) = dl_tmp(:)+360._dp
-                     END WHERE
-                  ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                     WHERE( dl_tmp(:) > 180_dp ) 
-                        dl_tmp(:) = dl_tmp(:)-180._dp
-                     END WHERE
-                  ENDIF
-               ENDIF
-
-               ! compute bicubic coefficient
-               dl_coef(:)=interp__1D_cubic_coef(dl_tmp(:),&
-               &                                dl_dfdx(   ii:ii+1), &
-               &                                dd_fill )
-
-               ! compute value on detetected point
-               CALL interp__1D_cubic_fill(dd_value( ji:ji+id_rhoi),&
-               &                          id_detect(ji:ji+id_rhoi),&
-               &                          dl_coef(:), dd_fill,     &
-               &                          ld_even, id_rhoi )
-
-               IF( ll_discont )THEN
-                  WHERE( dd_value( ji:ji+id_rhoi ) >= 180._dp .AND. &
-                     &   dd_value( ji:ji+id_rhoi ) /= dd_fill )
-                     dd_value( ji:ji+id_rhoi ) = &
-                     &           dd_value( ji:ji+id_rhoi ) - 360._dp
-                  END WHERE
-               ENDIF
-
-            ENDDO
-
-            DEALLOCATE(dl_coef)
-            DEALLOCATE(dl_tmp )
-
-         CASE('nearest') 
-
-            DO ji=1,il_shape(1)-1,id_rhoi
-               ii=((ji-1)/id_rhoi)+1            
-
-               ! compute value on detetected point
-               CALL interp__1D_nearest_fill(dd_value( ji:ji+id_rhoi), &
-               &                            id_detect(ji:ji+id_rhoi)  )
-
-            ENDDO
-
-         CASE DEFAULT ! linear 
-
-            ALLOCATE(dl_coef(2))
-            ALLOCATE( dl_tmp(2) )
-
-            DO ji=1,il_shape(1)-1,id_rhoi
-               ii=((ji-1)/id_rhoi)+1            
-
-               IF( ANY(dl_coarse(ii:ii+1)==dd_fill ) ) CYCLE
-
-               dl_tmp(:)=dl_coarse(ii:ii+1)
-               IF( ll_discont )THEN
-
-                  dl_min=MINVAL( dl_tmp(:), dl_tmp(:)/=dd_fill )
-                  dl_max=MAXVAL( dl_tmp(:), dl_tmp(:)/=dd_fill )
-                  IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
-                     WHERE( dl_tmp(:) < 0_dp ) 
-                        dl_tmp(:) = dl_tmp(:)+360._dp
-                     END WHERE
-                  ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
-                     WHERE( dl_tmp(:) > 180_dp ) 
-                        dl_tmp(:) = dl_tmp(:)-180._dp
-                     END WHERE
-                  ENDIF
-               ENDIF
-
-               ! compute bilinear coefficient
-               dl_coef(:)=interp__1D_linear_coef(dl_tmp(:), dd_fill)
-
-               ! compute value on detetected point
-               CALL interp__1D_linear_fill( dd_value( ji:ji+id_rhoi),&
-               &                            id_detect(ji:ji+id_rhoi),&
-               &                            dl_coef(:), dd_fill,     &
-               &                            ld_even, id_rhoi  )
-
-               IF( ll_discont )THEN
-                  WHERE( dd_value( ji:ji+id_rhoi ) >= 180._dp .AND. &
-                     &   dd_value( ji:ji+id_rhoi ) /= dd_fill )
-                     dd_value( ji:ji+id_rhoi ) = &
-                     &           dd_value( ji:ji+id_rhoi ) - 360._dp
-                  END WHERE
-               ENDIF
-
-            ENDDO
-
-            DEALLOCATE(dl_coef)
-
-      END SELECT
-
-      DEALLOCATE( dl_coarse )
-
-   END SUBROUTINE interp__1D
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION interp__2D_cubic_coef( dd_value, &
-      &                            dd_dfdx,  &
-      &                            dd_dfdy,  &
-      &                            dd_d2fdxy,&
-      &                            dd_fill )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_value 
-      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_dfdx  
-      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_dfdy  
-      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_d2fdxy
-      REAL(dp)                , INTENT(IN) :: dd_fill
-
-      ! function
-      REAL(dp), DIMENSION(16) :: interp__2D_cubic_coef
-
-      ! local variable
-      REAL(dp), DIMENSION(16,16), PARAMETER :: dp_matrix = RESHAPE( &
-      & (/ 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,& 
-           0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,& 
-          -3 , 3 , 0 , 0 ,-2 ,-1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,& 
-           2 ,-2 , 0 , 0 , 1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,& 
-           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,& 
-           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 0 , 0 ,& 
-           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,-3 , 3 , 0 , 0 ,-2 ,-1 , 0 , 0 ,& 
-           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 2 ,-2 , 0 , 0 , 1 , 1 , 0 , 0 ,& 
-          -3 , 0 , 3 , 0 , 0 , 0 , 0 , 0 ,-2 , 0 ,-1 , 0 , 0 , 0 , 0 , 0 ,& 
-           0 , 0 , 0 , 0 ,-3 , 0 , 3 , 0 , 0 , 0 , 0 , 0 ,-2 , 0 ,-1 , 0 ,& 
-           9 ,-9 ,-9 , 9 , 6 , 3 ,-6 ,-3 , 6 ,-6 , 3 ,-3 , 4 , 2 , 2 , 1 ,& 
-          -6 , 6 , 6 ,-6 ,-3 ,-3 , 3 , 3 ,-4 , 4 ,-2 , 2 ,-2 ,-2 ,-1 ,-1 ,& 
-           2 , 0 ,-2 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 , 0 , 0 , 0 , 0 ,& 
-           0 , 0 , 0 , 0 , 2 , 0 ,-2 , 0 , 0 , 0 , 0 , 0 , 1 , 0 , 1 , 0 ,& 
-          -6 , 6 , 6 ,-6 ,-4 ,-2 , 4 , 2 ,-3 , 3 ,-3 , 3 ,-2 ,-1 ,-2 ,-1 ,& 
-           4 ,-4 ,-4 , 4 , 2 , 2 ,-2 ,-2 , 2 ,-2 , 2 ,-2 , 1 , 1 , 1 , 1 /), &
-      & (/ 16, 16 /) )
-
-      REAL(dp), DIMENSION(16) :: dl_vect
-
-      !----------------------------------------------------------------
-      ! init
-      interp__2D_cubic_coef(:)=dd_fill
-
-      IF( ANY(SHAPE( dd_value(:,:))/= 2) .OR. &
-      &   ANY(SHAPE(  dd_dfdx(:,:))/= 2) .OR. &
-      &   ANY(SHAPE(  dd_dfdy(:,:))/= 2) .OR. &
-      &   ANY(SHAPE(dd_d2fdxy(:,:))/= 2) )THEN
-   
-         CALL logger_error("INTERP CUBIC COEF: invalid dimension of "//&
-         &              "input tables. shape should be (/2,2/)")
-
-      ELSEIF( ANY( dd_value(:,:) == dd_fill) .OR. &
-      &       ANY(  dd_dfdx(:,:) == dd_fill) .OR. &
-      &       ANY(  dd_dfdy(:,:) == dd_fill) .OR. &
-      &       ANY(dd_d2fdxy(:,:) == dd_fill) )THEN
-      
-         CALL logger_warn("INTERP CUBIC COEF: fill value detected. "//&
-         &  "can not compute coefficient ")
-
-      ELSE
-
-         dl_vect( 1: 4)=PACK(dd_value(:,:),.TRUE. )
-         dl_vect( 5: 8)=PACK(dd_dfdx(:,:),.TRUE. )
-         dl_vect( 9:12)=PACK(dd_dfdy(:,:),.TRUE. )
-         dl_vect(13:16)=PACK(dd_d2fdxy(:,:),.TRUE. )
-
-         interp__2D_cubic_coef(:)=MATMUL(TRANSPOSE(dp_matrix(:,:)),dl_vect(:))
-
-      ENDIF
-   END FUNCTION interp__2D_cubic_coef
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__2D_cubic_fill( dd_value, id_detect, dd_coef, dd_fill, &
-   &                                 ld_even, id_rhoi, id_rhoj )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)        , DIMENSION(:,:), INTENT(INOUT) :: dd_value 
-      INTEGER(i4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
-      REAL(dp)        , DIMENSION(:)  , INTENT(IN   ) :: dd_coef 
-      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
-      LOGICAL         , DIMENSION(:),   INTENT(IN   ) :: ld_even
-      INTEGER(I4)     ,                 INTENT(IN   ) :: id_rhoi
-      INTEGER(I4)     ,                 INTENT(IN   ) :: id_rhoj
-
-      ! local variable
-      INTEGER(i4), DIMENSION(2)  :: il_shape
-
-      REAL(dp)   , DIMENSION(16) :: dl_vect
-      REAL(dp)                   :: dl_dx
-      REAL(dp)                   :: dl_dy
-      REAL(dp)                   :: dl_x
-      REAL(dp)                   :: dl_x2
-      REAL(dp)                   :: dl_x3
-      REAL(dp)                   :: dl_y
-      REAL(dp)                   :: dl_y2
-      REAL(dp)                   :: dl_y3
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jj
-      !----------------------------------------------------------------
-
-      IF( SIZE(dd_coef(:)) /= 16 )THEN
-         CALL logger_error("INTERP CUBIC FILL: invalid dimension of "//&
-         &              "coef table. shape should be (/16/)")
-      ELSEIF( ANY(   dd_coef(:)==dd_fill ) )THEN
-         CALL logger_error("INTERP CUBIC FILL: fill value detected in coef . "//&
-         &              "can not compute interpolation.")
-      ELSE
-
-         il_shape(:)=SHAPE(dd_value(:,:))
-
-         dl_dx=1./REAL(id_rhoi)
-         dl_dy=1./REAL(id_rhoj)
-
-         DO jj=1,il_shape(2)
-
-            IF( ld_even(2) )THEN
-               dl_y=(jj-1)*dl_dy - dl_dy*0.5
-            ELSE ! odd refinement
-               dl_y=(jj-1)*dl_dy
-            ENDIF
-            dl_y2=dl_y*dl_y
-            dl_y3=dl_y2*dl_y
-
-            DO ji=1,il_shape(1)
-               
-               IF(id_detect(ji,jj)==1)THEN
-                  
-                  IF( ld_even(1) )THEN
-                     dl_x=(ji-1)*dl_dx - dl_dx*0.5 
-                  ELSE ! odd refinement
-                     dl_x=(ji-1)*dl_dx 
-                  ENDIF
-                  dl_x2=dl_x*dl_x
-                  dl_x3=dl_x2*dl_x
-
-                  dl_vect(:)=(/1._dp, dl_x      , dl_x2      , dl_x3      , &
-                  &            dl_y , dl_x*dl_y , dl_x2*dl_y , dl_x3*dl_y , &
-                  &            dl_y2, dl_x*dl_y2, dl_x2*dl_y2, dl_x3*dl_y2, &
-                  &            dl_y3, dl_x*dl_y3, dl_x2*dl_y3, dl_x3*dl_y3 /)
-
-                  dd_value(ji,jj)=DOT_PRODUCT(dd_coef(:),dl_vect(:))
-                  id_detect(ji,jj)=0
-
-               ENDIF
-
-            ENDDO
-         ENDDO
-
-      ENDIF
-
-   END SUBROUTINE interp__2D_cubic_fill
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION interp__2D_linear_coef( dd_value, dd_fill )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp), DIMENSION(:,:)  , INTENT(IN) :: dd_value 
-      REAL(dp)                  , INTENT(IN) :: dd_fill 
-
-      ! function
-      REAL(dp), DIMENSION(4) :: interp__2D_linear_coef
-
-      ! local variable
-
-      REAL(dp), DIMENSION(4,4), PARAMETER :: dp_matrix = RESHAPE( &
-      & (/  1 , 0 , 0 , 0 ,& 
-           -1 , 1 , 0 , 0 ,& 
-           -1 , 0 , 1 , 0 ,& 
-            1 ,-1 ,-1 , 1 /), &
-      & (/ 4, 4 /) )
-
-      REAL(dp), DIMENSION(4) :: dl_vect
-
-      !----------------------------------------------------------------
-
-      IF( ANY(SHAPE(dd_value(:,:))/= 2) )THEN
-         CALL logger_error("INTERP LINEAR COEF: invalid dimension of "//&
-         &              "input tables. shape should be (/2,2/)")
-      ELSEIF( ANY(dd_value(:,:)==dd_fill) )THEN
-         CALL logger_error("INTERP LINEAR COEF: fill value detected. "//&
-         &              "can not compute coefficient.")
-      ELSE
-
-         dl_vect( 1: 4)=PACK(dd_value(:,:),.TRUE. )
-
-         interp__2D_linear_coef(:)=MATMUL(TRANSPOSE(dp_matrix(:,:)),dl_vect(:))
-
-      ENDIF
-   END FUNCTION interp__2D_linear_coef
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__2D_linear_fill( dd_value, id_detect, dd_coef, dd_fill, &
-   &                                  ld_even, id_rhoi, id_rhoj )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)        , DIMENSION(:,:), INTENT(INOUT) :: dd_value 
-      INTEGER(i4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
-      REAL(dp)        , DIMENSION(:)  , INTENT(IN   ) :: dd_coef 
-      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
-      LOGICAL         , DIMENSION(:),   INTENT(IN   ) :: ld_even
-      INTEGER(I4)     ,                 INTENT(IN   ) :: id_rhoi
-      INTEGER(I4)     ,                 INTENT(IN   ) :: id_rhoj
-
-      ! local variable
-      INTEGER(i4), DIMENSION(2) :: il_shape
-
-      REAL(dp)   , DIMENSION(4) :: dl_vect
-      REAL(dp)                  :: dl_dx
-      REAL(dp)                  :: dl_dy
-      REAL(dp)                  :: dl_x
-      REAL(dp)                  :: dl_y
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jj
-      !----------------------------------------------------------------
-
-      IF( SIZE(dd_coef(:)) /= 4 )THEN
-         CALL logger_error("INTERP LINEAR FILL: invalid dimension of "//&
-         &              "coef table. shape should be (/4/)")
-      ELSEIF( ANY( dd_coef(:)==dd_fill ) )THEN
-         CALL logger_error("INTERP LINEAR FILL: fill value detected in coef. "//&
-         &              "can not compute interpolation.")
-      ELSE
-
-         il_shape(:)=SHAPE(dd_value(:,:))
-
-         dl_dx=1./REAL(id_rhoi)
-         dl_dy=1./REAL(id_rhoj)
-
-         DO jj=1,il_shape(2)
-
-            IF( ld_even(2) )THEN
-               dl_y=(jj-1)*dl_dy - dl_dy*0.5
-            ELSE ! odd refinement
-               dl_y=(jj-1)*dl_dy
-            ENDIF
-
-            DO ji=1,il_shape(1)
-               
-               IF(id_detect(ji,jj)==1)THEN
-
-                  IF( ld_even(1) )THEN
-                     dl_x=(ji-1)*dl_dx - dl_dx*0.5 
-                  ELSE ! odd refinement
-                     dl_x=(ji-1)*dl_dx 
-                  ENDIF
-
-                  dl_vect(:)=(/1._dp, dl_x, dl_y, dl_x*dl_y /)
-
-                  dd_value(ji,jj)=DOT_PRODUCT(dd_coef(:),dl_vect(:))
-                  id_detect(ji,jj)=0
-
-               ENDIF
-
-            ENDDO
-         ENDDO
-
-      ENDIF
-
-   END SUBROUTINE interp__2D_linear_fill
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__2D_nearest_fill( dd_value, id_detect )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)   , DIMENSION(:,:)  , INTENT(INOUT) :: dd_value 
-      INTEGER(i4), DIMENSION(:,:)  , INTENT(INOUT) :: id_detect
-
-      ! local variable
-      INTEGER(i4), DIMENSION(2) :: il_shape
-
-      INTEGER(i4) :: il_i1
-      INTEGER(i4) :: il_i2
-      INTEGER(i4) :: il_j1
-      INTEGER(i4) :: il_j2
-
-      INTEGER(i4) :: il_half1
-      INTEGER(i4) :: il_half2
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      INTEGER(i4) :: jj
-      !----------------------------------------------------------------
-
-      il_shape(:)=SHAPE(dd_value(:,:))
-
-      il_i1=1
-      il_i2=il_shape(1)
-
-      il_j1=1
-      il_j2=il_shape(2)
-
-      il_half1=CEILING(il_shape(1)*0.5)
-      il_half2=CEILING(il_shape(2)*0.5)
-
-      DO jj=1,il_half2
-
-         DO ji=1,il_half1
-            
-            ! lower left point
-            IF(id_detect(ji,jj)==1)THEN
-
-               dd_value( ji,jj)=dd_value(il_i1,il_j1)
-               id_detect(ji,jj)=0
-
-            ENDIF
-
-            ! lower right point
-            IF(id_detect(il_shape(1)-ji+1,jj)==1)THEN
-
-               dd_value( il_shape(1)-ji+1,jj)=dd_value(il_i2,il_j1)
-               id_detect(il_shape(1)-ji+1,jj)=0
-
-            ENDIF
-
-            ! upper left point
-            IF(id_detect(ji,il_shape(2)-jj+1)==1)THEN
-
-               dd_value( ji,il_shape(2)-jj+1)=dd_value(il_i1,il_j2)
-               id_detect(ji,il_shape(2)-jj+1)=0
-
-            ENDIF            
-
-            ! upper right point
-            IF(id_detect(il_shape(1)-ji+1,il_shape(2)-jj+1)==1)THEN
-
-               dd_value( il_shape(1)-ji+1,il_shape(2)-jj+1)=dd_value(il_i2,il_j2)
-               id_detect(il_shape(1)-ji+1,il_shape(2)-jj+1)=0
-
-            ENDIF            
-
-         ENDDO
-
-      ENDDO
-
-   END SUBROUTINE interp__2D_nearest_fill
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION interp__1D_cubic_coef( dd_value, &
-      &                            dd_dfdx,  &
-      &                            dd_fill )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp), DIMENSION(:)  , INTENT(IN) :: dd_value 
-      REAL(dp), DIMENSION(:)  , INTENT(IN) :: dd_dfdx  
-      REAL(dp)                , INTENT(IN) :: dd_fill  
-
-      ! function
-      REAL(dp), DIMENSION(4) :: interp__1D_cubic_coef
-
-      ! local variable
-
-      REAL(dp), DIMENSION(4,4), PARAMETER :: dp_matrix = RESHAPE( &
-      & (/  1 , 0 , 0 , 0 ,& 
-           -1 , 1 , 0 , 0 ,& 
-           -3 , 3 ,-2 ,-1 ,& 
-            2 ,-2 , 1 , 1  /), &
-      & (/ 4, 4 /) )
-
-      REAL(dp), DIMENSION(4) :: dl_vect
-
-      !----------------------------------------------------------------
-      IF( SIZE(dd_value(:))/= 2 .OR. &
-      &   SIZE(dd_dfdx(:) )/= 2  )THEN
-   
-         CALL logger_error("INTERP CUBIC COEF: invalid dimension of "//&
-         &              "input tables. shape should be (/2,2/)")
-
-      ELSEIF( ANY(dd_value(:)==dd_fill) .OR. &
-      &       ANY( dd_dfdx(:)==dd_fill) )THEN
-         CALL logger_error("INTERP CUBIC COEF: fill value detected. "//&
-         &              "can not compute coefficient.")
-      ELSE
-
-         dl_vect( 1: 2)=PACK(dd_value(:),.TRUE. )
-         dl_vect( 3: 4)=PACK(dd_dfdx(:),.TRUE. )
-
-         interp__1D_cubic_coef(:)=MATMUL(TRANSPOSE(dp_matrix(:,:)),dl_vect(:))
-
-      ENDIF
-
-   END FUNCTION interp__1D_cubic_coef
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__1D_cubic_fill( dd_value, id_detect, dd_coef, dd_fill, &
-   &                                 ld_even, id_rhoi )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)        , DIMENSION(:), INTENT(INOUT) :: dd_value 
-      INTEGER(i4)     , DIMENSION(:), INTENT(INOUT) :: id_detect
-      REAL(dp)        , DIMENSION(:), INTENT(IN   ) :: dd_coef 
-      REAL(dp)                      , INTENT(IN   ) :: dd_fill 
-      LOGICAL         ,               INTENT(IN   ) :: ld_even
-      INTEGER(I4)     ,               INTENT(IN   ) :: id_rhoi
-
-      ! local variable
-      INTEGER(i4), DIMENSION(1)  :: il_shape
-
-      REAL(dp)   , DIMENSION(4) :: dl_vect
-      REAL(dp)                   :: dl_dx
-      REAL(dp)                   :: dl_x
-      REAL(dp)                   :: dl_x2
-      REAL(dp)                   :: dl_x3
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-
-      IF( SIZE(dd_coef(:)) /= 4 )THEN
-         CALL logger_error("INTERP CUBIC FILL: invalid dimension of "//&
-         &              "coef table. shape should be (/4/)")
-      !ELSEIF( ANY(dd_value(:)==dd_fill .AND. id_detect(:)==0 ) .OR. &
-      ELSEIF( ANY( dd_coef(:)==dd_fill ) )THEN
-         CALL logger_error("INTERP CUBIC FILL: fill value detected. "//&
-         &              "can not compute interpolation")
-      ELSE
-
-         il_shape(:)=SHAPE(dd_value(:))
-
-         dl_dx=1./REAL(id_rhoi)
-         
-         DO ji=1,il_shape(1)
-            
-            IF(id_detect(ji)==1)THEN
-
-               IF( ld_even )THEN
-                  dl_x=(ji-1)*dl_dx - dl_dx*0.5 
-               ELSE ! odd refinement
-                  dl_x=(ji-1)*dl_dx 
-               ENDIF
-               dl_x2=dl_x*dl_x
-               dl_x3=dl_x2*dl_x
-
-               dl_vect(:)=(/1._dp, dl_x, dl_x2, dl_x3 /)
-
-               dd_value(ji)=DOT_PRODUCT(dd_coef(:),dl_vect(:))
-               id_detect(ji)=0
-
-            ENDIF
-
-         ENDDO
-
-      ENDIF
-
-   END SUBROUTINE interp__1D_cubic_fill
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION interp__1D_linear_coef( dd_value, dd_fill )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp), DIMENSION(:)  , INTENT(IN) :: dd_value 
-      REAL(dp)                , INTENT(IN) :: dd_fill  
-
-      ! function
-      REAL(dp), DIMENSION(2) :: interp__1D_linear_coef
-
-      ! local variable
-
-      REAL(dp), DIMENSION(2,2), PARAMETER :: dp_matrix = RESHAPE( &
-      & (/  1 , 0 ,& 
-           -1 , 1  /), &
-      &  (/ 2, 2 /) )
-
-      REAL(dp), DIMENSION(2) :: dl_vect
-
-      !----------------------------------------------------------------
-
-      IF( ANY(SHAPE(dd_value(:))/= 2) )THEN
-         CALL logger_error("INTERP LINEAR COEF: invalid dimension of "//&
-         &              "input tables. shape should be (/2/)")
-      ELSEIF( ANY(dd_value(:)==dd_fill) )THEN
-         CALL logger_error("INTERP LINEAR COEF: fill value detected. "//&
-         &              "can not compute coefficient.")
-      ELSE
-         
-         dl_vect( 1: 2)=PACK(dd_value(:),.TRUE. )
-
-         interp__1D_linear_coef(:)=MATMUL(TRANSPOSE(dp_matrix(:,:)),dl_vect(:))
-
-      ENDIF
-
-   END FUNCTION interp__1D_linear_coef
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__1D_linear_fill( dd_value, id_detect, dd_coef, dd_fill, &
-   &                                  ld_even, id_rhoi )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)        , DIMENSION(:), INTENT(INOUT) :: dd_value 
-      INTEGER(i4)     , DIMENSION(:), INTENT(INOUT) :: id_detect
-      REAL(dp)        , DIMENSION(:), INTENT(IN   ) :: dd_coef 
-      REAL(dp)                      , INTENT(IN   ) :: dd_fill 
-      LOGICAL         ,               INTENT(IN   ) :: ld_even
-      INTEGER(I4)     ,               INTENT(IN   ) :: id_rhoi      
-
-      ! local variable
-      INTEGER(i4), DIMENSION(1) :: il_shape
-
-      REAL(dp)   , DIMENSION(2) :: dl_vect
-      REAL(dp)                  :: dl_dx
-      REAL(dp)                  :: dl_x
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-
-      IF( SIZE(dd_coef(:)) /= 2 )THEN
-         CALL logger_error("INTERP LINEAR FILL: invalid dimension of "//&
-         &              "coef table. shape should be (/2/)")
-      !ELSEIF( ANY(dd_value(:)==dd_fill .AND. id_detect(:)==0 ) .OR. &
-      ELSEIF( ANY( dd_coef(:)==dd_fill ) )THEN
-         CALL logger_error("INTERP LINEAR FILL: fill value detected. "//&
-         &              "can not compute interpolation")
-      ELSE
-
-         il_shape(:)=SHAPE(dd_value)
-
-         dl_dx=1./REAL(id_rhoi)
-
-         DO ji=1,il_shape(1)
-            
-            IF(id_detect(ji)==1)THEN
-
-               IF( ld_even )THEN
-                  dl_x=(ji-1)*dl_dx - dl_dx*0.5 
-               ELSE ! odd refinement
-                  dl_x=(ji-1)*dl_dx 
-               ENDIF
-
-               dl_vect(:)=(/1._dp, dl_x /)
-
-               dd_value(ji)=DOT_PRODUCT(dd_coef(:),dl_vect(:))
-               id_detect(ji)=0
-
-            ENDIF
-
-         ENDDO
-
-      ENDIF
-
-   END SUBROUTINE interp__1D_linear_fill
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief
-   !> This subroutine 
-   !> 
-   !> @details 
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in]
-   !> @param[out] 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE interp__1D_nearest_fill( dd_value, id_detect )
-      IMPLICIT NONE
-      ! Argument
-      REAL(dp)   , DIMENSION(:), INTENT(INOUT) :: dd_value 
-      INTEGER(i4), DIMENSION(:), INTENT(INOUT) :: id_detect
-
-      ! local variable
-      INTEGER(i4), DIMENSION(1) :: il_shape
-
-      INTEGER(i4) :: il_i1
-      INTEGER(i4) :: il_i2
-
-      INTEGER(i4) :: il_half1
-      
-      ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-
-      il_shape(:)=SHAPE(dd_value)
-
-      il_i1=1
-      il_i2=il_shape(1)
-
-      il_half1=CEILING(il_shape(1)*0.5)
-      
-      DO ji=1,il_half1
-         
-         ! lower left point
-         IF(id_detect(ji)==1)THEN
-
-            dd_value( ji)=dd_value(il_i1)
-            id_detect(ji)=0
-
-         ENDIF
-
-         ! lower right point
-         IF(id_detect(il_shape(1)-ji+1)==1)THEN
-
-            dd_value( il_shape(1)-ji+1)=dd_value(il_i2)
-            id_detect(il_shape(1)-ji+1)=0
-
-         ENDIF
-
-      ENDDO
-
-   END SUBROUTINE interp__1D_nearest_fill
-   !> @endcode
 END MODULE interp
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_cubic.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_cubic.f90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_cubic.f90	(revision 5075)
@@ -0,0 +1,783 @@
+!----------------------------------------------------------------------
+! NEMO system team, System and Interface for oceanic RElocable Nesting
+!----------------------------------------------------------------------
+!
+! MODULE: interp
+!
+! DESCRIPTION:
+!> @brief 
+!> This module manage cubic interpolation on regular grid.
+!>
+!>
+!> @details
+!> to compute cubic interpolation:<br/>
+!> @code
+!> CALL interp_cubic_fill(dd_value, dd_fill, id_detect, id_rho, ld_even [,ld_discont] )
+!> @endcode
+!>    - dd_value is 2D array of variable value 
+!>    - dd_fill is the FillValue of variable
+!>    - id_detect is 2D array of point to be interpolated (see interp module) 
+!>    - id_rho  is array of refinment factor
+!>    - ld_even indicates even refinment or not 
+!>    - ld_discont indicates longitudinal discontinuity (-180°/180°, 0°/360°) or not
+!>
+!> @author
+!> J.Paul
+! REVISION HISTORY:
+!> @date September, 2014 -Initial version
+!>
+!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+!----------------------------------------------------------------------
+MODULE interp_cubic
+
+   USE netcdf                          ! nf90 library
+   USE global                          ! global variable
+   USE kind                            ! F90 kind parameter
+   USE logger                          ! log file manager
+   USE fct                             ! basic useful function
+   USE extrap                          ! extrapolation manager
+
+   IMPLICIT NONE
+   ! NOTE_avoid_public_variables_if_possible
+
+   ! type and variable
+
+   ! function and subroutine
+   PUBLIC :: interp_cubic_fill  !< compute interpolation using cubic method
+
+   PRIVATE :: interp_cubic__2D           !< compute bicubic interpolation on 2D gid
+   PRIVATE :: interp_cubic__1D           !< compute   cubic interpolation on 1D gid
+   PRIVATE :: interp_cubic__2D_coef      !< compute coefficient for bicubic interpolation
+   PRIVATE :: interp_cubic__2D_fill      !< fill value using bicubic interpolation
+   PRIVATE :: interp_cubic__1D_coef      !< compute coefficient for   cubic interpolation
+   PRIVATE :: interp_cubic__1D_fill      !< fill value using   cubic interpolation
+   PRIVATE :: interp_cubic__get_weight2D !< compute interpoaltion weight for 2D array 
+   PRIVATE :: interp_cubic__get_weight1D !< compute interpoaltion weight for 1D array
+
+CONTAINS   
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute horizontal cubic interpolation on 4D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  2D array of variable value 
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[inout] id_detect 2D array of point to be interpolated 
+   !> @param[in] id_rho       array of refinment factor
+   !> @param[in] ld_even      even refinment or not 
+   !> @param[in] ld_discont   longitudinal discontinuity (-180°/180°, 0°/360°) or not
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_cubic_fill(dd_value, dd_fill, id_detect, &
+   &                            id_rho, ld_even, ld_discont )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:,:,:), INTENT(INOUT) :: dd_value 
+      REAL(dp)                            , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)     , DIMENSION(:,:,:)  , INTENT(INOUT) :: id_detect
+      INTEGER(I4)     , DIMENSION(:)      , INTENT(IN   ) :: id_rho
+      LOGICAL         , DIMENSION(:)      , INTENT(IN   ) :: ld_even
+      LOGICAL                             , INTENT(IN   ), OPTIONAL :: ld_discont
+
+      ! local variable
+      INTEGER(i4), DIMENSION(4)                :: il_shape
+
+      LOGICAL                                  :: ll_discont
+
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_IJ
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_I
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_J
+      
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      INTEGER(i4) :: jk
+      INTEGER(i4) :: jl
+      !----------------------------------------------------------------
+      ll_discont=.FALSE.
+      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
+
+      il_shape(:)=SHAPE(dd_value)
+
+      ! compute vect2D
+      ALLOCATE(dl_weight_IJ(16,((id_rho(jp_I)+1)*(id_rho(jp_J)+1))) )
+      CALL interp_cubic__get_weight2D(dl_weight_IJ(:,:), &
+      &                               id_rho(:), ld_even(:))
+
+      ALLOCATE( dl_weight_I( 4,((id_rho(jp_I)+1)                 )) )
+      ALLOCATE( dl_weight_J( 4,(                 (id_rho(jp_J)+1))) )
+      CALL interp_cubic__get_weight1D(dl_weight_I(:,:), &
+      &                               id_rho(jp_I), ld_even(jp_I))
+      CALL interp_cubic__get_weight1D(dl_weight_J(:,:), &
+      &                               id_rho(jp_J), ld_even(jp_J))
+
+      DO jl=1,il_shape(4)
+         ! loop on vertical level
+         DO jk=1,il_shape(3)
+
+            ! I-J plan
+            CALL interp_cubic__2D(dd_value(:,:,jk,jl), dd_fill, &
+            &                     id_detect(:,:,jk),            &
+            &                     dl_weight_IJ(:,:),            &
+            &                     id_rho(jp_I), id_rho(jp_J),   &
+            &                     ll_discont)            
+            IF( ANY(id_detect(:,:,jk)==1) )THEN
+               ! I direction
+               DO jj=1,il_shape(2)
+                  CALL interp_cubic__1D( dd_value(:,jj,jk,jl), dd_fill, &
+                  &                      id_detect(:,jj,jk),            &
+                  &                      dl_weight_I(:,:),              &
+                  &                      id_rho(jp_I), ll_discont )
+               ENDDO
+               IF( ALL(id_detect(:,:,jk)==0) )THEN
+                  CYCLE
+               ELSE
+                  ! J direction
+                  DO ji=1,il_shape(1)
+                     CALL interp_cubic__1D( dd_value(ji,:,jk,jl), dd_fill, &
+                     &                      id_detect(ji,:,jk),            &
+                     &                      dl_weight_J(:,:),              &
+                     &                      id_rho(jp_J), ll_discont )
+                  ENDDO
+               ENDIF
+            ENDIF
+
+         ENDDO
+      ENDDO
+
+      DEALLOCATE(dl_weight_IJ)
+      DEALLOCATE(dl_weight_I)
+      DEALLOCATE(dl_weight_J)
+
+   END SUBROUTINE interp_cubic_fill
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute cubic interpolation on 2D array of value. 
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  2D array of variable value 
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[inout] id_detect 2D array of point to be interpolated 
+   !> @param[in] id_rhoi      refinment factor in i-direction
+   !> @param[in] id_rhoj      refinment factor in j-direction
+   !> @param[in] id_rhok      refinment factor in k-direction
+   !> @param[in] ld_even      even refinment or not 
+   !> @param[in] ld_discont   longitudinal discontinuity (-180°/180°, 0°/360°) or not
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_cubic__2D( dd_value,  dd_fill,   &
+      &                         id_detect,            &
+      &                         dd_weight,            &
+      &                         id_rhoi, id_rhoj,     &
+      &                         ld_discont )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:), INTENT(INOUT) :: dd_value 
+      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight 
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoj
+      LOGICAL                         , INTENT(IN   ) :: ld_discont
+
+      ! local variable
+      INTEGER(I4)                              :: il_xextra
+      INTEGER(I4)                              :: il_yextra
+      INTEGER(i4), DIMENSION(2)                :: il_shape
+      INTEGER(i4), DIMENSION(2)                :: il_dim
+
+      REAL(dp)                                 :: dl_min 
+      REAL(dp)                                 :: dl_max 
+      REAL(dp)   , DIMENSION(:)  , ALLOCATABLE :: dl_coef
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_coarse
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_tmp
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_dfdx
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_dfdy
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_d2fdxy
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      INTEGER(i4) :: ii
+      INTEGER(i4) :: ij
+
+      !----------------------------------------------------------------
+
+      IF( ANY(id_detect(:,:)==1) )THEN
+         il_shape(:)=SHAPE(dd_value)
+
+         ! compute coarse grid dimension
+         il_xextra=id_rhoi-1
+         il_dim(1)=(il_shape(1)+il_xextra)/id_rhoi
+
+         il_yextra=id_rhoj-1
+         il_dim(2)=(il_shape(2)+il_yextra)/id_rhoj
+
+         ALLOCATE( dl_coarse(il_dim(1),il_dim(2)) )
+
+         ! value on coarse grid
+         dl_coarse(:,:)=dd_value( 1:il_shape(1):id_rhoi, &
+         &                        1:il_shape(2):id_rhoj )
+
+         ALLOCATE( dl_dfdx(  il_dim(1),il_dim(2)), &
+         &         dl_dfdy(  il_dim(1),il_dim(2)), &
+         &         dl_d2fdxy(il_dim(1),il_dim(2)) )
+
+         ! compute derivative on coarse grid
+         dl_dfdx(:,:)=extrap_deriv_2D(dl_coarse(:,:), dd_fill, 'I', ld_discont)
+         dl_dfdy(:,:)=extrap_deriv_2D(dl_coarse(:,:), dd_fill, 'J', ld_discont)
+
+         ! compute cross derivative on coarse grid
+         dl_d2fdxy(:,:)=extrap_deriv_2D(dl_dfdx(:,:), dd_fill, 'J', ld_discont)
+
+         ALLOCATE( dl_tmp(2,2) )
+         ALLOCATE( dl_coef(16) )
+
+         DO jj=1,il_shape(2)-1,id_rhoj
+            ij=((jj-1)/id_rhoj)+1
+            DO ji=1,il_shape(1)-1,id_rhoi
+               ii=((ji-1)/id_rhoi)+1
+         
+               ! check if point to be interpolated
+               IF( ALL(id_detect(ji:ji+id_rhoi,   &
+               &                 jj:jj+id_rhoj)==0) ) CYCLE
+               ! check data needed to interpolate
+               IF( ANY(dl_coarse(ii:ii+1,ij:ij+1)==dd_fill) .OR. &
+               &   ANY(  dl_dfdx(ii:ii+1,ij:ij+1)==dd_fill) .OR. &
+               &   ANY(  dl_dfdy(ii:ii+1,ij:ij+1)==dd_fill) .OR. &
+               &   ANY(dl_d2fdxy(ii:ii+1,ij:ij+1)==dd_fill) ) CYCLE
+
+               dl_tmp(:,:)=dl_coarse(ii:ii+1,ij:ij+1)
+               ! check longitude discontinuity
+               IF( ld_discont )THEN
+
+                  dl_min=MINVAL( dl_tmp(:,:), dl_tmp(:,:)/=dd_fill )
+                  dl_max=MAXVAL( dl_tmp(:,:), dl_tmp(:,:)/=dd_fill )
+                  IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                     WHERE( dl_tmp(:,:) < 0_dp ) 
+                        dl_tmp(:,:) = dl_tmp(:,:)+360._dp
+                     END WHERE
+                  ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                     WHERE( dl_tmp(:,:) > 180_dp ) 
+                        dl_tmp(:,:) = dl_tmp(:,:)-180._dp
+                     END WHERE
+                  ENDIF
+
+               ENDIF
+
+               ! compute bicubic coefficient
+               dl_coef(:)=interp_cubic__2D_coef(dl_tmp(:,:),&
+               &                                dl_dfdx(  ii:ii+1,ij:ij+1),&
+               &                                dl_dfdy(  ii:ii+1,ij:ij+1),&
+               &                                dl_d2fdxy(ii:ii+1,ij:ij+1),&
+               &                                dd_fill )
+
+               ! compute value on detetected point
+               CALL interp_cubic__2D_fill(dd_value( ji:ji+id_rhoi,   &
+               &                                    jj:jj+id_rhoj ), &
+               &                          id_detect(ji:ji+id_rhoi,   &
+               &                                    jj:jj+id_rhoj ), &
+               &                          dd_weight(:,:), dl_coef(:),&
+               &                          dd_fill, id_rhoi, id_rhoj )
+
+               IF( ld_discont )THEN
+                  WHERE( dd_value( ji:ji+id_rhoi, &
+                     &             jj:jj+id_rhoj ) >= 180._dp .AND. &
+                     &   dd_value( ji:ji+id_rhoi, &
+                     &             jj:jj+id_rhoj ) /= dd_fill )
+                     dd_value( ji:ji+id_rhoi, &
+                     &         jj:jj+id_rhoj ) = &
+                     &           dd_value( ji:ji+id_rhoi, &
+                     &                     jj:jj+id_rhoj ) - 360._dp
+                  END WHERE
+               ENDIF
+
+            ENDDO
+         ENDDO
+
+         DEALLOCATE(dl_coef)
+         DEALLOCATE(dl_tmp )
+
+         DEALLOCATE(dl_dfdx, &
+         &          dl_dfdy, &
+         &          dl_d2fdxy )
+
+         DEALLOCATE( dl_coarse )
+      ENDIF
+
+   END SUBROUTINE interp_cubic__2D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute cubic interpolation on 1D array of value. 
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  1D array of variable value 
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[inout] id_detect 1D array of point to be interpolated 
+   !> @param[in] id_rhoi      refinment factor
+   !> @param[in] ld_even      even refinment or not 
+   !> @param[in] ld_discont   longitudinal discontinuity (-180°/180°, 0°/360°) or not
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_cubic__1D( dd_value,  dd_fill,   &
+      &                         id_detect,            &
+      &                         dd_weight,            &
+      &                         id_rhoi,              &
+      &                         ld_discont )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:)  , INTENT(INOUT) :: dd_value 
+      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)     , DIMENSION(:)  , INTENT(INOUT) :: id_detect
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight 
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
+      LOGICAL                         , INTENT(IN   ) :: ld_discont
+
+      ! local variable
+      INTEGER(I4)                            :: il_xextra
+      INTEGER(i4), DIMENSION(1)              :: il_shape
+      INTEGER(i4), DIMENSION(1)              :: il_dim
+
+      REAL(dp)                               :: dl_min 
+      REAL(dp)                               :: dl_max 
+      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_coef
+      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_coarse
+      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_tmp
+      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_dfdx
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: ii
+
+      !----------------------------------------------------------------
+
+      IF( ANY(id_detect(:)==1) )THEN
+         il_shape(:)=SHAPE(dd_value)
+
+         ! compute coarse grid dimension
+         il_xextra=id_rhoi-1
+         il_dim(1)=(il_shape(1)+il_xextra)/id_rhoi
+
+         ALLOCATE( dl_coarse(il_dim(1)) )
+
+         ! value on coarse grid
+         dl_coarse(:)=dd_value( 1:il_shape(1):id_rhoi )
+
+         ALLOCATE( dl_dfdx(il_dim(1)) )
+
+         ! compute derivative on coarse grid
+         dl_dfdx(:)=extrap_deriv_1D(dl_coarse(:), dd_fill, ld_discont)
+
+         ALLOCATE( dl_tmp(2) )
+         ALLOCATE( dl_coef(4) )
+
+         DO ji=1,il_shape(1)-1,id_rhoi
+            ii=((ji-1)/id_rhoi)+1
+         
+            ! check if point to be interpolated
+            IF( ALL(id_detect(ji:ji+id_rhoi)==0) ) CYCLE
+            ! check data needed to interpolate
+            IF( ANY(dl_coarse(ii:ii+1)==dd_fill) .OR. &
+            &   ANY(  dl_dfdx(ii:ii+1)==dd_fill) ) CYCLE
+            ! check longitude discontinuity
+            dl_tmp(:)=dl_coarse(ii:ii+1)
+            IF( ld_discont )THEN
+
+               dl_min=MINVAL( dl_tmp(:), dl_tmp(:)/=dd_fill )
+               dl_max=MAXVAL( dl_tmp(:), dl_tmp(:)/=dd_fill )
+               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                  WHERE( dl_tmp(:) < 0_dp ) 
+                     dl_tmp(:) = dl_tmp(:)+360._dp
+                  END WHERE
+               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                  WHERE( dl_tmp(:) > 180_dp ) 
+                     dl_tmp(:) = dl_tmp(:)-180._dp
+                  END WHERE
+               ENDIF
+
+            ENDIF
+
+            ! compute bicubic coefficient
+            dl_coef(:)=interp_cubic__1D_coef(dl_tmp(:),       &
+            &                                dl_dfdx(ii:ii+1),&
+            &                                dd_fill )
+
+            ! compute value on detetected point
+            CALL interp_cubic__1D_fill( dd_value( ji:ji+id_rhoi ), &
+            &                           id_detect(ji:ji+id_rhoi ), &
+            &                           dd_weight(:,:), dl_coef(:),  &
+            &                           dd_fill, id_rhoi )
+
+            IF( ld_discont )THEN
+               WHERE( dd_value( ji:ji+id_rhoi ) >= 180._dp .AND. &
+                  &   dd_value( ji:ji+id_rhoi ) /= dd_fill )
+                  dd_value(ji:ji+id_rhoi) = dd_value(ji:ji+id_rhoi) - 360._dp
+               END WHERE
+            ENDIF
+
+         ENDDO
+
+         DEALLOCATE(dl_coef)
+         DEALLOCATE(dl_tmp )
+
+         DEALLOCATE(dl_dfdx )
+         DEALLOCATE( dl_coarse )
+      ENDIF
+
+   END SUBROUTINE interp_cubic__1D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute 2D array of coefficient for cubic interpolation.
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] dd_value  2D array of value
+   !> @param[in] dd_dfdx   2D array of first derivative in i-direction 
+   !> @param[in] dd_dfdy   2D array of first derivative in j-direction
+   !> @param[in] dd_d2fdxy 2D array of cross derivative in i-j-direction
+   !> @param[in] dd_fill   FillValue of variable
+   !-------------------------------------------------------------------
+   FUNCTION interp_cubic__2D_coef( dd_value, &
+      &                            dd_dfdx,  &
+      &                            dd_dfdy,  &
+      &                            dd_d2fdxy,&
+      &                            dd_fill )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_value 
+      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_dfdx  
+      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_dfdy  
+      REAL(dp), DIMENSION(:,:), INTENT(IN) :: dd_d2fdxy
+      REAL(dp)                , INTENT(IN) :: dd_fill
+
+      ! function
+      REAL(dp), DIMENSION(16) :: interp_cubic__2D_coef
+
+      ! local variable
+      REAL(dp), DIMENSION(16,16), PARAMETER :: dl_matrix = RESHAPE( &
+      & (/ 1 , 0 ,-3 , 2 , 0 , 0 , 0 , 0 ,-3 , 0 , 9 ,-6 , 2 , 0 ,-6 , 4 ,& 
+           0 , 0 , 3 ,-2 , 0 , 0 , 0 , 0 , 0 , 0 ,-9 , 6 , 0 , 0 , 6 ,-4 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 3 , 0 ,-9 , 6 ,-2 , 0 , 6 ,-4 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 9 ,-6 , 0 , 0 ,-6 , 4 ,& 
+           0 , 1 ,-2 , 1 , 0 , 0 , 0 , 0 , 0 ,-3 , 6 ,-3 , 0 , 2 ,-4 , 2 ,& 
+           0 , 0 ,-1 , 1 , 0 , 0 , 0 , 0 , 0 , 0 , 3 ,-3 , 0 , 0 ,-2 , 2 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 3 ,-6 , 3 , 0 ,-2 , 4 ,-2 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,-3 , 3 , 0 , 0 , 2 ,-2 ,& 
+           0 , 0 , 0 , 0 , 1 , 0 ,-3 , 2 ,-2 , 0 , 6 ,-4 , 1 , 0 ,-3 , 2 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 3 ,-2 , 0 , 0 ,-6 , 4 , 0 , 0 , 3 ,-2 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,-1 , 0 , 3 ,-2 , 1 , 0 ,-3 , 2 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,-3 , 2 , 0 , 0 , 3 ,-2 ,& 
+           0 , 0 , 0 , 0 , 0 , 1 ,-2 , 1 , 0 ,-2 , 4 ,-2 , 0 , 1 ,-2 , 1 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 ,-1 , 1 , 0 , 0 , 2 ,-2 , 0 , 0 ,-1 , 1 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,-1 , 2 ,-1 , 0 , 1 ,-2 , 1 ,& 
+           0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 1 ,-1 , 0 , 0 ,-1 , 1 /), &
+      & (/ 16, 16 /) )
+
+      REAL(dp), DIMENSION(16) :: dl_vect
+
+      !----------------------------------------------------------------
+      ! init
+      interp_cubic__2D_coef(:)=dd_fill
+
+      dl_vect( 1: 4)=PACK(dd_value(:,:),.TRUE. )
+      dl_vect( 5: 8)=PACK(dd_dfdx(:,:),.TRUE. )
+      dl_vect( 9:12)=PACK(dd_dfdy(:,:),.TRUE. )
+      dl_vect(13:16)=PACK(dd_d2fdxy(:,:),.TRUE. )
+
+      interp_cubic__2D_coef(:)=MATMUL(dl_matrix(:,:),dl_vect(:))
+
+   END FUNCTION interp_cubic__2D_coef
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute cubic interpolation of a 2D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  2D array of mixed grid value
+   !> @param[inout] id_detect 2D array of point to be interpolated
+   !> @param[in] dd_coef      2D array of coefficient
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] ld_even      even refinment or not
+   !> @param[in] id_rhoi      refinement factor in i-direction 
+   !> @param[in] id_rhoj      refinement factor in j-direction
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_cubic__2D_fill( dd_value, id_detect, &
+   &                                 dd_weight, dd_coef,  &
+   &                                 dd_fill, id_rhoi, id_rhoj )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:), INTENT(INOUT) :: dd_value 
+      INTEGER(i4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight
+      REAL(dp)        , DIMENSION(:)  , INTENT(IN   ) :: dd_coef 
+      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)     ,                 INTENT(IN   ) :: id_rhoi
+      INTEGER(I4)     ,                 INTENT(IN   ) :: id_rhoj
+
+      ! local variable
+
+      ! loop indices
+      INTEGER(i4) :: ii
+
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+
+      IF( ANY( dd_coef(:)==dd_fill ) )THEN
+         CALL logger_error("INTERP CUBIC FILL: fill value detected in coef . "//&
+         &              "can not compute interpolation.")
+      ELSE
+
+         ii=0
+         DO jj=1,id_rhoj+1
+            DO ji=1,id_rhoi+1
+              
+               ii=ii+1
+               IF(id_detect(ji,jj)==1)THEN
+                  
+                  dd_value(ji,jj)=DOT_PRODUCT(dd_coef(:),dd_weight(:,ii))
+                  id_detect(ji,jj)=0
+
+               ENDIF
+
+            ENDDO
+         ENDDO
+
+      ENDIF
+
+   END SUBROUTINE interp_cubic__2D_fill
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute 1D array of coefficient for cubic interpolation. 
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] dd_value  1D array of value
+   !> @param[in] dd_dfdx   1D array of first derivative 
+   !> @param[in] dd_fill   FillValue of variable
+   !-------------------------------------------------------------------
+   FUNCTION interp_cubic__1D_coef( dd_value, &
+      &                            dd_dfdx,  &
+      &                            dd_fill )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:)  , INTENT(IN) :: dd_value 
+      REAL(dp), DIMENSION(:)  , INTENT(IN) :: dd_dfdx  
+      REAL(dp)                , INTENT(IN) :: dd_fill  
+
+      ! function
+      REAL(dp), DIMENSION(4) :: interp_cubic__1D_coef
+
+      ! local variable
+      REAL(dp), DIMENSION(4,4), PARAMETER :: dl_matrix = RESHAPE( &
+      & (/  1 ,-1 ,-3 , 2 ,& 
+            0 , 1 , 3 ,-2 ,& 
+            0 , 0 ,-2 , 1 ,& 
+            0 , 0 ,-1 , 1  /), &
+      & (/ 4, 4 /) )      
+
+      REAL(dp), DIMENSION(4) :: dl_vect
+
+      !----------------------------------------------------------------
+      ! init
+      interp_cubic__1D_coef(:)=dd_fill
+
+      dl_vect( 1: 2)=PACK(dd_value(:),.TRUE. )
+      dl_vect( 3: 4)=PACK(dd_dfdx(:),.TRUE. )
+
+      interp_cubic__1D_coef(:)=MATMUL(dl_matrix(:,:),dl_vect(:))
+
+   END FUNCTION interp_cubic__1D_coef
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute cubic interpolation of a 1D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  1D array of mixed grid value
+   !> @param[inout] id_detect 1D array of point to be interpolated
+   !> @param[in] dd_coef      1D array of coefficient
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] ld_even      even refinment or not
+   !> @param[in] id_rho       refinement factor 
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_cubic__1D_fill( dd_value, id_detect, &
+   &                                 dd_weight, dd_coef,  &
+   &                                 dd_fill, id_rhoi )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:)  , INTENT(INOUT) :: dd_value 
+      INTEGER(i4)     , DIMENSION(:)  , INTENT(INOUT) :: id_detect
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight 
+      REAL(dp)        , DIMENSION(4)  , INTENT(IN   ) :: dd_coef 
+      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
+
+      ! local variable
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      IF( ANY( dd_coef(:)==dd_fill ) )THEN
+         CALL logger_error("INTERP CUBIC FILL: fill value detected. "//&
+         &              "can not compute interpolation")
+      ELSE
+
+         DO ji=1,id_rhoi+1
+            
+            IF(id_detect(ji)==1)THEN
+
+               dd_value(ji)=DOT_PRODUCT(dd_coef(:),dd_weight(:,ji))
+               id_detect(ji)=0
+
+            ENDIF
+
+         ENDDO
+
+      ENDIF
+
+   END SUBROUTINE interp_cubic__1D_fill
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute interpoaltion weight for 2D array. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] dd_weight interpolation weight of 2D array
+   !> @param[in] ld_even   even refinment or not
+   !> @param[in] id_rho    refinement factor 
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_cubic__get_weight2D(dd_weight, &
+   &                                     id_rho, ld_even)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:,:), INTENT(INOUT) :: dd_weight
+      INTEGER(I4), DIMENSION(:)  , INTENT(IN   ) :: id_rho
+      LOGICAL    , DIMENSION(:)  , INTENT(IN   ) :: ld_even
+
+      ! local variable
+      REAL(dp)                  :: dl_dx
+      REAL(dp)                  :: dl_x      
+      REAL(dp)                  :: dl_x2
+      REAL(dp)                  :: dl_x3
+      REAL(dp)                  :: dl_dy
+      REAL(dp)                  :: dl_y      
+      REAL(dp)                  :: dl_y2
+      REAL(dp)                  :: dl_y3
+      
+      ! loop indices
+      INTEGER(i4) :: ii 
+
+      INTEGER(i4) :: ji 
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+      
+      IF( ld_even(jp_I) )THEN
+         dl_dx=1./REAL(id_rho(jp_I)-1)
+      ELSE ! odd refinement
+         dl_dx=1./REAL(id_rho(jp_I))
+      ENDIF
+
+      IF( ld_even(jp_J) )THEN
+         dl_dy=1./REAL(id_rho(jp_J)-1)
+      ELSE ! odd refinement
+         dl_dy=1./REAL(id_rho(jp_J))
+      ENDIF
+
+      ii=0
+      DO jj=1,id_rho(jp_J)+1
+
+         IF( ld_even(jp_J) )THEN
+            dl_y=(jj-1)*dl_dy - dl_dy*0.5 
+         ELSE ! odd refinement
+            dl_y=(jj-1)*dl_dy 
+         ENDIF
+         dl_y2=dl_y*dl_y
+         dl_y3=dl_y2*dl_y
+
+         DO ji=1,id_rho(jp_I)+1
+
+            ! iter
+            ii=ii+1
+
+            IF( ld_even(jp_I) )THEN
+               dl_x=(ji-1)*dl_dx - dl_dx*0.5 
+            ELSE ! odd refinement
+               dl_x=(ji-1)*dl_dx 
+            ENDIF
+            dl_x2=dl_x*dl_x
+            dl_x3=dl_x2*dl_x
+
+            dd_weight(:,ii)=(/1._dp, dl_x      , dl_x2      , dl_x3      , &
+            &                 dl_y , dl_x*dl_y , dl_x2*dl_y , dl_x3*dl_y , &
+            &                 dl_y2, dl_x*dl_y2, dl_x2*dl_y2, dl_x3*dl_y2, &
+            &                 dl_y3, dl_x*dl_y3, dl_x2*dl_y3, dl_x3*dl_y3 /)
+
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE interp_cubic__get_weight2D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute interpoaltion weight for 1D array. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] dd_weight interpolation weight of 1D array
+   !> @param[in] ld_even   even refinment or not
+   !> @param[in] id_rho    refinement factor 
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_cubic__get_weight1D(dd_weight, &
+   &                                     id_rho, ld_even)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:,:), INTENT(INOUT) :: dd_weight
+      INTEGER(I4)                , INTENT(IN   ) :: id_rho
+      LOGICAL                    , INTENT(IN   ) :: ld_even
+      ! local variable
+      REAL(dp)                  :: dl_dx
+      REAL(dp)                  :: dl_x      
+      REAL(dp)                  :: dl_x2
+      REAL(dp)                  :: dl_x3
+      ! loop indices
+      INTEGER(i4) :: ji   
+      !----------------------------------------------------------------
+      
+      IF( ld_even )THEN
+         dl_dx=1./REAL(id_rho-1)
+      ELSE ! odd refinement
+         dl_dx=1./REAL(id_rho)
+      ENDIF
+
+      DO ji=1,id_rho+1
+         IF( ld_even )THEN
+            dl_x=(ji-1)*dl_dx - dl_dx*0.5 
+         ELSE ! odd refinement
+            dl_x=(ji-1)*dl_dx 
+         ENDIF
+         dl_x2=dl_x*dl_x
+         dl_x3=dl_x2*dl_x
+
+         dd_weight(:,ji)=(/1._dp, dl_x, dl_x2, dl_x3 /)
+      ENDDO
+
+   END SUBROUTINE interp_cubic__get_weight1D
+END MODULE interp_cubic
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_linear.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_linear.f90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_linear.f90	(revision 5075)
@@ -0,0 +1,701 @@
+!----------------------------------------------------------------------
+! NEMO system team, System and Interface for oceanic RElocable Nesting
+!----------------------------------------------------------------------
+!
+! MODULE: interp
+!
+! DESCRIPTION:
+!> @brief 
+!> This module manage linear interpolation on regular grid.
+!>
+!> @details
+!> to compute linear interpolation:<br/>
+!> @code
+!> CALL interp_linear_fill(dd_value, dd_fill, id_detect, id_rho, ld_even [,ld_discont] )
+!> @endcode
+!>    - dd_value is 2D array of variable value 
+!>    - dd_fill is the FillValue of variable
+!>    - id_detect is 2D array of point to be interpolated (see interp module) 
+!>    - id_rho  is array of refinment factor
+!>    - ld_even indicates even refinment or not 
+!>    - ld_discont indicates longitudinal discontinuity (-180°/180°, 0°/360°) or not
+!>
+!> @author
+!> J.Paul
+! REVISION HISTORY:
+!> @date September, 2014 -Initial version
+!>
+!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+!----------------------------------------------------------------------
+
+MODULE interp_linear
+
+   USE netcdf                          ! nf90 library
+   USE global                          ! global variable
+   USE kind                            ! F90 kind parameter
+   USE logger                          ! log file manager
+   USE fct                             ! basic useful function
+   USE extrap                          ! extrapolation manager
+
+   IMPLICIT NONE
+   ! NOTE_avoid_public_variables_if_possible
+
+   ! type and variable
+
+   ! function and subroutine
+   PUBLIC :: interp_linear_fill  !< compute interpolation using linear method
+
+   PRIVATE :: interp_linear__2D           !< compute bilinear interpolation on 2D gid
+   PRIVATE :: interp_linear__1D           !< compute   linear interpolation on 1D gid
+   PRIVATE :: interp_linear__2D_coef      !< compute coefficient for bilinear interpolation
+   PRIVATE :: interp_linear__2D_fill      !< fill value using bilinear interpolation
+   PRIVATE :: interp_linear__1D_coef      !< compute coefficient for   linear interpolation
+   PRIVATE :: interp_linear__1D_fill      !< fill value using   linear interpolation
+   PRIVATE :: interp_linear__get_weight2D !< compute interpoaltion weight for 2D array.
+   PRIVATE :: interp_linear__get_weight1D !< compute interpoaltion weight for 1D array.
+
+CONTAINS   
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute horizontal linear interpolation on 4D array of value. 
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  2D array of variable value 
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[inout] id_detect 2D array of point to be interpolated 
+   !> @param[in] id_rho       array of refinment factor
+   !> @param[in] ld_even      even refinment or not 
+   !> @param[in] ld_discont   longitudinal discontinuity (-180°/180°, 0°/360°) or not
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_linear_fill(dd_value, dd_fill, id_detect, &
+   &                             id_rho, ld_even, ld_discont )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:,:,:), INTENT(INOUT) :: dd_value 
+      REAL(dp)                            , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)     , DIMENSION(:,:,:)  , INTENT(INOUT) :: id_detect
+      INTEGER(I4)     , DIMENSION(:)      , INTENT(IN   ) :: id_rho
+      LOGICAL         , DIMENSION(:)      , INTENT(IN   ) :: ld_even
+      LOGICAL                             , INTENT(IN   ), OPTIONAL :: ld_discont
+
+      ! local variable
+      INTEGER(i4), DIMENSION(4)                :: il_shape
+
+      LOGICAL                                  :: ll_discont
+      
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_IJ
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_I
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_weight_J
+      
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      INTEGER(i4) :: jk
+      INTEGER(i4) :: jl
+      !----------------------------------------------------------------
+      ll_discont=.FALSE.
+      IF( PRESENT(ld_discont) ) ll_discont=ld_discont
+
+      il_shape(:)=SHAPE(dd_value)
+
+      ! compute vect2D
+      ALLOCATE(dl_weight_IJ(16,((id_rho(jp_I)+1)*(id_rho(jp_J)+1))) )
+      CALL interp_linear__get_weight2D(dl_weight_IJ(:,:), &
+      &                               id_rho(:), ld_even(:))
+
+      ALLOCATE( dl_weight_I( 4,((id_rho(jp_I)+1)                 )) )
+      ALLOCATE( dl_weight_J( 4,(                 (id_rho(jp_J)+1))) )
+      CALL interp_linear__get_weight1D(dl_weight_I(:,:), &
+      &                               id_rho(jp_I), ld_even(jp_I))
+      CALL interp_linear__get_weight1D(dl_weight_J(:,:), &
+      &                               id_rho(jp_J), ld_even(jp_J))
+
+      DO jl=1,il_shape(4)
+         ! loop on vertical level
+         DO jk=1,il_shape(3)
+
+            ! I-J plan
+            CALL interp_linear__2D(dd_value(:,:,jk,jl), dd_fill,&
+            &                     id_detect(:,:,jk),            &
+            &                     dl_weight_IJ(:,:),            &
+            &                     id_rho(jp_I), id_rho(jp_J),   &
+            &                     ll_discont)            
+            IF( ANY(id_detect(:,:,jk)==1) )THEN
+               ! I direction
+               DO jj=1,il_shape(2)
+                  CALL interp_linear__1D( dd_value(:,jj,jk,jl), dd_fill,&
+                  &                       id_detect(:,jj,jk),           &
+                  &                       dl_weight_I(:,:),             &
+                  &                       id_rho(jp_I), ll_discont )
+               ENDDO
+               IF( ALL(id_detect(:,:,jk)==0) )THEN
+                  CYCLE
+               ELSE
+                  ! J direction
+                  DO ji=1,il_shape(1)
+                     CALL interp_linear__1D( dd_value(ji,:,jk,jl), dd_fill,&
+                     &                       id_detect(ji,:,jk),           &
+                     &                       dl_weight_J(:,:),             &
+                     &                       id_rho(jp_J), ll_discont )
+                  ENDDO
+               ENDIF
+            ENDIF
+
+         ENDDO
+      ENDDO
+
+      DEALLOCATE(dl_weight_IJ)
+      DEALLOCATE(dl_weight_I)
+      DEALLOCATE(dl_weight_J)
+      
+   END SUBROUTINE interp_linear_fill
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute linear interpolation on 2D array of value. 
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  2D array of variable value 
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[inout] id_detect 2D array of point to be interpolated 
+   !> @param[in] id_rhoi      refinment factor in i-direction
+   !> @param[in] id_rhoj      refinment factor in j-direction
+   !> @param[in] id_rhok      refinment factor in k-direction
+   !> @param[in] ld_even      even refinment or not 
+   !> @param[in] ld_discont   longitudinal discontinuity (-180°/180°, 0°/360°) or not
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_linear__2D( dd_value,  dd_fill,   &
+      &                          id_detect,            &
+      &                          dd_weight,            &
+      &                          id_rhoi, id_rhoj,     &
+      &                          ld_discont )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:), INTENT(INOUT) :: dd_value 
+      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoj
+      LOGICAL                         , INTENT(IN   ) :: ld_discont
+
+      ! local variable
+      INTEGER(I4)                              :: il_xextra
+      INTEGER(I4)                              :: il_yextra
+      INTEGER(i4), DIMENSION(2)                :: il_shape
+      INTEGER(i4), DIMENSION(2)                :: il_dim
+
+      REAL(dp)                                 :: dl_min 
+      REAL(dp)                                 :: dl_max 
+      REAL(dp)   , DIMENSION(:)  , ALLOCATABLE :: dl_coef
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_coarse
+      REAL(dp)   , DIMENSION(:,:), ALLOCATABLE :: dl_tmp
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      INTEGER(i4) :: ii
+      INTEGER(i4) :: ij
+
+      !----------------------------------------------------------------
+
+      IF( ANY(id_detect(:,:)==1) )THEN
+         il_shape(:)=SHAPE(dd_value)
+
+         ! compute coarse grid dimension
+         il_xextra=id_rhoi-1
+         il_dim(1)=(il_shape(1)+il_xextra)/id_rhoi
+
+         il_yextra=id_rhoj-1
+         il_dim(2)=(il_shape(2)+il_yextra)/id_rhoj
+
+         ALLOCATE( dl_coarse(il_dim(1),il_dim(2)) )
+
+         ! value on coarse grid
+         dl_coarse(:,:)=dd_value( 1:il_shape(1):id_rhoi, &
+         &                        1:il_shape(2):id_rhoj )
+
+         ALLOCATE( dl_tmp(2,2) )
+         ALLOCATE( dl_coef(4) )
+
+         DO jj=1,il_shape(2)-1,id_rhoj
+            ij=((jj-1)/id_rhoj)+1
+            DO ji=1,il_shape(1)-1,id_rhoi
+               ii=((ji-1)/id_rhoi)+1
+         
+               ! check if point to be interpolated
+               IF( ALL(id_detect(ji:ji+id_rhoi,   &
+               &                 jj:jj+id_rhoj)==0) ) CYCLE
+               ! check data to needed to interpolate
+               IF( ANY(dl_coarse(ii:ii+1,ij:ij+1)==dd_fill) ) CYCLE
+               ! check longitude discontinuity
+               dl_tmp(:,:)=dl_coarse(ii:ii+1,ij:ij+1)
+               IF( ld_discont )THEN
+
+                  dl_min=MINVAL( dl_tmp(:,:), dl_tmp(:,:)/=dd_fill )
+                  dl_max=MAXVAL( dl_tmp(:,:), dl_tmp(:,:)/=dd_fill )
+                  IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                     WHERE( dl_tmp(:,:) < 0_dp ) 
+                        dl_tmp(:,:) = dl_tmp(:,:)+360._dp
+                     END WHERE
+                  ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                     WHERE( dl_tmp(:,:) > 180_dp ) 
+                        dl_tmp(:,:) = dl_tmp(:,:)-180._dp
+                     END WHERE
+                  ENDIF
+
+               ENDIF
+
+               ! compute bilinear coefficient
+               dl_coef(:)=interp_linear__2D_coef(dl_tmp(:,:),&
+               &                                 dd_fill )
+
+               ! compute value on detetected point
+               CALL interp_linear__2D_fill(dd_value( ji:ji+id_rhoi,   &
+               &                                     jj:jj+id_rhoj ), &
+               &                           id_detect(ji:ji+id_rhoi,   &
+               &                                     jj:jj+id_rhoj ), &
+               &                           dd_weight(:,:), dl_coef(:),&
+               &                           dd_fill, id_rhoi, id_rhoj )
+
+               IF( ld_discont )THEN
+                  WHERE( dd_value( ji:ji+id_rhoi, &
+                     &             jj:jj+id_rhoj ) >= 180._dp .AND. &
+                     &   dd_value( ji:ji+id_rhoi, &
+                     &             jj:jj+id_rhoj ) /= dd_fill )
+                     dd_value( ji:ji+id_rhoi, &
+                     &         jj:jj+id_rhoj ) = &
+                     &           dd_value( ji:ji+id_rhoi, &
+                     &                     jj:jj+id_rhoj ) - 360._dp
+                  END WHERE
+               ENDIF
+
+            ENDDO
+         ENDDO
+
+         DEALLOCATE(dl_coef)
+         DEALLOCATE(dl_tmp )
+
+         DEALLOCATE( dl_coarse )
+      ENDIF
+
+   END SUBROUTINE interp_linear__2D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute linear interpolation on 1D array of value. 
+   !> 
+   !> @details 
+   !>
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  1D array of variable value 
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[inout] id_detect 1D array of point to be interpolated 
+   !> @param[in] id_rhoi      refinment factor
+   !> @param[in] ld_even      even refinment or not 
+   !> @param[in] ld_discont   longitudinal discontinuity (-180°/180°, 0°/360°) or not
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_linear__1D( dd_value,  dd_fill,   &
+      &                          id_detect,            &
+      &                          dd_weight,            &
+      &                          id_rhoi,              &
+      &                          ld_discont )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:)  , INTENT(INOUT) :: dd_value 
+      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)     , DIMENSION(:)  , INTENT(INOUT) :: id_detect
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
+      LOGICAL                         , INTENT(IN   ) :: ld_discont
+
+      ! local variable
+      INTEGER(I4)                            :: il_xextra
+      INTEGER(i4), DIMENSION(1)              :: il_shape
+      INTEGER(i4), DIMENSION(1)              :: il_dim
+
+      REAL(dp)                               :: dl_min 
+      REAL(dp)                               :: dl_max 
+      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_coef
+      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_coarse
+      REAL(dp)   , DIMENSION(:), ALLOCATABLE :: dl_tmp
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: ii
+
+      !----------------------------------------------------------------
+
+      IF( ANY(id_detect(:)==1) )THEN
+         il_shape(:)=SHAPE(dd_value)
+
+         ! compute coarse grid dimension
+         il_xextra=id_rhoi-1
+         il_dim(1)=(il_shape(1)+il_xextra)/id_rhoi
+
+         ALLOCATE( dl_coarse(il_dim(1)) )
+
+         ! value on coarse grid
+         dl_coarse(:)=dd_value( 1:il_shape(1):id_rhoi )
+
+         ALLOCATE( dl_tmp(2) )
+         ALLOCATE( dl_coef(4) )
+
+         DO ji=1,il_shape(1)-1,id_rhoi
+            ii=((ji-1)/id_rhoi)+1
+         
+            ! check if point to be interpolated
+            IF( ALL(id_detect(ji:ji+id_rhoi)==0) ) CYCLE
+            ! check data needed to interpolate
+            IF( ANY(dl_coarse(ii:ii+1)==dd_fill) ) CYCLE
+            ! check longitude discontinuity
+            dl_tmp(:)=dl_coarse(ii:ii+1)
+            IF( ld_discont )THEN
+
+               dl_min=MINVAL( dl_tmp(:), dl_tmp(:)/=dd_fill )
+               dl_max=MAXVAL( dl_tmp(:), dl_tmp(:)/=dd_fill )
+               IF( dl_min < -170_dp .AND. dl_max > 170_dp )THEN
+                  WHERE( dl_tmp(:) < 0_dp ) 
+                     dl_tmp(:) = dl_tmp(:)+360._dp
+                  END WHERE
+               ELSEIF( dl_min < 10_dp .AND. dl_max > 350_dp )THEN
+                  WHERE( dl_tmp(:) > 180_dp ) 
+                     dl_tmp(:) = dl_tmp(:)-180._dp
+                  END WHERE
+               ENDIF
+
+            ENDIF
+
+            ! compute bilinear coefficient
+            dl_coef(:)=interp_linear__1D_coef(dl_tmp(:),       &
+            &                                 dd_fill )
+
+            ! compute value on detetected point
+            CALL interp_linear__1D_fill( dd_value( ji:ji+id_rhoi ), &
+            &                            id_detect(ji:ji+id_rhoi ), &
+            &                            dd_weight(:,:), dl_coef(:),&
+            &                            dd_fill, id_rhoi )
+
+            IF( ld_discont )THEN
+               WHERE( dd_value( ji:ji+id_rhoi ) >= 180._dp .AND. &
+                  &   dd_value( ji:ji+id_rhoi ) /= dd_fill )
+                  dd_value(ji:ji+id_rhoi) = dd_value(ji:ji+id_rhoi) - 360._dp
+               END WHERE
+            ENDIF
+
+         ENDDO
+
+         DEALLOCATE(dl_coef)
+         DEALLOCATE(dl_tmp )
+
+         DEALLOCATE( dl_coarse )
+      ENDIF
+
+   END SUBROUTINE interp_linear__1D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute 2D array of coefficient for linear interpolation. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] dd_value  2D array of value
+   !> @param[in] dd_fill   FillValue of variable
+   !-------------------------------------------------------------------
+   FUNCTION interp_linear__2D_coef( dd_value, dd_fill )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:,:)  , INTENT(IN) :: dd_value 
+      REAL(dp)                  , INTENT(IN) :: dd_fill 
+
+      ! function
+      REAL(dp), DIMENSION(4) :: interp_linear__2D_coef
+
+      ! local variable
+      REAL(dp), DIMENSION(4,4), PARAMETER :: dl_matrix = RESHAPE( &
+      & (/  1 ,-1 ,-1 , 1 ,& 
+            0 , 1 , 0 ,-1 ,& 
+            0 , 0 , 1 ,-1 ,& 
+            0 , 0 , 0 , 1 /), &
+      & (/ 4, 4 /) )
+
+      REAL(dp), DIMENSION(4) :: dl_vect
+
+      !----------------------------------------------------------------
+      ! init
+      interp_linear__2D_coef(:)=dd_fill
+
+      dl_vect( 1: 4)=PACK(dd_value(:,:),.TRUE. )
+      interp_linear__2D_coef(:)=MATMUL(dl_matrix(:,:),dl_vect(:))
+
+   END FUNCTION interp_linear__2D_coef
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute linear interpolation of a 2D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !> 
+   !> @param[inout] dd_value  2D array of mixed grid value
+   !> @param[inout] id_detect 2D array of point to be interpolated
+   !> @param[in] dd_coef      2D array of coefficient
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] ld_even      even refinment or not
+   !> @param[in] id_rhoi      refinement factor in i-direction 
+   !> @param[in] id_rhoj      refinement factor in j-direction
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_linear__2D_fill( dd_value, id_detect, &
+   &                                  dd_weight, dd_coef,  &
+   &                                  dd_fill, id_rhoi, id_rhoj )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:), INTENT(INOUT) :: dd_value 
+      INTEGER(i4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight
+      REAL(dp)        , DIMENSION(:)  , INTENT(IN   ) :: dd_coef 
+      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)     ,                 INTENT(IN   ) :: id_rhoi
+      INTEGER(I4)     ,                 INTENT(IN   ) :: id_rhoj
+
+      ! local variable
+
+      ! loop indices
+      INTEGER(i4) :: ii
+
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+
+         IF( ANY( dd_coef(:)==dd_fill ) )THEN
+            CALL logger_error("INTERP LINEAR FILL: fill value detected in coef. "//&
+            &              "can not compute interpolation.")
+         ELSE
+
+            ii=0
+            DO jj=1,id_rhoj+1
+               DO ji=1,id_rhoi+1
+
+                  ii=ii+1
+                  IF(id_detect(ji,jj)==1)THEN
+
+                     dd_value(ji,jj)=DOT_PRODUCT(dd_coef(:),dd_weight(:,ii))
+                     id_detect(ji,jj)=0
+
+                  ENDIF
+
+               ENDDO
+            ENDDO
+
+         ENDIF
+
+   END SUBROUTINE interp_linear__2D_fill
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute 1D array of coefficient for linear interpolation. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] dd_value  1D array of value
+   !> @param[in] dd_fill   FillValue of variable
+   !-------------------------------------------------------------------
+   FUNCTION interp_linear__1D_coef( dd_value, dd_fill )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp), DIMENSION(:)  , INTENT(IN) :: dd_value 
+      REAL(dp)                , INTENT(IN) :: dd_fill  
+
+      ! function
+      REAL(dp), DIMENSION(2) :: interp_linear__1D_coef
+
+      ! local variable
+      REAL(dp), DIMENSION(2,2), PARAMETER :: dl_matrix = RESHAPE( &
+      & (/  1 ,-1 ,& 
+            0 , 1  /), &
+      &  (/ 2, 2 /) )
+
+      REAL(dp), DIMENSION(2) :: dl_vect
+
+      !----------------------------------------------------------------
+      ! init
+      interp_linear__1D_coef(:)=dd_fill
+
+      dl_vect( 1: 2)=PACK(dd_value(:),.TRUE. )
+      interp_linear__1D_coef(:)=MATMUL(dl_matrix(:,:),dl_vect(:))
+
+   END FUNCTION interp_linear__1D_coef
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute linear interpolation of a 1D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !> 
+   !> @param[inout] dd_value  1D array of mixed grid value
+   !> @param[inout] id_detect 1D array of point to be interpolated
+   !> @param[in] dd_coef      1D array of coefficient
+   !> @param[in] dd_fill      FillValue of variable
+   !> @param[in] ld_even      even refinment or not
+   !> @param[in] id_rho       refinement factor
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_linear__1D_fill( dd_value, id_detect, &
+   &                                  dd_weight, dd_coef,  &
+   &                                  dd_fill, id_rho )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:)  , INTENT(INOUT) :: dd_value 
+      INTEGER(i4)     , DIMENSION(:)  , INTENT(INOUT) :: id_detect
+      REAL(dp)        , DIMENSION(:,:), INTENT(IN   ) :: dd_weight
+      REAL(dp)        , DIMENSION(:)  , INTENT(IN   ) :: dd_coef 
+      REAL(dp)                        , INTENT(IN   ) :: dd_fill 
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rho      
+
+      ! local variable
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      IF( ANY( dd_coef(:)==dd_fill ) )THEN
+         CALL logger_error("INTERP LINEAR FILL: fill value detected. "//&
+         &              "can not compute interpolation")
+      ELSE
+
+         DO ji=1,id_rho+1
+            
+            IF(id_detect(ji)==1)THEN
+
+               dd_value(ji)=DOT_PRODUCT(dd_coef(:),dd_weight(:,ji))
+               id_detect(ji)=0
+
+            ENDIF
+
+         ENDDO
+
+      ENDIF
+
+   END SUBROUTINE interp_linear__1D_fill
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute interpoaltion weight for 2D array. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] dd_weight interpolation weight of 2D array
+   !> @param[in] ld_even   even refinment or not
+   !> @param[in] id_rho    refinement factor 
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_linear__get_weight2D(dd_weight, &
+   &                                     id_rho, ld_even)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:,:), INTENT(INOUT) :: dd_weight
+      INTEGER(I4), DIMENSION(:)  , INTENT(IN   ) :: id_rho
+      LOGICAL    , DIMENSION(:)  , INTENT(IN   ) :: ld_even
+      ! local variable
+      REAL(dp)                  :: dl_dx
+      REAL(dp)                  :: dl_x      
+      REAL(dp)                  :: dl_dy
+      REAL(dp)                  :: dl_y      
+      
+      ! loop indices
+      INTEGER(i4) :: ii 
+
+      INTEGER(i4) :: ji 
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+      
+      IF( ld_even(jp_I) )THEN
+         dl_dx=1./REAL(id_rho(jp_I)-1)
+      ELSE ! odd refinement
+         dl_dx=1./REAL(id_rho(jp_I))
+      ENDIF
+
+      IF( ld_even(jp_J) )THEN
+         dl_dy=1./REAL(id_rho(jp_J)-1)
+      ELSE ! odd refinement
+         dl_dy=1./REAL(id_rho(jp_J))
+      ENDIF
+
+      ii=0
+      DO jj=1,id_rho(jp_J)+1
+
+         IF( ld_even(jp_J) )THEN
+            dl_y=(jj-1)*dl_dy - dl_dy*0.5 
+         ELSE ! odd refinement
+            dl_y=(jj-1)*dl_dy 
+         ENDIF
+
+         DO ji=1,id_rho(jp_I)+1
+
+            ! iter
+            ii=ii+1
+
+            IF( ld_even(jp_I) )THEN
+               dl_x=(ji-1)*dl_dx - dl_dx*0.5 
+            ELSE ! odd refinement
+               dl_x=(ji-1)*dl_dx 
+            ENDIF
+
+            dd_weight(:,ii)=(/1._dp, dl_x, dl_y, dl_x*dl_y /)
+
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE interp_linear__get_weight2D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute interpoaltion weight for 1D array. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] dd_weight interpolation weight of 1D array
+   !> @param[in] ld_even   even refinment or not
+   !> @param[in] id_rho    refinement factor 
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_linear__get_weight1D(dd_weight, &
+   &                                     id_rho, ld_even)
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:,:), INTENT(INOUT) :: dd_weight
+      INTEGER(I4)                , INTENT(IN   ) :: id_rho
+      LOGICAL                    , INTENT(IN   ) :: ld_even
+
+      ! local variable
+      REAL(dp)                  :: dl_dx
+      REAL(dp)                  :: dl_x      
+
+      ! loop indices
+      INTEGER(i4) :: ji   
+      !----------------------------------------------------------------
+      
+      IF( ld_even )THEN
+         dl_dx=1./REAL(id_rho-1)
+      ELSE ! odd refinement
+         dl_dx=1./REAL(id_rho)
+      ENDIF
+
+      DO ji=1,id_rho+1
+         IF( ld_even )THEN
+            dl_x=(ji-1)*dl_dx - dl_dx*0.5 
+         ELSE ! odd refinement
+            dl_x=(ji-1)*dl_dx 
+         ENDIF
+
+         dd_weight(:,ji)=(/1._dp, dl_x /)
+      ENDDO
+
+   END SUBROUTINE interp_linear__get_weight1D
+END MODULE interp_linear
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_nearest.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_nearest.f90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/interp_nearest.f90	(revision 5075)
@@ -0,0 +1,353 @@
+!----------------------------------------------------------------------
+! NEMO system team, System and Interface for oceanic RElocable Nesting
+!----------------------------------------------------------------------
+!
+! MODULE: interp
+!
+! DESCRIPTION:
+!> @brief 
+!> This module manage nearest interpolation on regular grid.
+!>
+!> @details
+!> to compute nearest interpolation:<br/>
+!> @code
+!> CALL interp_nearest_fill(dd_value, dd_fill, id_detect, id_rho, ld_even [,ld_discont] )
+!> @endcode
+!>    - dd_value is 2D array of variable value 
+!>    - dd_fill is the FillValue of variable
+!>    - id_detect is 2D array of point to be interpolated (see interp module) 
+!>    - id_rho  is array of refinment factor
+!>    - ld_even indicates even refinment or not 
+!>    - ld_discont indicates longitudinal discontinuity (-180°/180°, 0°/360°) or not
+!>
+!> @author
+!> J.Paul
+! REVISION HISTORY:
+!> @date September, 2014 -Initial version
+!>
+!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+!----------------------------------------------------------------------
+MODULE interp_nearest
+
+   USE netcdf                          ! nf90 library
+   USE global                          ! global variable
+   USE kind                            ! F90 kind parameter
+   USE logger                          ! log file manager
+   USE fct                             ! basic useful function
+
+   IMPLICIT NONE
+   ! NOTE_avoid_public_variables_if_possible
+
+   ! type and variable
+
+   ! function and subroutine
+   PUBLIC :: interp_nearest_fill  !< compute interpolation using nearest method
+
+   PRIVATE :: interp_nearest__2D       !< compute binearest interpolation on 2D gid
+   PRIVATE :: interp_nearest__1D       !< compute   nearest interpolation on 1D gid
+   PRIVATE :: interp_nearest__2D_fill  !< fill value using binearest interpolation
+   PRIVATE :: interp_nearest__1D_fill  !< fill value using   nearest interpolation
+
+CONTAINS   
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute horizontal nearest interpolation on 4D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  2D array of variable value 
+   !> @param[inout] id_detect 2D array of point to be interpolated 
+   !> @param[in]    id_rho    array of refinment factor
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_nearest_fill(dd_value, id_detect, id_rho )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:,:,:), INTENT(INOUT) :: dd_value 
+      INTEGER(I4)     , DIMENSION(:,:,:)  , INTENT(INOUT) :: id_detect
+      INTEGER(I4)     , DIMENSION(:)      , INTENT(IN   ) :: id_rho
+
+      ! local variable
+      INTEGER(i4), DIMENSION(4)                :: il_shape
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      INTEGER(i4) :: jk
+      INTEGER(i4) :: jl
+      !----------------------------------------------------------------
+
+      il_shape(:)=SHAPE(dd_value)
+
+      DO jl=1,il_shape(4)
+         ! loop on vertical level
+         DO jk=1,il_shape(3)
+
+            ! I-J plan
+            CALL interp_nearest__2D(dd_value(:,:,jk,jl),&
+            &                       id_detect(:,:,jk),  &
+            &                       id_rho(jp_I), id_rho(jp_J) )            
+            IF( ANY(id_detect(:,:,jk)==1) )THEN
+               ! I direction
+               DO jj=1,il_shape(2)
+                  CALL interp_nearest__1D( dd_value(:,jj,jk,jl),&
+                  &                        id_detect(:,jj,jk),  &
+                  &                        id_rho(jp_I) )
+               ENDDO
+               IF( ALL(id_detect(:,:,jk)==0) )THEN
+                  CYCLE
+               ELSE
+                  ! J direction
+                  DO ji=1,il_shape(1)
+                     CALL interp_nearest__1D( dd_value(ji,:,jk,jl),&
+                     &                        id_detect(ji,:,jk),  &
+                     &                        id_rho(jp_J) )
+                  ENDDO
+               ENDIF
+            ENDIF
+
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE interp_nearest_fill
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute nearest interpolation on 2D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  2D array of variable value 
+   !> @param[inout] id_detect 2D array of point to be interpolated 
+   !> @param[in] id_rhoi      refinment factor in i-direction
+   !> @param[in] id_rhoj      refinment factor in j-direction
+   !> @param[in] id_rhok      refinment factor in k-direction
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_nearest__2D( dd_value, id_detect, &
+      &                           id_rhoi, id_rhoj )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:,:), INTENT(INOUT) :: dd_value 
+      INTEGER(I4)     , DIMENSION(:,:), INTENT(INOUT) :: id_detect
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoi
+      INTEGER(I4)                     , INTENT(IN   ) :: id_rhoj
+
+      ! local variable
+      INTEGER(i4), DIMENSION(2)                :: il_shape
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+
+      !----------------------------------------------------------------
+
+      IF( ANY(id_detect(:,:)==1) )THEN
+
+         il_shape(:)=SHAPE(dd_value)
+
+         DO jj=1,il_shape(2)-1,id_rhoj
+            DO ji=1,il_shape(1)-1,id_rhoi
+         
+               ! check if point to be interpolated
+               IF( ALL(id_detect(ji:ji+id_rhoi,   &
+               &                 jj:jj+id_rhoj)==0) ) CYCLE
+
+               ! compute value on detetected point
+               CALL interp_nearest__2D_fill(dd_value( ji:ji+id_rhoi,   &
+               &                                      jj:jj+id_rhoj ), &
+               &                            id_detect(ji:ji+id_rhoi,   &
+               &                                      jj:jj+id_rhoj ) )
+
+            ENDDO
+         ENDDO
+
+      ENDIF
+
+   END SUBROUTINE interp_nearest__2D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute nearest interpolation on 1D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  1D array of variable value 
+   !> @param[inout] id_detect 1D array of point to be interpolated 
+   !> @param[in]    id_rhoi   refinment factor
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_nearest__1D( dd_value,  id_detect, &
+      &                           id_rhoi )
+
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)        , DIMENSION(:), INTENT(INOUT) :: dd_value 
+      INTEGER(I4)     , DIMENSION(:), INTENT(INOUT) :: id_detect
+      INTEGER(I4)                   , INTENT(IN   ) :: id_rhoi
+
+      ! local variable
+      INTEGER(i4), DIMENSION(1)              :: il_shape
+
+      ! loop indices
+      INTEGER(i4) :: ji
+
+      !----------------------------------------------------------------
+
+      IF( ANY(id_detect(:)==1) )THEN
+         il_shape(:)=SHAPE(dd_value)
+
+         DO ji=1,il_shape(1)-1,id_rhoi
+         
+            ! check if point to be interpolated
+            IF( ALL(id_detect(ji:ji+id_rhoi)==0) ) CYCLE
+
+            ! compute value on detetected point
+            CALL interp_nearest__1D_fill( dd_value( ji:ji+id_rhoi ), &
+            &                             id_detect(ji:ji+id_rhoi ) )
+
+         ENDDO
+
+      ENDIF
+
+   END SUBROUTINE interp_nearest__1D
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute nearest interpolation of a 2D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  2D array of mixed grid value
+   !> @param[inout] id_detect 2D array of point to be interpolated
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_nearest__2D_fill( dd_value, id_detect )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:,:)  , INTENT(INOUT) :: dd_value 
+      INTEGER(i4), DIMENSION(:,:)  , INTENT(INOUT) :: id_detect
+
+      ! local variable
+      INTEGER(i4), DIMENSION(2) :: il_shape
+
+      INTEGER(i4) :: il_i1
+      INTEGER(i4) :: il_i2
+      INTEGER(i4) :: il_j1
+      INTEGER(i4) :: il_j2
+
+      INTEGER(i4) :: il_half1
+      INTEGER(i4) :: il_half2
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+
+      il_shape(:)=SHAPE(dd_value(:,:))
+
+      il_i1=1
+      il_i2=il_shape(1)
+
+      il_j1=1
+      il_j2=il_shape(2)
+
+      il_half1=CEILING(il_shape(1)*0.5)
+      il_half2=CEILING(il_shape(2)*0.5)
+
+      DO jj=1,il_half2
+
+         DO ji=1,il_half1
+            
+            ! lower left point
+            IF(id_detect(ji,jj)==1)THEN
+
+               dd_value( ji,jj)=dd_value(il_i1,il_j1)
+               id_detect(ji,jj)=0
+
+            ENDIF
+
+            ! lower right point
+            IF(id_detect(il_shape(1)-ji+1,jj)==1)THEN
+
+               dd_value( il_shape(1)-ji+1,jj)=dd_value(il_i2,il_j1)
+               id_detect(il_shape(1)-ji+1,jj)=0
+
+            ENDIF
+
+            ! upper left point
+            IF(id_detect(ji,il_shape(2)-jj+1)==1)THEN
+
+               dd_value( ji,il_shape(2)-jj+1)=dd_value(il_i1,il_j2)
+               id_detect(ji,il_shape(2)-jj+1)=0
+
+            ENDIF            
+
+            ! upper right point
+            IF(id_detect(il_shape(1)-ji+1,il_shape(2)-jj+1)==1)THEN
+
+               dd_value( il_shape(1)-ji+1,il_shape(2)-jj+1)=dd_value(il_i2,il_j2)
+               id_detect(il_shape(1)-ji+1,il_shape(2)-jj+1)=0
+
+            ENDIF            
+
+         ENDDO
+
+      ENDDO
+
+   END SUBROUTINE interp_nearest__2D_fill
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine compute nearest interpolation of a 1D array of value. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[inout] dd_value  1D array of mixed grid value
+   !> @param[inout] id_detect 1D array of point to be interpolated
+   !-------------------------------------------------------------------
+   SUBROUTINE interp_nearest__1D_fill( dd_value, id_detect )
+      IMPLICIT NONE
+      ! Argument
+      REAL(dp)   , DIMENSION(:), INTENT(INOUT) :: dd_value 
+      INTEGER(i4), DIMENSION(:), INTENT(INOUT) :: id_detect
+
+      ! local variable
+      INTEGER(i4), DIMENSION(1) :: il_shape
+
+      INTEGER(i4) :: il_i1
+      INTEGER(i4) :: il_i2
+
+      INTEGER(i4) :: il_half1
+      
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      il_shape(:)=SHAPE(dd_value)
+
+      il_i1=1
+      il_i2=il_shape(1)
+
+      il_half1=CEILING(il_shape(1)*0.5)
+      
+      DO ji=1,il_half1
+         
+         ! lower left point
+         IF(id_detect(ji)==1)THEN
+
+            dd_value( ji)=dd_value(il_i1)
+            id_detect(ji)=0
+
+         ENDIF
+
+         ! lower right point
+         IF(id_detect(il_shape(1)-ji+1)==1)THEN
+
+            dd_value( il_shape(1)-ji+1)=dd_value(il_i2)
+            id_detect(il_shape(1)-ji+1)=0
+
+         ENDIF
+
+      ENDDO
+
+   END SUBROUTINE interp_nearest__1D_fill
+END MODULE interp_nearest
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom.f90	(revision 5075)
@@ -6,67 +6,93 @@
 !
 ! DESCRIPTION:
-!> @brief Input/Output manager :  Library to read input files<br/>
+!> @brief Input/Output manager :  Library to read input files
 !>
 !> @details
+!>    to open file:<br/>
+!> @code
+!>    CALL iom_open(td_file)
+!> @endcode
+!>       - td_file is file structure
+!>
+!>    to create file:<br/>
+!> @code
+!>    CALL iom_create(td_file)
+!> @endcode
+!>       - td_file is file structure
 !> 
-!>    to open file:<br/>
-!>    CALL iom_open(td_file)
-!>       - td_file is file structure
-!>
 !>    to write in file:<br/>
+!> @code
 !>    CALL  iom_write_file(td_file)
+!> @endcode
 !>
 !>    to close file:<br/>
+!> @code
 !>    CALL iom_close(tl_file)
+!> @endcode
 !>
 !>    to read one dimension in file:<br/>
-!>    tl_dim = iom_read_dim(tl_file, id_dimid)<br/>
+!> @code
+!>    tl_dim = iom_read_dim(tl_file, id_dimid)
+!> @endcode
 !>    or<br/>
-!>    tl_dim = iom_read_dim(tl_file, cd_name)<br/>
+!> @code
+!>    tl_dim = iom_read_dim(tl_file, cd_name)
+!> @endcode
 !>       - id_dimid is dimension id
 !>       - cd_name is dimension name
 !>
 !>    to read variable or global attribute in file:<br/>
-!>    tl_att = iom_read_att(tl_file, id_varid, id_attid)<br/>
-!>    or<br/>
-!>    tl_att = iom_read_att(tl_file, id_varid, cd_attname)<br/>
-!>    or<br/>
-!>    tl_att = iom_read_att(tl_file, cd_varname, cd_attid, [cd_stdname])<br/>
-!>    or<br/>
-!>    tl_att = iom_read_att(tl_file, cd_varname, cd_attname, cd_stdname)
+!> @code
+!>    tl_att = iom_read_att(tl_file, id_varid, id_attid)
+!> @endcode
+!>    or
+!> @code
+!>    tl_att = iom_read_att(tl_file, id_varid, cd_attname)
+!> @endcode
+!>    or
+!> @code
+!>    tl_att = iom_read_att(tl_file, cd_varname, id_attid)
+!> @endcode
+!>    or
+!> @code
+!>    tl_att = iom_read_att(tl_file, cd_varname, cd_attname)
+!> @endcode
 !>       - id_varid is variable id
 !>       - id_attid is attribute id
 !>       - cd_attname is attribute name
-!>       - cd_varname is variable name
-!>       - cd_stdname is variable standard name (optional)
+!>       - cd_varname is variable name or standard name
 !>    
 !>    to read one variable in file:<br/>
-!>    tl_var = iom_read_var(td_file, id_varid, [id_start, id_count])<br/>
-!>    or<br/>
-!>    tl_var = iom_read_var(td_file, cd_name, [id_start, [id_count,]] [cd_stdname])
+!> @code
+!>    tl_var = iom_read_var(td_file, id_varid, [id_start, id_count])
+!> @endcode
+!>    or
+!> @code
+!>    tl_var = iom_read_var(td_file, cd_name, [id_start, [id_count,]])
+!> @endcode
 !>       - id_varid is variabale id
-!>       - cd_name is variabale name
-!>       - id_start is a integer(4) 1D table of index from which the data 
-!>          values will be read (optional)
-!>       - id_count is a integer(4) 1D table of the number of indices selected
-!>          along each dimension (optional)
-!>       - cd_stdname is variable standard name (optional)
+!>       - cd_name is variabale name or standard name.
+!>       - id_start is a integer(4) 1D array of index from which the data 
+!>          values will be read [optional]
+!>       - id_count is a integer(4) 1D array of the number of indices selected
+!>          along each dimension [optional]
 !>
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
-!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+!> @date November, 2013 - Initial Version
+!>
 !> @todo
 !> - see lbc_lnk
 !> - see goup netcdf4
-!> - add iom_fill_var_value : complete tl_file avec valeur de la variable
+!>
+!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
 !----------------------------------------------------------------------
 MODULE iom
    USE netcdf                          ! nf90 library
+   USE global                          ! global parameter
    USE kind                            ! F90 kind parameter
    USE fct                             ! basic useful function
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE dim                             ! dimension manager
    USE att                             ! attribute manager
@@ -76,5 +102,4 @@
    USE iom_rstdimg                     ! restart dimg I/O manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
@@ -86,21 +111,16 @@
    PUBLIC :: iom_read_att    !< read one attribute in an opened file
    PUBLIC :: iom_read_var    !< read one variable  in an opened file   
-   PUBLIC :: iom_fill_var    !< fill variable value
    PUBLIC :: iom_write_file  !< write file structure contents in an opened file
-   ! PUBLIC :: iom_get_mpp     ! get sub domain decomposition 
-
-                                          !< read variable or global attribute in an opened file
-   PRIVATE :: iom__read_var_name_att_id   !< given variable name or standard name and attribute id.
-   PRIVATE :: iom__read_var_id_att_id     !< given variable id and attribute id.
-   PRIVATE :: iom__read_var_name_att_name !< given variable name or standard name, and attribute name.
-   PRIVATE :: iom__read_var_id_att_name   !< given variable id and attribute name.
-
-   PRIVATE :: iom__read_dim_id            !< read one dimension in an opened file, given dimension id.
-   PRIVATE :: iom__read_dim_name          !< read one dimension in an opened netcdf file, given dimension name.
-   PRIVATE :: iom__read_var_id            !< read variable value in an opened file, given variable id.
-   PRIVATE :: iom__read_var_name          !< read variable value in an opened file, given variable name or standard name.
-   PRIVATE :: iom__fill_var_id            !< fill variable value in an opened file, given variable id
-   PRIVATE :: iom__fill_var_name          !< fill variable value in an opened file, given variable name
-   PRIVATE :: iom__fill_var_all           !< fill all variable value in an opened file
+
+                                          ! read variable or global attribute in an opened file
+   PRIVATE :: iom__read_att_varname_id   ! given variable name or standard name and attribute id.
+   PRIVATE :: iom__read_att_varid_id     ! given variable id and attribute id.
+   PRIVATE :: iom__read_att_varname_name ! given variable name or standard name, and attribute name.
+   PRIVATE :: iom__read_att_varid_name   ! given variable id and attribute name.
+
+   PRIVATE :: iom__read_dim_id            ! read one dimension in an opened file, given dimension id.
+   PRIVATE :: iom__read_dim_name          ! read one dimension in an opened netcdf file, given dimension name.
+   PRIVATE :: iom__read_var_id            ! read variable value in an opened file, given variable id.
+   PRIVATE :: iom__read_var_name          ! read variable value in an opened file, given variable name or standard name.
 
    INTERFACE iom_read_var
@@ -109,10 +129,4 @@
    END INTERFACE iom_read_var
 
-   INTERFACE iom_fill_var
-      MODULE PROCEDURE iom__fill_var_id
-      MODULE PROCEDURE iom__fill_var_name
-      MODULE PROCEDURE iom__fill_var_all
-   END INTERFACE 
-
    INTERFACE iom_read_dim
       MODULE PROCEDURE iom__read_dim_id
@@ -121,16 +135,17 @@
 
    INTERFACE iom_read_att    !< read variable or global attribute in an opened file
-      MODULE PROCEDURE iom__read_var_name_att_id   !< given variable name or standard name and attribute id.
-      MODULE PROCEDURE iom__read_var_id_att_id     !< given variable id and attribute id.
-      MODULE PROCEDURE iom__read_var_name_att_name !< given variable name or standard name, and attribute name.
-      MODULE PROCEDURE iom__read_var_id_att_name   !< given variable id and attribute name.
+      MODULE PROCEDURE iom__read_att_varname_id   !< given variable name or standard name and attribute id.
+      MODULE PROCEDURE iom__read_att_varid_id     !< given variable id and attribute id.
+      MODULE PROCEDURE iom__read_att_varname_name !< given variable name or standard name, and attribute name.
+      MODULE PROCEDURE iom__read_att_varid_name   !< given variable id and attribute name.
    END INTERFACE iom_read_att
 
 CONTAINS
    !-------------------------------------------------------------------
-   !> @brief This function open a file in read or write mode<br/>
+   !> @brief This function open a file in read or write mode
+   !> @details
    !> If try to open a file in write mode that did not exist, create it.<br/>
    !> 
-   !> If file already exist, get information about:
+   !> If file exist, get information about:
    !> - the number of variables
    !> - the number of dimensions
@@ -141,9 +156,8 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_open(td_file)
       IMPLICIT NONE
@@ -163,19 +177,17 @@
             CALL iom_rstdimg_open(td_file)
          CASE DEFAULT
-            CALL logger_error("OPEN: unknow type : "//TRIM(td_file%c_name))
+            CALL logger_error("IOM OPEN: unknow type : "//TRIM(td_file%c_name))
 
       END SELECT
 
    END SUBROUTINE iom_open
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function create a file<br/>
+   !-------------------------------------------------------------------
+   !> @brief This function create a file.
    !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_create(td_file)
       IMPLICIT NONE
@@ -202,19 +214,17 @@
             CALL iom_rstdimg_open(td_file)
          CASE DEFAULT
-            CALL logger_error( "CREATE: can't create file "//&
+            CALL logger_error( "IOM CREATE: can't create file "//&
             &               TRIM(td_file%c_name)//": type unknown " )
       END SELECT
 
    END SUBROUTINE iom_create
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine close file
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_close(td_file)
       IMPLICIT NONE
@@ -230,30 +240,26 @@
             CALL iom_rstdimg_close(td_file)
          CASE DEFAULT
-            CALL logger_error( " CLOSE: can't close file "//&
+            CALL logger_error( "IOM CLOSE: can't close file "//&
             &               TRIM(td_file%c_name)//": type unknown " )
       END SELECT
 
    END SUBROUTINE iom_close
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read attribute (of variable or global) in an opened 
    !> file, given variable name or standard name and attribute id.
-   !> to get global attribute use 'GLOBAL' as variable name 
-   !>
-   !> To check only standard name of the variable, put variable name to ''
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] cd_varname : variable name. use 'GLOBAL' to read global 
+   !> @details
+   !>  - to get global attribute use 'GLOBAL' as variable name. 
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file      file structure
+   !> @param[in] cd_varname   variable name. use 'GLOBAL' to read global 
    !> attribute in a file
-   !> @param[in] id_attid : attribute id
-   !> @param[in] cd_stdname : variable standard name
+   !> @param[in] id_attid     attribute id
    !> @return  attribute structure 
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION iom__read_var_name_att_id( td_file, cd_varname, &
-   &                                              id_attid)
+   TYPE(TATT) FUNCTION iom__read_att_varname_id( td_file, cd_varname, &
+   &                                             id_attid)
       IMPLICIT NONE
       ! Argument
@@ -277,17 +283,16 @@
          SELECT CASE(TRIM(td_file%c_type))
             CASE('cdf')
-               iom__read_var_name_att_id=iom_read_att( td_file, il_varid, &
+               iom__read_att_varname_id=iom_read_att( td_file, il_varid, &
                &                                       id_attid)
             CASE('dimg')
-               CALL logger_warn( " READ ATT: can't read attribute "//&
+               CALL logger_warn( " IOM READ ATT: can't read attribute "//&
                &              "in dimg file : "//TRIM(td_file%c_name) )
             CASE DEFAULT
-               CALL logger_error( " READ ATT: can't read attribute in file "//&
-               &               TRIM(td_file%c_name)//" : type unknown " )
+               CALL logger_error( " IOM READ ATT: can't read attribute "//&
+               &    " in file "//TRIM(td_file%c_name)//" : type unknown " )
          END SELECT
       ENDIF
 
-   END FUNCTION iom__read_var_name_att_id
-   !> @endcode   
+   END FUNCTION iom__read_att_varname_id
    !-------------------------------------------------------------------
    !> @brief This function read attribute (of variable or global) in an opened 
@@ -295,14 +300,13 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_varid : variable id. use NF90_GLOBAL to read global 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_varid  variable id. use NF90_GLOBAL to read global 
    !> attribute in a file
-   !> @param[in] id_attid : attribute id
+   !> @param[in] id_attid  attribute id
    !> @return  attribute structure 
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION iom__read_var_id_att_id( td_file, id_varid, &
+   TYPE(TATT) FUNCTION iom__read_att_varid_id( td_file, id_varid, &
    &                                            id_attid)
       IMPLICIT NONE
@@ -316,34 +320,31 @@
       SELECT CASE(TRIM(td_file%c_type))
          CASE('cdf')
-            iom__read_var_id_att_id=iom_cdf_read_att( td_file, id_varid, &
+            iom__read_att_varid_id=iom_cdf_read_att( td_file, id_varid, &
             &                                         id_attid)
          CASE('dimg')
-            CALL logger_warn( " READ ATT: can't read attribute in dimg file "//&
+            CALL logger_warn( " IOM READ ATT: can't read attribute in dimg file "//&
             &              TRIM(td_file%c_name) )
          CASE DEFAULT
-            CALL logger_error( " READ ATT: can't read attribute in file "//&
-            &               TRIM(td_file%c_name)//" : type unknown " )
-      END SELECT
-
-   END FUNCTION iom__read_var_id_att_id
-   !> @endcode
+            CALL logger_error( " IOM READ ATT: can't read attribute in file "//&
+            &               TRIM(td_file%c_name)//" : type unknown " )
+      END SELECT
+
+   END FUNCTION iom__read_att_varid_id
    !-------------------------------------------------------------------
    !> @brief This function read attribute (of variable or global) in an opened 
    !> file, given variable name or standard name, and attribute name.
-   !> to get global attribute use 'GLOBAL' as variable name.
-   !>
-   !> To check only standard name of the variable, put variable name to ''
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] cd_varname : variable name or standard name. use 'GLOBAL' to read global
+   !> @details
+   !> - to get global attribute use 'GLOBAL' as variable name.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file      file structure
+   !> @param[in] cd_varname   variable name or standard name. use 'GLOBAL' to read global
    !> attribute in a file
-   !> @param[in] cd_attname : attribute name
+   !> @param[in] cd_attname   attribute name
    !> @return  attribute structure    
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION iom__read_var_name_att_name( td_file, cd_varname, &
+   TYPE(TATT) FUNCTION iom__read_att_varname_name( td_file, cd_varname, &
    &                                                cd_attname)
       IMPLICIT NONE
@@ -368,17 +369,16 @@
          SELECT CASE(TRIM(td_file%c_type))
             CASE('cdf')
-               iom__read_var_name_att_name=iom_cdf_read_att( td_file, il_varid, &
+               iom__read_att_varname_name=iom_cdf_read_att( td_file, il_varid, &
                &                                             cd_attname)
             CASE('dimg')
-               CALL logger_warn( " READ ATT: can't read attribute "//&
+               CALL logger_warn( " IOM READ ATT: can't read attribute "//&
                &              "in dimg file :"//TRIM(td_file%c_name) )
             CASE DEFAULT
-               CALL logger_error( " READ ATT: can't read attribute in file "//&
+               CALL logger_error( " IOM READ ATT: can't read attribute in file "//&
                &               TRIM(td_file%c_name)//" : type unknown " )
          END SELECT
       ENDIF
 
-   END FUNCTION iom__read_var_name_att_name
-   !> @endcode
+   END FUNCTION iom__read_att_varname_name
    !-------------------------------------------------------------------
    !> @brief This function read attribute (of variable or global) in an opened 
@@ -386,14 +386,13 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_varid : variable id. use NF90_GLOBAL to read global
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file      file structure
+   !> @param[in] id_varid     variable id. use NF90_GLOBAL to read global
    !> attribute in a file
-   !> @param[in] cd_name : attribute name
+   !> @param[in] cd_attname   attribute name
    !> @return  attribute structure    
    !-------------------------------------------------------------------
-   !> @code
-   TYPE(TATT) FUNCTION iom__read_var_id_att_name( td_file, id_varid, &
+   TYPE(TATT) FUNCTION iom__read_att_varid_name( td_file, id_varid, &
    &                                              cd_attname)
       IMPLICIT NONE
@@ -407,16 +406,15 @@
       SELECT CASE(TRIM(td_file%c_type))
          CASE('cdf')
-            iom__read_var_id_att_name=iom_cdf_read_att( td_file, id_varid, &
+            iom__read_att_varid_name=iom_cdf_read_att( td_file, id_varid, &
             &                                           cd_attname)
          CASE('dimg')
-            CALL logger_warn( " READ ATT: can't read attribute in dimg file :"&
+            CALL logger_warn( " IOM READ ATT: can't read attribute in dimg file :"&
             &              //TRIM(td_file%c_name) )
          CASE DEFAULT
-            CALL logger_error( " READ ATT: can't read attribute in file "//&
-            &               TRIM(td_file%c_name)//" : type unknown " )
-      END SELECT
-
-   END FUNCTION iom__read_var_id_att_name
-   !> @endcode
+            CALL logger_error( " IOM READ ATT: can't read attribute in file "//&
+            &               TRIM(td_file%c_name)//" : type unknown " )
+      END SELECT
+
+   END FUNCTION iom__read_att_varid_name
    !-------------------------------------------------------------------
    !> @brief This function read one dimension in an opened file, 
@@ -424,11 +422,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_dimid : dimension id
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_dimid  dimension id
    !> @return  dimension structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TDIM) FUNCTION iom__read_dim_id(td_file, id_dimid)
       IMPLICIT NONE
@@ -445,10 +442,9 @@
             iom__read_dim_id=iom_rstdimg_read_dim(td_file, id_dimid)
          CASE DEFAULT
-            CALL logger_error( " READ DIM: can't read dimension in file "//&
+            CALL logger_error( " IOM READ DIM: can't read dimension in file "//&
             &               TRIM(td_file%c_name)//" : type unknown " )
       END SELECT      
 
    END FUNCTION iom__read_dim_id
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read one dimension in an opened netcdf file, 
@@ -456,11 +452,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] cd_name : dimension name
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] cd_name   dimension name
    !> @return  dimension structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TDIM) FUNCTION iom__read_dim_name(td_file, cd_name)
       IMPLICIT NONE
@@ -477,27 +472,26 @@
             iom__read_dim_name=iom_rstdimg_read_dim(td_file, cd_name)
          CASE DEFAULT
-            CALL logger_error( " READ DIM: can't read dimension in file "//&
+            CALL logger_error( " IOM READ DIM: can't read dimension in file "//&
             &               TRIM(td_file%c_name)//" : type unknown " )
       END SELECT      
 
    END FUNCTION iom__read_dim_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read variable value in an opened 
-   !> file, given variable id.</br/>
+   !> file, given variable id.
+   !> @details
    !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_varid : variable id
-   !> @param[in] id_start : index in the variable from which the data values 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_varid  variable id
+   !> @param[in] id_start  index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom__read_var_id( td_file, id_varid,&
    &                                     id_start, id_count)
@@ -519,32 +513,29 @@
             &                                     id_start, id_count)
          CASE DEFAULT
-            CALL logger_error( " READ VAR: can't read variable in file "//&
+            CALL logger_error( " IOM READ VAR: can't read variable in file "//&
             &               TRIM(td_file%c_name)//" : type unknown " )
       END SELECT
 
    END FUNCTION iom__read_var_id
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read variable value in an opened 
-   !> file, given variable name or standard name.</br/>
+   !> file, given variable name or standard name.
+   !> @details
    !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @details
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !>
    !> look first for variable name. If it doesn't
    !> exist in file, look for variable standard name.<br/>
-   !> If variable name is not present, check variable standard name.<br/>
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file  : file structure
-   !> @param[in] cd_name  : variable name or standard name
-   !> @param[in] id_start : index in the variable from which the data values
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] cd_name   variable name or standard name
+   !> @param[in] id_start  index in the variable from which the data values
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom__read_var_name(td_file, cd_name,   &
    &                                      id_start, id_count  )
@@ -552,9 +543,7 @@
       ! Argument      
       TYPE(TFILE)                   , INTENT(IN) :: td_file
-      CHARACTER(LEN=*)              , INTENT(IN), OPTIONAL :: cd_name
+      CHARACTER(LEN=*)              , INTENT(IN) :: cd_name
       INTEGER(i4)     , DIMENSION(:), INTENT(IN), OPTIONAL :: id_start
       INTEGER(i4)     , DIMENSION(:), INTENT(IN), OPTIONAL :: id_count
-      !INTEGER(i4),      DIMENSION(ip_maxdim),  INTENT(IN), OPTIONAL :: id_start
-      !INTEGER(i4),      DIMENSION(ip_maxdim),  INTENT(IN), OPTIONAL :: id_count
       !----------------------------------------------------------------
       
@@ -568,138 +557,17 @@
             &                                   id_start, id_count )
          CASE DEFAULT
-            CALL logger_error( " READ VAR: can't read variable in file "//&
+            CALL logger_error( " IOM READ VAR: can't read variable in file "//&
             &               TRIM(td_file%c_name)//" : type unknown " )
       END SELECT
 
    END FUNCTION iom__read_var_name
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill all variables value in an opened 
-   !> file.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom__fill_var_all( td_file, id_start, id_count)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TFILE),                       INTENT(INOUT) :: td_file
-      INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL :: id_start
-      INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL :: id_count
-      !----------------------------------------------------------------
-
-      ! open file
-      SELECT CASE(TRIM(td_file%c_type))
-         CASE('cdf')
-            CALL iom_cdf_fill_var(td_file, id_start, id_count)
-         CASE('dimg')
-            CALL iom_rstdimg_fill_var(td_file, id_start, id_count)
-         CASE DEFAULT
-            CALL logger_error( " FILL VAR: can't read variable in file "//&
-            &               TRIM(td_file%c_name)//" : type unknown " )
-      END SELECT
-
-   END SUBROUTINE iom__fill_var_all
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill variable value in an opened 
-   !> file, given variable id.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] id_varid : variable id
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom__fill_var_id( td_file, id_varid, id_start, id_count)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TFILE),                       INTENT(INOUT) :: td_file
-      INTEGER(i4),                       INTENT(IN)    :: id_varid
-      INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL :: id_start
-      INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL :: id_count
-      !----------------------------------------------------------------
-
-      ! open file
-      SELECT CASE(TRIM(td_file%c_type))
-         CASE('cdf')
-            CALL iom_cdf_fill_var(td_file, id_varid, id_start, id_count)
-         CASE('dimg')
-            CALL iom_rstdimg_fill_var(td_file, id_varid, id_start, id_count)
-         CASE DEFAULT
-            CALL logger_error( " FILL VAR: can't read variable in file "//&
-            &               TRIM(td_file%c_name)//" : type unknown " )
-      END SELECT
-
-   END SUBROUTINE iom__fill_var_id
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill variable value in an opened 
-   !> file, given variable name or standard name.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @details
-   !> look first for variable name. If it doesn't
-   !> exist in file, look for variable standard name.<br/>
-   !> If variable name is not present, check variable standard name.<br/>
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name  : variable name or standard name
-   !> @param[in] id_start : index in the variable from which the data values
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom__fill_var_name( td_file, cd_name, id_start, id_count )
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TFILE),                             INTENT(INOUT) :: td_file
-      CHARACTER(LEN=*),                        INTENT(IN)    :: cd_name
-      INTEGER(i4),      DIMENSION(ip_maxdim),  INTENT(IN),   OPTIONAL :: id_start
-      INTEGER(i4),      DIMENSION(ip_maxdim),  INTENT(IN),   OPTIONAL :: id_count
-      !----------------------------------------------------------------
-      
-      ! open file
-      SELECT CASE(TRIM(td_file%c_type))
-         CASE('cdf')
-            CALL iom_cdf_fill_var(td_file, cd_name, id_start, id_count )
-         CASE('dimg')
-            CALL iom_rstdimg_fill_var(td_file, cd_name, id_start, id_count )
-         CASE DEFAULT
-            CALL logger_error( " FILL VAR: can't read variable in file "//&
-            &               TRIM(td_file%c_name)//" : type unknown " )
-      END SELECT
-
-   END SUBROUTINE iom__fill_var_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine write file structure in an opened file.
    !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_write_file(td_file)
       IMPLICIT NONE
@@ -715,40 +583,9 @@
             CALL iom_rstdimg_write_file(td_file)
          CASE DEFAULT
-            CALL logger_error( " WRITE: can't write file "//&
+            CALL logger_error( " IOM WRITE: can't write file "//&
             &               TRIM(td_file%c_name)//" : type unknown " )
       END SELECT
 
    END SUBROUTINE iom_write_file
-   !> @endcode   
-!   !-------------------------------------------------------------------
-!   !> @brief This function get sub domain decomposition.
-!   !
-!   !> @details
-!   !
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in] td_file : file structure
-!   !-------------------------------------------------------------------
-!   !> @code
-!   TYPE(TMPP) FUNCTION iom_get_mpp(td_file)
-!      IMPLICIT NONE
-!      ! Argument      
-!      TYPE(TFILE), INTENT(INOUT) :: td_file
-!      !----------------------------------------------------------------
-!
-!      ! open file
-!      SELECT CASE(TRIM(td_file%c_type))
-!         CASE('cdf')
-!            iom_get_mpp = iom_cdf_get_mpp(td_file)
-!         CASE('dimg')
-!            iom_get_mpp = iom_rstdimg_get_mpp(td_file)
-!         CASE DEFAULT
-!            CALL logger_error( " WRITE: can't write file "//&
-!            &               TRIM(td_file%c_name)//" : type unknown " )
-!      END SELECT
-!
-!   END FUNCTION iom_get_mpp
-!   !> @endcode
 END MODULE iom
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_cdf.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_cdf.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_cdf.f90	(revision 5075)
@@ -6,30 +6,42 @@
 !
 ! DESCRIPTION:
-!> @brief
-!> This module is a library to read/write Netcdf file.
+!> @brief NETCDF Input/Output manager :  Library to read Netcdf input files
 !>
 !> @details
-!>
 !>    to open netcdf file:<br/>
+!> @code
 !>    CALL iom_cdf_open(td_file)
-!>       - td_file is file structure (see file.f90)
+!> @endcode
+!>       - td_file is file structure (see @ref file)
 !>
 !>    to write in netcdf file:<br/>
+!> @code
 !>    CALL  iom_cdf_write_file(td_file)
+!> @endcode
 !>
 !>    to close netcdf file:<br/>
+!> @code
 !>    CALL iom_cdf_close(tl_file)
+!> @endcode
 !>
 !>    to read one dimension in netcdf file:<br/>
-!>    tl_dim = iom_cdf_read_dim(tl_file, id_dimid)<br/>
-!>    or<br/>
+!> @code
+!>    tl_dim = iom_cdf_read_dim(tl_file, id_dimid)
+!> @endcode
+!>    or
+!> @code
 !>    tl_dim = iom_cdf_read_dim(tl_file, cd_name)
+!> @endcode
 !>       - id_dimid is dimension id<br/>
 !>       - cd_name is dimension name
 !>
-!>    to read one global attribute in netcdf file:<br/>
-!>    tl_att = iom_cdf_read_att(tl_file, id_varid, id_attid)<br/>
-!>    or<br/>
+!>    to read one attribute in netcdf file:<br/>
+!> @code
+!>    tl_att = iom_cdf_read_att(tl_file, id_varid, id_attid)
+!> @endcode
+!>    or
+!> @code
 !>    tl_att = iom_cdf_read_att(tl_file, id_varid, cd_name)
+!> @endcode
 !>       - id_varid is variable id
 !>       - id_attid is attribute id<br/>
@@ -37,33 +49,24 @@
 !>    
 !>    to read one variable in netcdf file:<br/>
-!>    tl_var = iom_cdf_read_var(td_file, id_varid, [id_start, id_count])<br/>
-!>    or<br/>
-!>    tl_var = iom_cdf_read_var(td_file, cd_name, [id_start, [id_count,]] [cd_stdname])
+!> @code
+!>    tl_var = iom_cdf_read_var(td_file, id_varid, [id_start, id_count])
+!> @endcode
+!>    or
+!> @code
+!>    tl_var = iom_cdf_read_var(td_file, cd_name, [id_start, [id_count,]])
+!> @endcode
 !>       - id_varid is variabale id
 !>       - cd_name is variabale name
-!>       - id_start is a integer(4) 1D table of index from which the data 
-!>          values will be read (optional)
-!>       - id_count is a integer(4) 1D table of the number of indices selected
-!>          along each dimension (optional)
-!>       - cd_stdname is variable standard name (optional)
+!>       - id_start is a integer(4) 1D array of index from which the data 
+!>          values will be read [optional]
+!>       - id_count is a integer(4) 1D array of the number of indices selected
+!>          along each dimension [optional]
 !>
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
-!> @param MyModule_type : brief_description
+!> @date November, 2013 - Initial Version
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!
-!> @todo 
-!> - inform variable pni, pnj, pnij, area, iglo, jglo 
-!> - use var_init when read new variable
-!> - use dim_init when read new dimension
-!> - use att_init when read new attribute
-!> - add read td_dom
-!> @todo
-!> - voir si il ne faut pas redefinir (__copy) variable si elle vient de mpp
-!> exemple CALL  mpp_move_var( td_mpp, td_mpp%t_var )
 !----------------------------------------------------------------------
 MODULE iom_cdf
@@ -72,13 +75,10 @@
    USE kind                            ! F90 kind parameter
    USE fct                             ! basic useful function
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE att                             ! attribute manage
    USE dim                             ! dimension manager
    USE var                             ! variable manager
    USE file                            ! file manager
-   USE dom                             ! domain manager
-!   USE proc                            ! processor manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
@@ -91,30 +91,29 @@
    PUBLIC :: iom_cdf_fill_var    !< fill variable value in an opened netcdf file
    PUBLIC :: iom_cdf_write_file  !< write file structure contents in an opened netcdf file
-   ! PUBLIC :: iom_cdf_get_mpp     ! get sub domain decomposition in a netcdf file
-
-   PRIVATE :: iom_cdf__check           !< provides a simple interface to netcdf error message
-   PRIVATE :: iom_cdf__get_info        !< get global information in an opened netcdf file
-   PRIVATE :: iom_cdf__get_file_dim    !< read dimension on an opened netcdf file, and reorder it
-   PRIVATE :: iom_cdf__get_file_att    !< read global attribute on an opened netcdf file
-   PRIVATE :: iom_cdf__get_file_var    !< read information about variable on an opened netcdf file
-   PRIVATE :: iom_cdf__read_dim_id     !< read one dimension in an opened netcdf file, given dimension id.
-   PRIVATE :: iom_cdf__read_dim_name   !< read one dimension in an opened netcdf file, given dimension name.
-   PRIVATE :: iom_cdf__read_att_name   !< read variable or global attribute in an opened netcdf file, given attribute name. 
-   PRIVATE :: iom_cdf__read_att_id     !< read variable or global attribute in an opened netcdf file, given attribute id.
-   PRIVATE :: iom_cdf__read_var_id     !< read variable value in an opened netcdf file, given variable id.
-   PRIVATE :: iom_cdf__read_var_name   !< read variable value in an opened netcdf file, given variable name or standard name.
-   PRIVATE :: iom_cdf__read_var_meta   !< read metadata of a variable in an opened netcdf file.
-   PRIVATE :: iom_cdf__read_var_dim    !< read variable dimension in an opened netcdf file.
-   PRIVATE :: iom_cdf__read_var_att    !< read variable attributes in an opened netcdf file.
-   PRIVATE :: iom_cdf__read_var_value  !< read variable value in an opened netcdf file.
-   PRIVATE :: iom_cdf__write_dim       !< write one dimension in an opened netcdf file in write mode.
-   PRIVATE :: iom_cdf__write_att       !< write a variable attribute in an opened netcdf file.
-   PRIVATE :: iom_cdf__write_var       !< write a variable in an opened netcdf file.
-   PRIVATE :: iom_cdf__write_var_def   !< define variable in an opened netcdf file.
-   PRIVATE :: iom_cdf__write_var_value !< put variable value in an opened netcdf file.
-   PRIVATE :: iom_cdf__fill_var_id     !< fill variable value in an opened netcdf file, given variable id
-   PRIVATE :: iom_cdf__fill_var_name   !< fill variable value in an opened netcdf file, given variable name
-   PRIVATE :: iom_cdf__fill_var_all    !< fill all variable value in an opened netcdf file
-   PRIVATE :: iom_cdf__del_var_dim     !< remove variable dimension from an opened netcdf file
+
+   PRIVATE :: iom_cdf__check           ! provides a simple interface to netcdf error message
+   PRIVATE :: iom_cdf__get_info        ! get global information in an opened netcdf file
+   PRIVATE :: iom_cdf__get_file_dim    ! read dimension on an opened netcdf file, and reorder it
+   PRIVATE :: iom_cdf__get_file_att    ! read global attribute on an opened netcdf file
+   PRIVATE :: iom_cdf__get_file_var    ! read information about variable on an opened netcdf file
+   PRIVATE :: iom_cdf__read_dim_id     ! read one dimension in an opened netcdf file, given dimension id.
+   PRIVATE :: iom_cdf__read_dim_name   ! read one dimension in an opened netcdf file, given dimension name.
+   PRIVATE :: iom_cdf__read_att_name   ! read variable or global attribute in an opened netcdf file, given attribute name. 
+   PRIVATE :: iom_cdf__read_att_id     ! read variable or global attribute in an opened netcdf file, given attribute id.
+   PRIVATE :: iom_cdf__read_var_id     ! read variable value in an opened netcdf file, given variable id.
+   PRIVATE :: iom_cdf__read_var_name   ! read variable value in an opened netcdf file, given variable name or standard name.
+   PRIVATE :: iom_cdf__read_var_meta   ! read metadata of a variable in an opened netcdf file.
+   PRIVATE :: iom_cdf__read_var_dim    ! read variable dimension in an opened netcdf file.
+   PRIVATE :: iom_cdf__read_var_att    ! read variable attributes in an opened netcdf file.
+   PRIVATE :: iom_cdf__read_var_value  ! read variable value in an opened netcdf file.
+   PRIVATE :: iom_cdf__write_dim       ! write one dimension in an opened netcdf file in write mode.
+   PRIVATE :: iom_cdf__write_att       ! write a variable attribute in an opened netcdf file.
+   PRIVATE :: iom_cdf__write_var       ! write a variable in an opened netcdf file.
+   PRIVATE :: iom_cdf__write_var_def   ! define variable in an opened netcdf file.
+   PRIVATE :: iom_cdf__write_var_value ! put variable value in an opened netcdf file.
+   PRIVATE :: iom_cdf__fill_var_id     ! fill variable value in an opened netcdf file, given variable id
+   PRIVATE :: iom_cdf__fill_var_name   ! fill variable value in an opened netcdf file, given variable name
+   PRIVATE :: iom_cdf__fill_var_all    ! fill all variable value in an opened netcdf file
+   PRIVATE :: iom_cdf__del_coord_var   ! remove coordinate variable from an opened netcdf file
 
    INTERFACE iom_cdf_read_var
@@ -145,9 +144,8 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] id_status : error status
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] id_status error status
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__check(id_status)
       IMPLICIT NONE
@@ -161,9 +159,9 @@
 
    END SUBROUTINE iom_cdf__check
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine open a netcdf file in read or write mode<br/>
+   !-------------------------------------------------------------------
+   !> @brief This subroutine open a netcdf file in read or write mode.
+   !> @details
    !> if try to open a file in write mode that did not exist, create it.<br/>
-   !> if file already exist, get information about:
+   !> if file already exist, get information about0:<br/>
    !> - the number of variables
    !> - the number of dimensions
@@ -171,12 +169,12 @@
    !> - the ID of the unlimited dimension
    !> - the file format
-   !> and finally read dimensions.
+   !> Finally it read dimensions, and 'longitude' variable to compute East-West
+   !> overlap.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf_open(td_file)
       IMPLICIT NONE
@@ -189,8 +187,4 @@
 
       INTEGER(i4) :: il_status
-
-      TYPE(TVAR)  :: tl_lon
-      ! loop indices
-      INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
@@ -202,11 +196,10 @@
          IF( .NOT. td_file%l_wrt )THEN
 
-            CALL logger_fatal( " OPEN: can not open file "//&
+            CALL logger_fatal( " IOM CDF OPEN: can not open file "//&
             &               TRIM(td_file%c_name) )
-            td_file%i_id=-1
-         
+ 
          ELSE
 
-            CALL logger_info( " CREATE: file "//TRIM(td_file%c_name) )
+            CALL logger_info( " IOM CDF CREATE: file "//TRIM(td_file%c_name) )
 
             il_status = NF90_CREATE( TRIM(td_file%c_name),&
@@ -220,26 +213,25 @@
 
       ELSE
-
          IF( td_file%i_id /= 0 )THEN
 
-            CALL logger_error( " OPEN: file "//&
+            CALL logger_error( " IOM CDF OPEN: file "//&
             &               TRIM(td_file%c_name)//" already opened")
 
          ELSE
-
+ 
             IF( .NOT. td_file%l_wrt )THEN
 
-               CALL logger_info( " OPEN: file "//&
+               CALL logger_info( " IOM CDF OPEN: file "//&
                &              TRIM(td_file%c_name)//" in read only mode" )
 
                il_status = NF90_OPEN( TRIM(td_file%c_name), &
-               &                      NF90_NOWRITE,              &
+               &                      NF90_NOWRITE,         &
                &                      td_file%i_id)
                CALL iom_cdf__check(il_status)
 
-               CALL logger_debug("OPEN "//TRIM(td_file%c_name)//" "//TRIM(fct_str(td_file%i_id)))
+               CALL logger_trace("IOM CDF OPEN "//TRIM(td_file%c_name)//" "//TRIM(fct_str(td_file%i_id)))
             ELSE
 
-               CALL logger_info( " OPEN: file "//&
+               CALL logger_info( "IOM CDF OPEN: file "//&
                &              TRIM(td_file%c_name)//" in write mode" )
 
@@ -263,19 +255,6 @@
             CALL iom_cdf__get_file_var(td_file)
 
-            ! get ew overlap
-            tl_lon=iom_cdf_read_var(td_file,'longitude')
-            td_file%i_ew=dom_get_ew_overlap(tl_lon)
-            CALL logger_debug(" IOM OPEN EW "//TRIM(fct_str(td_file%i_ew)) )
-            WHERE( td_file%t_var(:)%t_dim(1)%l_use )
-               td_file%t_var(:)%i_ew=td_file%i_ew
-            END WHERE
-            CALL var_clean(tl_lon)
-
-            DO ji=1,td_file%i_nvar
-               CALL logger_debug(TRIM(td_file%t_var(ji)%c_name)//": "//TRIM(fct_str(td_file%t_var(ji)%i_ew)) )
-            ENDDO
- 
             ! remove dimension variable from list of variable
-            CALL iom_cdf__del_var_dim(td_file)
+            CALL iom_cdf__del_coord_var(td_file)
 
          ENDIF
@@ -284,14 +263,12 @@
 
    END SUBROUTINE iom_cdf_open
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine close netcdf file
+   !-------------------------------------------------------------------
+   !> @brief This subroutine close netcdf file.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf_close(td_file)
       IMPLICIT NONE
@@ -307,9 +284,9 @@
 
          CALL logger_error( &
-         &  " CLOSE: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF CLOSE: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE
          CALL logger_info( &
-         &  " CLOSE: file "//TRIM(td_file%c_name))
+         &  " IOM CDF CLOSE: file "//TRIM(td_file%c_name))
 
          il_status = NF90_CLOSE(td_file%i_id)
@@ -321,8 +298,7 @@
 
    END SUBROUTINE iom_cdf_close
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine get global information in an opened netcdf 
-   !> file.<br/>
+   !> file.
    !> @details
    !> It gets the number of variables, the number of dimensions, 
@@ -331,10 +307,8 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__get_info(td_file)
       IMPLICIT NONE
@@ -348,5 +322,5 @@
 
       CALL logger_trace( &
-      &  " GET INFO: about netcdf file "//TRIM(td_file%c_name))
+      &  " IOM CDF GET INFO: about netcdf file "//TRIM(td_file%c_name))
 
       il_status=NF90_INQUIRE(td_file%i_id, td_file%i_ndim, &
@@ -365,17 +339,14 @@
 
    END SUBROUTINE iom_cdf__get_info
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine read dimension on an opened netcdf file, and
-   !> reorder dimension to ('x', 'y', 'z', 't').<br/>
+   !> reorder dimension to ('x', 'y', 'z', 't').
    !> The dimension structure inside file structure is then completed.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__get_file_dim(td_file)
       IMPLICIT NONE
@@ -401,5 +372,5 @@
          IF( td_file%i_uldid == -1 )THEN
             CALL logger_warn( &
-            &  " GET FILE DIM: there is no unlimited dimension in file "//&
+            &  " IOM CDF GET FILE DIM: there is no unlimited dimension in file "//&
             &  TRIM(td_file%c_name))
          ELSE
@@ -410,5 +381,5 @@
 
          CALL logger_warn( &
-         &  " GET FILE DIM: there is no dimension in file "//&
+         &  " IOM CDF GET FILE DIM: there is no dimension in file "//&
          &  TRIM(td_file%c_name))
 
@@ -419,17 +390,16 @@
 
    END SUBROUTINE iom_cdf__get_file_dim
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine read global attribute on an opened netcdf 
-   !> file.<br/>
+   !> file.
    !> The attribute structure inside file structure is then completed.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - use attribute periodicity read from the file if present.
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__get_file_att(td_file)
       IMPLICIT NONE
@@ -437,4 +407,5 @@
       TYPE(TFILE), INTENT(INOUT) :: td_file
 
+      ! local variable
       ! loop indices
       INTEGER(i4) :: ji
@@ -443,4 +414,5 @@
       IF( td_file%i_natt > 0 )THEN
          IF(ASSOCIATED(td_file%t_att))THEN
+            CALL att_clean(td_file%t_att(:))
             DEALLOCATE(td_file%t_att)
          ENDIF
@@ -451,36 +423,24 @@
             td_file%t_att(ji)=iom_cdf_read_att( td_file, NF90_GLOBAL, ji)
             
-            SELECT CASE(TRIM(td_file%t_att(ji)%c_name))
-               CASE('periodicity')
-                  td_file%i_perio=INT(td_file%t_att(ji)%d_value(1),i4)
-               CASE('pivot_point')
-                  td_file%i_pivot=INT(td_file%t_att(ji)%d_value(1),i4)
-               CASE('ew_overlap')
-                  td_file%i_ew=INT(td_file%t_att(ji)%d_value(1),i4)
-            END SELECT
-
          ENDDO
 
       ELSE
          CALL logger_debug( &
-         &  " GET FILE ATT: there is no global attribute in file "//&
+         &  " IOM CDF GET FILE ATT: there is no global attribute in file "//&
          &  TRIM(td_file%c_name))
       ENDIF
 
    END SUBROUTINE iom_cdf__get_file_att
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine read information about variable of an 
-   !> opened netcdf file.<br/>
+   !> opened netcdf file.
    !> The variable structure inside file structure is then completed.
    !> @note variable value are not read !
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__get_file_var(td_file)
       IMPLICIT NONE
@@ -497,4 +457,5 @@
       IF( td_file%i_nvar > 0 )THEN
          IF(ASSOCIATED(td_file%t_var))THEN
+            CALL var_clean(td_file%t_var(:))
             DEALLOCATE(td_file%t_var)
          ENDIF
@@ -504,5 +465,4 @@
             ! read dimension information
             td_file%t_var(ji)=iom_cdf__read_var_meta( td_file, ji)
-
             SELECT CASE(td_file%t_var(ji)%i_ndim)
                CASE(0)
@@ -524,7 +484,9 @@
                   td_file%i_depthid=ji
                ELSE
-                  CALL logger_error("IOM OPEN: find more than one "//&
-                  &                 "depth variable in file "//&
-                  &                 TRIM(td_file%c_name) )
+                  IF( td_file%i_depthid /= ji )THEN
+                     CALL logger_error("IOM CDF GET FILE VAR: find more than one "//&
+                     &                 "depth variable in file "//&
+                     &                 TRIM(td_file%c_name) )
+                  ENDIF
                ENDIF
             ENDIF
@@ -554,21 +516,19 @@
       ELSE
          CALL logger_debug( &
-         &  " GET FILE VAR: there is no variable in file "//&
+         &  " IOM CDF GET FILE VAR: there is no variable in file "//&
          &  TRIM(td_file%c_name))
       ENDIF
 
    END SUBROUTINE iom_cdf__get_file_var
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine delete variable dimension from an 
-   !> opened netcdf file.<br/>
-   !
-   !> @author J.Paul
-   !> - 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_cdf__del_var_dim(td_file)
+   !-------------------------------------------------------------------
+   !> @brief This subroutine delete coordinate variable from an 
+   !> opened netcdf file if present.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_cdf__del_coord_var(td_file)
       IMPLICIT NONE
       ! Argument      
@@ -598,87 +558,8 @@
       ELSE
          CALL logger_debug( &
-         &  " DEL VAR DIM: there is no variable in file "//&
+         &  " IOM CDF DEL VAR DIM: there is no variable in file "//&
          &  TRIM(td_file%c_name))
       ENDIF
-   END SUBROUTINE iom_cdf__del_var_dim
-   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief This subroutine get variable time from an 
-!   !> opened netcdf file.<br/>
-!   !
-!   !> @author J.Paul
-!   !> - 2013- Initial Version
-!   !
-!   !> @param[inout] td_file : file structure
-!   !-------------------------------------------------------------------
-!   !> @code
-!   SUBROUTINE iom_cdf__get_var_time(td_file)
-!      IMPLICIT NONE
-!      ! Argument      
-!      TYPE(TFILE), INTENT(INOUT) :: td_file
-!
-!      ! local variable
-!      CHARACTER(LEN=lc) :: cl_name
-!
-!      ! loop indices
-!      INTEGER(i4) :: ji
-!      !----------------------------------------------------------------
-!      IF( td_file%i_nvar > 0 )THEN
-!         DO ji=1,td_file%i_nvar
-!            cl_name=TRIM(td_file%t_var(ji)%c_name)
-!            IF( INDEX(cl_name,'time') /= 0 )THEN
-!               ! read time variable
-!               td_file%t_time=iom_cdf_read_var(td_file,ji)
-!               ! remove time variable from variable list
-!               CALL file_del_ver(td_file,TRIM(cl_name))
-!               EXIT
-!            ENDIF
-!         ENDDO
-!      ELSE
-!         CALL logger_debug( &
-!         &  " GET VAR TIME: there is no variable in file "//&
-!         &  TRIM(td_file%c_name))
-!      ENDIF
-!   END SUBROUTINE iom_cdf__get_var_time
-!   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief This subroutine get variable depth from an 
-!   !> opened netcdf file.<br/>
-!   !
-!   !> @author J.Paul
-!   !> - 2013- Initial Version
-!   !
-!   !> @param[inout] td_file : file structure
-!   !-------------------------------------------------------------------
-!   !> @code
-!   SUBROUTINE iom_cdf__get_var_depth(td_file)
-!      IMPLICIT NONE
-!      ! Argument      
-!      TYPE(TFILE), INTENT(INOUT) :: td_file
-!
-!      ! local variable
-!      CHARACTER(LEN=lc) :: cl_name
-!
-!      ! loop indices
-!      INTEGER(i4) :: ji
-!      !----------------------------------------------------------------
-!      IF( td_file%i_nvar > 0 )THEN
-!         DO ji=1,td_file%i_nvar
-!            cl_name=TRIM(td_file%t_var(ji)%c_name)
-!            IF( INDEX(cl_name,'depth') /= 0 )THEN
-!               ! read depth variable
-!               td_file%t_depth=iom_cdf_read_var(td_file,ji)
-!               ! remove depth variable from variable list
-!               CALL file_del_ver(td_file,TRIM(cl_name))
-!               EXIT
-!            ENDIF
-!         ENDDO
-!      ELSE
-!         CALL logger_debug( &
-!         &  " GET VAR TIME: there is no variable in file "//&
-!         &  TRIM(td_file%c_name))
-!      ENDIF
-!   END SUBROUTINE iom_cdf__get_var_depth
-!   !> @endcode
+   END SUBROUTINE iom_cdf__del_coord_var
    !-------------------------------------------------------------------
    !> @brief This function read one dimension in an opened netcdf file, 
@@ -686,11 +567,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_dimid : dimension id
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_dimid  dimension id
    !> @return  dimension structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TDIM) FUNCTION iom_cdf__read_dim_id(td_file, id_dimid)
       IMPLICIT NONE
@@ -709,5 +589,5 @@
 
          CALL logger_error( &
-         &  " READ DIM: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF READ DIM: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE      
@@ -715,6 +595,6 @@
          iom_cdf__read_dim_id%i_id=id_dimid
 
-         CALL logger_debug( &
-         &  " READ DIM: dimension "//TRIM(fct_str(id_dimid))//&
+         CALL logger_trace( &
+         &  " IOM CDF READ DIM: dimension "//TRIM(fct_str(id_dimid))//&
          &  " in file "//TRIM(td_file%c_name))
 
@@ -728,5 +608,4 @@
 
    END FUNCTION iom_cdf__read_dim_id
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read one dimension in an opened netcdf file, 
@@ -734,11 +613,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] cd_name : dimension name
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] cd_name   dimension name
    !> @return  dimension structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TDIM) FUNCTION iom_cdf__read_dim_name(td_file, cd_name)
       IMPLICIT NONE
@@ -756,5 +634,5 @@
 
          CALL logger_error( &
-         &  " READ DIM: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF READ DIM: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE      
@@ -769,5 +647,4 @@
 
    END FUNCTION iom_cdf__read_dim_name
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This function read variable or global attribute in an opened 
@@ -775,13 +652,12 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_varid : variable id. use NF90_GLOBAL to read global
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_varid  variable id. use NF90_GLOBAL to read global
    !> attribute in a file
-   !> @param[in] cd_name : attribute name
+   !> @param[in] cd_name   attribute name
    !> @return  attribute structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TATT) FUNCTION iom_cdf__read_att_name(td_file, id_varid, cd_name)
       IMPLICIT NONE
@@ -800,4 +676,5 @@
 
       CHARACTER(LEN=lc) :: cl_value
+      
       INTEGER(i1), DIMENSION(:), ALLOCATABLE :: bl_value
       INTEGER(i2), DIMENSION(:), ALLOCATABLE :: sl_value
@@ -810,5 +687,5 @@
 
          CALL logger_error( &
-         &  " READ ATT: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF READ ATT: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE      
@@ -819,12 +696,12 @@
          IF( id_varid == NF90_GLOBAL )THEN
 
-            CALL logger_debug( &
-            &  " READ ATT: inquire global attribute "//&
+            CALL logger_trace( &
+            &  " IOM CDF READ ATT: inquire global attribute "//&
             &  " in file "//TRIM(td_file%c_name))
 
          ELSE
 
-            CALL logger_debug( &
-            &  " READ ATT: inquire attribute "//&
+            CALL logger_trace( &
+            &  " IOM CDF READ ATT: inquire attribute "//&
             &  " of variable "//TRIM(fct_str(id_varid))//&
             &  " in file "//TRIM(td_file%c_name))
@@ -840,5 +717,5 @@
 
          !! get attribute value
-         CALL logger_debug( " READ ATT: get attribute "//TRIM(cl_name)//&
+         CALL logger_debug( " IOM CDF READ ATT: get attribute "//TRIM(cl_name)//&
          &               " in file "//TRIM(td_file%c_name))
 
@@ -851,5 +728,5 @@
 
                   CALL logger_error( &
-                  &  " READ ATT: not enough space to put attribute "//&
+                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
                   &  TRIM(cl_name) )
 
@@ -872,7 +749,6 @@
                IF(il_status /= 0 )THEN
 
-                  CALL logger_error( &
-                  &  " READ ATT: not enough space to put attribute "//&
-                  &  TRIM(cl_name) )
+                  CALL logger_error( "IOM CDF READ ATT: "//&
+                  &  "not enough space to put attribute "//TRIM(cl_name) )
 
                ELSE
@@ -897,5 +773,5 @@
 
                   CALL logger_error( &
-                  &  " READ ATT: not enough space to put attribute "//&
+                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
                   &  TRIM(cl_name) )
 
@@ -921,5 +797,5 @@
 
                   CALL logger_error( &
-                  &  " READ ATT: not enough space to put attribute "//&
+                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
                   &  TRIM(cl_name) )
 
@@ -944,5 +820,5 @@
 
                   CALL logger_error( &
-                  &  " READ ATT: not enough space to put attribute "//&
+                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
                   &  TRIM(cl_name) )
 
@@ -968,5 +844,5 @@
 
                   CALL logger_error( &
-                  &  " READ ATT: not enough space to put attribute "//&
+                  &  " IOM CDF READ ATT: not enough space to put attribute "//&
                   &  TRIM(cl_name) )
 
@@ -992,5 +868,4 @@
 
    END FUNCTION iom_cdf__read_att_name
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This function read variable or global attribute in an opened 
@@ -998,13 +873,12 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_varid : variable id. use NF90_GLOBAL to read global 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_varid  variable id. use NF90_GLOBAL to read global 
    !> attribute in a file
-   !> @param[in] id_attid : attribute id
+   !> @param[in] id_attid  attribute id
    !> @return  attribute structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TATT) FUNCTION iom_cdf__read_att_id(td_file, id_varid, id_attid)
       IMPLICIT NONE
@@ -1022,7 +896,7 @@
 
          CALL logger_error( &
-         &  " READ ATT: no id associated to file "//TRIM(td_file%c_name))
-
-      ELSE      
+         &  "IOM CDF READ ATT: no id associated to file "//TRIM(td_file%c_name))
+
+      ELSE
 
          ! get attribute name
@@ -1036,22 +910,21 @@
 
    END FUNCTION iom_cdf__read_att_id
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This function read variable value in an opened 
-   !> netcdf file, given variable id.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_varid : variable id
-   !> @param[in] id_start : index in the variable from which the data values 
+   !> netcdf file, given variable id.
+   !> @details
+   !> Optionaly, start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_varid  variable id
+   !> @param[in] id_start  index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom_cdf__read_var_id(td_file, id_varid,&
    &                                        id_start, id_count)
@@ -1070,15 +943,14 @@
 
          CALL logger_error( &
-         &  " IOM READ VAR: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF READ VAR: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE
 
-         ! look for variable id
+         ! look for variable index
          il_ind(:)=MINLOC(td_file%t_var(:)%i_id,mask=(td_file%t_var(:)%i_id==id_varid))
          IF( il_ind(1) /= 0 )THEN
 
-            iom_cdf__read_var_id=td_file%t_var(il_ind(1))
-
-            print *,"iom_cdf__read_var_id ",trim(iom_cdf__read_var_id%c_name)," ",iom_cdf__read_var_id%i_ew
+            iom_cdf__read_var_id=var_copy(td_file%t_var(il_ind(1)))
+
             !!! read variable value
             CALL iom_cdf__read_var_value(td_file, iom_cdf__read_var_id, &
@@ -1086,7 +958,6 @@
 
          ELSE
-            print *,"iom_cdf__read_var_id "
             CALL logger_error( &
-            &  " IOM READ VAR: there is no variable with id "//&
+            &  " IOM CDF READ VAR: there is no variable with id "//&
             &  TRIM(fct_str(id_varid))//" in file "//TRIM(td_file%c_name))
          ENDIF
@@ -1094,27 +965,23 @@
       ENDIF
    END FUNCTION iom_cdf__read_var_id
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This function read variable value in an opened 
-   !> netcdf file, given variable name or standard name.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
+   !> netcdf file, given variable name or standard name.
    !> @details
+   !> Optionaly, start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !>
    !> look first for variable name. If it doesn't
    !> exist in file, look for variable standard name.<br/>
-   !> If variable name is not present, check variable standard name.<br/>
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] cd_name  : variable name
-   !> @param[in] id_start : index in the variable from which the data values will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] cd_stdname : variable standard name
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] cd_name   variable name or standard name.
+   !> @param[in] id_start  index in the variable from which the data values will be read
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom_cdf__read_var_name(td_file, cd_name,  &
    &                                          id_start, id_count )
@@ -1127,5 +994,5 @@
 
       ! local variable
-      INTEGER(i4)       :: il_ind
+      INTEGER(i4)       :: il_varid
       !----------------------------------------------------------------
       ! check if file opened
@@ -1133,5 +1000,5 @@
 
          CALL logger_error( &
-         &  " IOM READ VAR: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF READ VAR: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE
@@ -1140,13 +1007,13 @@
 
             CALL logger_error( &
-            &  " IOM READ VAR: you must specify a variable to read "//&
+            &  " IOM CDF READ VAR: you must specify a variable to read "//&
             &  " in file "//TRIM(td_file%c_name))
 
          ELSE
 
-            il_ind=var_get_id(td_file%t_var(:), cd_name)
-            IF( il_ind /= 0 )THEN
-
-               iom_cdf__read_var_name=td_file%t_var(il_ind)
+            il_varid=var_get_index(td_file%t_var(:), cd_name)
+            IF( il_varid /= 0 )THEN
+
+               iom_cdf__read_var_name=var_copy(td_file%t_var(il_varid))
 
                !!! read variable value
@@ -1158,5 +1025,5 @@
 
                CALL logger_error( &
-               &  " IOM READ VAR: there is no variable with "//&
+               &  " IOM CDF READ VAR: there is no variable with "//&
                &  " name or standard name "//TRIM(cd_name)//&
                &  " in file "//TRIM(td_file%c_name) )
@@ -1168,23 +1035,19 @@
       
    END FUNCTION iom_cdf__read_var_name
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill variable value in an opened 
-   !> netcdf file, given variable id.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @note ne peut pas marcher qd on fait boucle sur les variable d'un
-   !> fichier. puisque change id.
-
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] id_start : index in the variable from which the data values 
+   !-------------------------------------------------------------------
+   !> @brief This subroutine fill all variable value from an opened 
+   !> netcdf file.
+   !> @details
+   !> Optionaly, start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] id_start     index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] id_count     number of indices selected along each dimension
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__fill_var_all(td_file, id_start, id_count)
       IMPLICIT NONE
@@ -1203,34 +1066,31 @@
 
          CALL logger_error( &
-         &  " FILL VAR: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF FILL VAR: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE
 
          DO ji=1,td_file%i_nvar
-            CALL iom_cdf_fill_var(td_file, ji, id_start, id_count)
+            CALL iom_cdf_fill_var(td_file, td_file%t_var(ji)%i_id, &
+            &                     id_start, id_count)
          ENDDO
 
       ENDIF
    END SUBROUTINE iom_cdf__fill_var_all
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine fill variable value in an opened 
-   !> netcdf file, given variable id.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @note ne peut pas marcher qd on fait boucle sur les variable d'un
-   !> fichier. puisque change id.
-
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] id_varid : variable id
-   !> @param[in] id_start : index in the variable from which the data values 
+   !> netcdf file, given variable id.
+   !> @details
+   !> Optionaly, start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] id_varid     variable id
+   !> @param[in] id_start     index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] id_count     number of indices selected along each dimension
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__fill_var_id(td_file, id_varid, id_start, id_count)
       IMPLICIT NONE
@@ -1242,5 +1102,5 @@
 
       ! local variable
-      INTEGER(i4), DIMENSION(1) :: il_ind
+      INTEGER(i4), DIMENSION(1) :: il_varid
 
       ! loop indices
@@ -1251,23 +1111,25 @@
 
          CALL logger_error( &
-         &  " FILL VAR: no id associated to file "//TRIM(td_file%c_name))
+         &  "IOM CDF FILL VAR: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE
 
          ! look for variable id
-         il_ind(:)=MINLOC( td_file%t_var(:)%i_id, &
+         il_varid(:)=MINLOC( td_file%t_var(:)%i_id, &
          &                 mask=(td_file%t_var(:)%i_id==id_varid))
-         IF( il_ind(1) /= 0 )THEN
+         IF( il_varid(1) /= 0 )THEN
 
             !!! read variable value
-            CALL iom_cdf__read_var_value(td_file, td_file%t_var(il_ind(1)), &
+            CALL iom_cdf__read_var_value(td_file, td_file%t_var(il_varid(1)), &
             &                            id_start, id_count)
 
             DO ji=1,td_file%i_nvar
-               CALL logger_debug(" var id "//TRIM(td_file%t_var(ji)%c_name)//" "//TRIM(fct_str(td_file%t_var(ji)%i_id)) )
+               CALL logger_debug(" IOM CDF FILL VAR: var id "//&
+               &     TRIM(td_file%t_var(ji)%c_name)//" "//&
+               &     TRIM(fct_str(td_file%t_var(ji)%i_id)) )
             ENDDO
          ELSE
             CALL logger_error( &
-            &  " FILL VAR: there is no variable with id "//&
+            &  " IOM CDF FILL VAR: there is no variable with id "//&
             &  TRIM(fct_str(id_varid))//" in file "//TRIM(td_file%c_name))
          ENDIF
@@ -1275,25 +1137,22 @@
       ENDIF
    END SUBROUTINE iom_cdf__fill_var_id
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine fill variable value in an opened 
-   !> netcdf file, given variable name or standard name.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
+   !> netcdf file, given variable name or standard name.
    !> @details
+   !> Optionaly, start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !>
    !> look first for variable name. If it doesn't
    !> exist in file, look for variable standard name.<br/>
-   !> If variable name is not present, check variable standard name.<br/>
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name  : variable name or standard name
-   !> @param[in] id_start : index in the variable from which the data values will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !-------------------------------------------------------------------
-   !> @code
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] cd_name      variable name or standard name
+   !> @param[in] id_start     index in the variable from which the data values will be read
+   !> @param[in] id_count     number of indices selected along each dimension
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__fill_var_name(td_file, cd_name, id_start, id_count )
       IMPLICIT NONE
@@ -1305,5 +1164,5 @@
 
       ! local variable
-      INTEGER(i4)       :: il_ind
+      INTEGER(i4)       :: il_varid
       !----------------------------------------------------------------
       ! check if file opened
@@ -1311,13 +1170,13 @@
 
          CALL logger_error( &
-         &  " FILL VAR: no id associated to file "//TRIM(td_file%c_name))
+         &  "IOM CDF FILL VAR: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE
 
-            il_ind=var_get_id(td_file%t_var(:), cd_name)
-            IF( il_ind /= 0 )THEN
+            il_varid=var_get_index(td_file%t_var(:), cd_name)
+            IF( il_varid /= 0 )THEN
 
                !!! read variable value
-               CALL iom_cdf__read_var_value(td_file, td_file%t_var(il_ind), &
+               CALL iom_cdf__read_var_value(td_file, td_file%t_var(il_varid), &
                &                            id_start, id_count)
 
@@ -1325,5 +1184,5 @@
 
                CALL logger_error( &
-               &  " FILL VAR: there is no variable with "//&
+               &  "IOM CDF FILL VAR: there is no variable with "//&
                &  "name or standard name"//TRIM(cd_name)//&
                &  " in file "//TRIM(td_file%c_name))
@@ -1333,19 +1192,19 @@
       
    END SUBROUTINE iom_cdf__fill_var_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read metadata of a variable in an opened 
-   !> netcdf file.</br/>
+   !> netcdf file.
    !
    !> @note variable value are not read
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] id_fileid : file id
-   !> @param[in] id_varid : variable id
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - force to use FillValue=1.e20 if no FillValue for coordinate variable.
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_varid  variable id
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom_cdf__read_var_meta(td_file, id_varid)
       IMPLICIT NONE
@@ -1375,5 +1234,6 @@
 
          CALL logger_error( &
-         &  " READ ATT: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF READ VAR META: no id associated to file "//&
+         &   TRIM(td_file%c_name))
 
       ELSE
@@ -1381,5 +1241,6 @@
          ! inquire variable
          CALL logger_trace( &
-         &  " READ VAR: inquire variable "//TRIM(fct_str(id_varid))//&
+         &  " IOM CDF READ VAR META: inquire variable "//&
+         &  TRIM(fct_str(id_varid))//&
          &  " in file "//TRIM(td_file%c_name))
          
@@ -1393,8 +1254,6 @@
          &                                il_natt )
          CALL iom_cdf__check(il_status)
-
          !!! fill variable dimension structure
          tl_dim(:)=iom_cdf__read_var_dim( td_file, il_ndim, il_dimid(:) )
-
          IF( il_natt /= 0 )THEN
             ALLOCATE( tl_att(il_natt) )
@@ -1405,5 +1264,5 @@
             il_attid=att_get_id(tl_att(:),'_FillValue')
             IF( il_attid == 0 )THEN
-               CALL logger_warn("IOM READ VAR: no _FillValue for variable "//&
+               CALL logger_info("IOM CDF READ VAR META: no _FillValue for variable "//&
                &  TRIM(cl_name)//" in file "//TRIM(td_file%c_name) )
 
@@ -1411,27 +1270,39 @@
                IF( il_attid /= 0 )THEN
                   ! create attribute _FillValue
-                  CALL logger_warn("IOM READ VAR: assume _FillValue is equal to "//&
+                  CALL logger_info("IOM CDF READ VAR META: assume _FillValue is equal to "//&
                   &                "missing_value for variable "//TRIM(cl_name) )
-                  tl_fill=att_init('_FillValue',tl_att(il_attid)%d_value(:))
+                  tl_fill=att_init('_FillValue',tl_att(il_attid)%d_value(:), &
+                  &                 id_type=tl_att(il_attid)%i_type)
                ELSE
                   ! create attribute _FillValue
-                  CALL logger_warn("IOM READ VAR: assume _FillValue is equal to "//&
-                  &                "zero for variable "//TRIM(cl_name) )
-                  tl_fill=att_init('_FillValue',0.)
-                  !tl_fill=att_init('_FillValue',1.e20)
+                  SELECT CASE(TRIM(cl_name))
+                     CASE DEFAULT
+                        CALL logger_info("IOM CDF READ VAR META: assume _FillValue is equal to "//&
+                        &                "zero for variable "//TRIM(cl_name) )
+                        tl_fill=att_init('_FillValue',0.)
+                     CASE('nav_lon','nav_lat', &
+                        &  'glamt','glamu','glamv','glamf', &
+                        &  'gphit','gphiu','gphiv','gphif')
+                        CALL logger_info("IOM CDF READ VAR META: assume _FillValue is equal to "//&
+                        &                "dummy fillValue (1.e20) for variable "//TRIM(cl_name) )
+                        tl_fill=att_init('_FillValue',1.e20)
+                  END SELECT
                ENDIF
 
                ALLOCATE( tl_tmp(il_natt) )
                ! save read attribut
-               tl_tmp(:)=tl_att(:)
-               ! change number of attribute in table
+               tl_tmp(:)=att_copy(tl_att(:))
+               ! change number of attribute in array
+               CALL att_clean(tl_att(:))
                DEALLOCATE( tl_att )
                ALLOCATE( tl_att(il_natt+1) )
                ! copy read attribut
-               tl_att(1:il_natt)=tl_tmp(:)
+               tl_att(1:il_natt)=att_copy(tl_tmp(:))
+               ! clean
+               CALL att_clean(tl_tmp(:))
                DEALLOCATE( tl_tmp )
 
                ! create attribute _FillValue
-               tl_att(il_natt+1)=tl_fill
+               tl_att(il_natt+1)=att_copy(tl_fill)
 
             ENDIF
@@ -1440,9 +1311,18 @@
             ALLOCATE(tl_att(il_natt+1) )
             ! create attribute _FillValue
-            CALL logger_warn("IOM READ VAR: assume _FillValue is equal to "//&
-            &                "zero for variable "//TRIM(cl_name) )
-            tl_fill=att_init('_FillValue',0.)
+            SELECT CASE(TRIM(cl_name))
+               CASE DEFAULT
+                  CALL logger_info("IOM CDF READ VAR META: assume _FillValue is equal to "//&
+                  &                "zero for variable "//TRIM(cl_name) )
+                  tl_fill=att_init('_FillValue',0.)
+               CASE('nav_lon','nav_lat', &
+                  &  'glamt','glamu','glamv','glamf', &
+                  &  'gphit','gphiu','gphiv','gphif')
+                  CALL logger_info("IOM CDF READ VAR META: assume _FillValue is equal to "//&
+                  &                "dummy fillValue (1.e20) for variable "//TRIM(cl_name) )
+                  tl_fill=att_init('_FillValue',1.e20)
+            END SELECT            
             ! create attribute _FillValue
-            tl_att(il_natt+1)=tl_fill
+            tl_att(il_natt+1)=att_copy(tl_fill)
          ENDIF
 
@@ -1451,4 +1331,8 @@
          &                                tl_att(:), id_id=id_varid )
 
+         ! clean
+         CALL dim_clean(tl_dim(:))
+         CALL att_clean(tl_fill)
+         CALL att_clean(tl_att(:))
          DEALLOCATE( tl_att )
 
@@ -1456,24 +1340,24 @@
 
    END FUNCTION iom_cdf__read_var_meta
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine read variable dimension
    !> in an opened netcdf file.
-   !
+   !>
    !> @details
    !> the number of dimension can't exceed 4, 
    !> and should be 'x', 'y', 'z', 't' (whatever their order).<br/>
-   !> If the number of dimension read is less than 4, the table of dimension
+   !> If the number of dimension read is less than 4, the array of dimension
    !> strucure is filled with unused dimension.<br/>
-   !> So the table of dimension structure of a variable is always compose of 4
+   !> So the array of dimension structure of a variable is always compose of 4
    !> dimension (use or not). 
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_ndim   number of dimension
+   !> @param[in] id_dimid  array of dimension id
+   !> @return array dimension structure 
+   !-------------------------------------------------------------------
    FUNCTION iom_cdf__read_var_dim(td_file, id_ndim, id_dimid)
       IMPLICIT NONE
@@ -1502,5 +1386,8 @@
          CALL dim_reorder(tl_dim(:))
 
-         iom_cdf__read_var_dim(:)=tl_dim(:)
+         iom_cdf__read_var_dim(:)=dim_copy(tl_dim(:))
+
+         ! clean
+         CALL dim_clean(tl_dim(:))
 
       ELSE IF( id_ndim > 0 .AND. id_ndim <= 4 )THEN
@@ -1508,5 +1395,5 @@
 
          DO ji = 1, id_ndim
-            CALL logger_debug( " READ VAR DIM: get variable dimension "//&
+            CALL logger_trace( " IOM CDF READ VAR DIM: get variable dimension "//&
             &               TRIM(fct_str(ji)) )
 
@@ -1521,9 +1408,12 @@
          CALL dim_reorder(tl_dim(:))
       
-         iom_cdf__read_var_dim(:)=tl_dim(:)
+         iom_cdf__read_var_dim(:)=dim_copy(tl_dim(:))
+
+         ! clean
+         CALL dim_clean(tl_dim(:))
 
       ELSE
 
-         CALL logger_error(" READ VAR DIM: can't manage "//&
+         CALL logger_error(" IOM CDF READ VAR DIM: can't manage "//&
          &              TRIM(fct_str(id_ndim))//" dimension(s)" )
 
@@ -1531,5 +1421,4 @@
 
    END FUNCTION iom_cdf__read_var_dim
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine read variable attributes
@@ -1537,11 +1426,11 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[inout] td_var : variable structure
-   !> @return filled variable attribute structure 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_varid  variable id
+   !> @param[in] id_natt   number of attributes
+   !> @return array of attribute structure
+   !-------------------------------------------------------------------
    FUNCTION iom_cdf__read_var_att(td_file, id_varid, id_natt)
       IMPLICIT NONE
@@ -1555,5 +1444,4 @@
 
       ! local variable
-      TYPE(TATT), DIMENSION(id_natt) :: tl_att
 
       ! loop indices
@@ -1562,35 +1450,35 @@
 
       IF( id_natt > 0 )THEN
-
+      
          ! read attributes
          DO ji = 1, id_natt
-            CALL logger_debug( " READ VAR ATT: get attribute "//&
+            CALL logger_trace( " IOM CDF READ VAR ATT: get attribute "//&
             &               TRIM(fct_str(ji)) )
 
-            tl_att(ji)=iom_cdf_read_att(td_file, id_varid, ji)
+            iom_cdf__read_var_att(ji)=iom_cdf_read_att(td_file, id_varid, ji)
 
          ENDDO
 
-         iom_cdf__read_var_att(:)=tl_att(:)
-
       ELSE
 
-         CALL logger_debug( " READ VAR ATT: no attribute for variable " )
+         CALL logger_debug( " IOM CDF READ VAR ATT: no attribute for variable " )
 
       ENDIF
 
    END FUNCTION iom_cdf__read_var_att
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine read variable value
    !> in an opened netcdf file.
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] id_start : index in the variable from which the data values will be read
-   !> @param[in] id_count : number of indices selected along each dimension
+   !> @details
+   !> Optionaly, start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] id_start  index in the variable from which the data values will be read
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return variable structure completed 
    !
@@ -1598,5 +1486,4 @@
    !> - warning do not change fill value when use scale factor..
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE iom_cdf__read_var_value(td_file, td_var, &
    &                                  id_start, id_count )
@@ -1610,173 +1497,186 @@
       ! local variable
       INTEGER(i4)                       :: il_status
-      INTEGER(i4)                       :: il_tmp1, il_tmp2, il_varid
+      INTEGER(i4)                       :: il_tmp1
+      INTEGER(i4)                       :: il_tmp2
+      INTEGER(i4)                       :: il_varid
       INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
       INTEGER(i4), DIMENSION(ip_maxdim) :: il_count
       INTEGER(i4), DIMENSION(ip_maxdim) :: il_start_ord
       INTEGER(i4), DIMENSION(ip_maxdim) :: il_count_ord
-      REAL(dp)   , DIMENSION(:,:,:,:), ALLOCATABLE :: dl_value
-
-      TYPE(TDIM),  DIMENSION(ip_maxdim) :: tl_dim
+      REAL(dp)   , DIMENSION(:,:,:,:)  , ALLOCATABLE :: dl_value
+      REAL(dp)   , DIMENSION(:,:,:,:)  , ALLOCATABLE :: dl_tmp
+
       ! loop indices
       INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
-      ! check id_count and id_start optionals parameters...
-      IF( (       PRESENT(id_start)  .AND. (.NOT. PRESENT(id_count))) .OR. &
-          ((.NOT. PRESENT(id_start)) .AND.        PRESENT(id_count) ) )THEN
-         CALL logger_warn( &
-         &  " READ VAR VALUE: id_start and id_count should be both specify")
-      ENDIF
-
-      IF( PRESENT(id_start).AND.PRESENT(id_count) )THEN
-
-         IF( SIZE(id_start(:)) /= ip_maxdim .OR. &
-         &   SIZE(id_count(:)) /= ip_maxdim )THEN
-            CALL logger_error("READ VAR: dimension of table start or count "//&
-            &      " are invalid to read variable "//TRIM(td_var%c_name)//&
-            &      " in file "//TRIM(td_file%c_name) )
-         ENDIF
-
-         ! change dimension order from ('x','y','z','t')
-         il_start(:)=dim_reorder_xyzt2(td_var%t_dim, id_start(:))
-         il_count(:)=dim_reorder_xyzt2(td_var%t_dim, id_count(:))
-
-         ! keep ordered table ('x','y','z','t')
-         il_start_ord(:)=il_start(:)
-         il_count_ord(:)=il_count(:)
-
+      ! check if variable in file structure
+      il_varid=var_get_id(td_file%t_var(:),TRIM(td_var%c_name))
+      IF( il_varid /= 0 )THEN
+
+         ! check id_count and id_start optionals parameters...
+         IF( (       PRESENT(id_start)  .AND. (.NOT. PRESENT(id_count))) .OR. &
+             ((.NOT. PRESENT(id_start)) .AND.        PRESENT(id_count) ) )THEN
+            CALL logger_warn( &
+            &  "IOM CDF READ VAR VALUE: id_start and id_count should be both specify")
+         ENDIF
+         IF( PRESENT(id_start).AND.PRESENT(id_count) )THEN
+
+            IF( SIZE(id_start(:)) /= ip_maxdim .OR. &
+            &   SIZE(id_count(:)) /= ip_maxdim )THEN
+               CALL logger_error("IOM CDF READ VAR: dimension of array start or count "//&
+               &      " are invalid to read variable "//TRIM(td_var%c_name)//&
+               &      " in file "//TRIM(td_file%c_name) )
+            ENDIF
+
+            ! change dimension order from ('x','y','z','t')
+            il_start(:)=dim_reorder_xyzt2(td_var%t_dim, id_start(:))
+            il_count(:)=dim_reorder_xyzt2(td_var%t_dim, id_count(:))
+
+            ! keep ordered array ('x','y','z','t')
+            il_start_ord(:)=id_start(:)
+            il_count_ord(:)=id_count(:)
+
+         ELSE
+
+            ! change dimension order from ('x','y','z','t')
+            il_start(:)=(/1,1,1,1/)
+            il_count(:)=dim_reorder_xyzt2(td_var%t_dim(:),td_var%t_dim(:)%i_len)
+
+            ! keep ordered array ('x','y','z','t')
+            il_start_ord(:)=(/1,1,1,1/)
+            il_count_ord(:)=td_var%t_dim(:)%i_len
+
+         ENDIF
+
+         ! check dimension
+         IF( .NOT. ALL(il_start_ord(:)>=(/1,1,1,1/)) )THEN
+
+            CALL logger_error( "IOM CDF READ VAR VALUE: start indices should"//&
+            &  " be greater than or equal to 1")
+
+         ENDIF
+
+         IF(.NOT.ALL(il_start_ord(:)+il_count_ord(:)-1 <= &
+            &  (/td_var%t_dim( 1 )%i_len,&
+            &    td_var%t_dim( 2 )%i_len,&
+            &    td_var%t_dim( 3 )%i_len,&
+            &    td_var%t_dim( 4 )%i_len &
+            &                                            /)) )THEN
+
+            CALL logger_error( "IOM CDF READ VAR VALUE: start + count exceed "//&
+            &  "variable dimension for "//TRIM(td_var%c_name) )
+
+            DO ji = 1, ip_maxdim
+               il_tmp1=il_start_ord(ji)+il_count_ord(ji)-1
+               il_tmp2=td_var%t_dim(ji)%i_len
+               CALL logger_debug( "IOM CDF READ VAR VALUE: start + count -1:"//&
+               &  TRIM(fct_str(il_tmp1))//" variable dimension"//&
+               &  TRIM(fct_str(il_tmp2)))
+            ENDDO
+
+         ELSE
+
+            ! Allocate space to hold variable value (unorder)
+            ALLOCATE(dl_value( il_count(1), &
+               &               il_count(2), &
+               &               il_count(3), &
+               &               il_count(4)),&
+               &               stat=il_status)
+            IF( il_status /= 0 )THEN
+
+              CALL logger_error( &
+               &  "IOM CDF READ VAR VALUE: not enough space to put variable "//&
+               &  TRIM(td_var%c_name))
+
+            ENDIF
+
+            ! read values
+            CALL logger_debug( &
+            &  "IOM CDF READ VAR VALUE: get variable "//TRIM(td_var%c_name)//&
+            &  " in file "//TRIM(td_file%c_name))
+
+            il_status = NF90_GET_VAR( td_file%i_id, il_varid,           &
+            &                                       dl_value(:,:,:,:),  &
+            &                                       start = il_start(:),&
+            &                                       count = il_count(:) )
+            CALL iom_cdf__check(il_status)
+
+            ! Allocate space to hold variable value in structure
+            IF( ASSOCIATED(td_var%d_value) )THEN
+               DEALLOCATE(td_var%d_value)   
+            ENDIF
+  
+            ! new dimension length
+            td_var%t_dim(:)%i_len=il_count_ord(:)
+
+!>   dummy patch for pgf95
+            ALLOCATE( dl_tmp( td_var%t_dim(1)%i_len, &
+            &                 td_var%t_dim(2)%i_len, &
+            &                 td_var%t_dim(3)%i_len, &
+            &                 td_var%t_dim(4)%i_len),&
+            &        stat=il_status)
+            IF(il_status /= 0 )THEN
+
+               CALL logger_error( &
+               &  "IOM CDF READ VAR VALUE: not enough space to put variable "//&
+               &  TRIM(td_var%c_name)//&
+               &  " in variable structure")
+            ENDIF
+            dl_tmp(:,:,:,:)=td_var%d_fill
+
+            ! reshape values to be ordered as ('x','y','z','t')
+            dl_tmp(:,:,:,:)=dim_reshape_2xyzt(td_var%t_dim(:), &
+            &                                 dl_value(:,:,:,:))
+
+            DEALLOCATE(dl_value)
+
+            ALLOCATE(td_var%d_value( td_var%t_dim(1)%i_len, &
+            &                        td_var%t_dim(2)%i_len, &
+            &                        td_var%t_dim(3)%i_len, &
+            &                        td_var%t_dim(4)%i_len),&
+            &        stat=il_status)
+            IF(il_status /= 0 )THEN
+
+               CALL logger_error( &
+               &  "IOM CDF READ VAR VALUE: not enough space to put variable "//&
+               &  TRIM(td_var%c_name)//&
+               &  " in variable structure")
+
+            ENDIF
+!            ! FillValue by default
+!            td_var%d_value(:,:,:,:)=td_var%d_fill
+!
+!            ! reshape values to be ordered as ('x','y','z','t')
+!            td_var%d_value(:,:,:,:)=dim_reshape_2xyzt(td_var%t_dim(:), &
+!            &                                         dl_value(:,:,:,:))
+!
+!            DEALLOCATE(dl_value)
+
+            td_var%d_value(:,:,:,:)=dl_tmp(:,:,:,:)
+            DEALLOCATE(dl_tmp)
+!<   dummy patch for pgf95
+
+            ! force to change _FillValue to avoid mistake 
+            ! with dummy zero _FillValue
+            IF( td_var%d_fill == 0._dp )THEN
+               CALL var_chg_FillValue(td_var)
+            ENDIF
+         ENDIF
       ELSE
-
-         ! change dimension order from ('x','y','z','t')
-         il_start(:)=(/1,1,1,1/)
-         il_count(:)=dim_reorder_xyzt2(td_var%t_dim(:),td_var%t_dim(:)%i_len)
-
-         ! keep ordered table ('x','y','z','t')
-         il_start_ord(:)=(/1,1,1,1/)
-         il_count_ord(:)=td_var%t_dim(:)%i_len
-
-      ENDIF
-
-      ! check dimension
-      IF( .NOT. ALL(il_start_ord(:)>=(/1,1,1,1/)) )THEN
-
          CALL logger_error( &
-         &" READ VAR VALUE: start indices should be greater than or equal to 1")
-
-      ENDIF
-
-      IF(.NOT.ALL(il_start_ord(:)+il_count_ord(:)-1<=(/td_var%t_dim(1)%i_len,&
-         &                                             td_var%t_dim(2)%i_len,&
-         &                                             td_var%t_dim(3)%i_len,&
-         &                                             td_var%t_dim(4)%i_len &
-         &                                            /)) )THEN
-
-         CALL logger_error( &
-         &  " READ VAR VALUE: start + count exceed variable dimension" )
-
-         DO ji = 1, ip_maxdim
-            il_tmp1=il_start_ord(ji)+il_count_ord(ji)
-            il_tmp2=td_var%t_dim(ji)%i_len
-            CALL logger_debug( &
-            &  " READ VAR VALUE: start + count -1 "//TRIM(fct_str(il_tmp1))//&
-            &  " variable dimension"//TRIM(fct_str(il_tmp2)))
-         ENDDO
-
-      ELSE
-
-         ! Allocate space to hold variable value (unorder)
-         ALLOCATE(dl_value( il_count(1), &
-            &               il_count(2), &
-            &               il_count(3), &
-            &               il_count(4)),&
-            &               stat=il_status)
-         IF( il_status /= 0 )THEN
-
-           CALL logger_error( &
-            &  " READ VAR VALUE: not enough space to put variable "//&
-            &  TRIM(td_var%c_name))
-
-         ENDIF
-
-         ! read values
-         CALL logger_debug( &
-         &  " READ VAR VALUE: get variable "//TRIM(td_var%c_name)//&
-         &  " in file "//TRIM(td_file%c_name))
-         CALL logger_debug("start "//TRIM(fct_str(il_start(1)))//','//&
-         &                           TRIM(fct_str(il_start(2)))//','//&
-         &                           TRIM(fct_str(il_start(3)))//','//&
-         &                           TRIM(fct_str(il_start(4)))//')'  )
-         CALL logger_debug("count "//TRIM(fct_str(il_count(1)))//','//&
-         &                           TRIM(fct_str(il_count(2)))//','//&
-         &                           TRIM(fct_str(il_count(3)))//','//&
-         &                           TRIM(fct_str(il_count(4)))//')'  )
-         CALL logger_debug("dim "//TRIM(fct_str(td_file%t_dim(1)%i_len))//','//&
-         &                         TRIM(fct_str(td_file%t_dim(2)%i_len))//','//&
-         &                         TRIM(fct_str(td_file%t_dim(3)%i_len))//','//&
-         &                         TRIM(fct_str(td_file%t_dim(4)%i_len))//')'  )
-         CALL logger_debug("shape "//TRIM(fct_str(SIZE(dl_value,DIM=1)))//","//&
-         &                           TRIM(fct_str(SIZE(dl_value,DIM=2)))//","//&
-         &                           TRIM(fct_str(SIZE(dl_value,DIM=3)))//","//&
-         &                           TRIM(fct_str(SIZE(dl_value,DIM=4)))//")" )
-         CALL logger_debug("var "//TRIM(td_var%c_name))
-         il_varid=var_get_id(td_file%t_var(:),TRIM(td_var%c_name))
-         CALL logger_debug("var id "//TRIM(fct_str(il_varid))//' '//TRIM(fct_str(td_var%i_id)))
-         CALL logger_debug("file id "//TRIM(fct_str(td_file%i_id)))
-         il_status = NF90_GET_VAR( td_file%i_id, td_var%i_id,        &
-         &                                       dl_value(:,:,:,:),  &
-         &                                       start = il_start(:),&
-         &                                       count = il_count(:) )
-         CALL iom_cdf__check(il_status)
-
-         ! Allocate space to hold variable value in structure
-         IF( ASSOCIATED(td_var%d_value) )THEN
-            DEALLOCATE(td_var%d_value)   
-         ENDIF
-  
-         ! new dimension length
-         td_var%t_dim(:)%i_len=il_count_ord(:)
-
-         ALLOCATE(td_var%d_value( il_count_ord(1), &
-         &                        il_count_ord(2), &
-         &                        il_count_ord(3), &
-         &                        il_count_ord(4)),&
-         &        stat=il_status)
-         IF(il_status /= 0 )THEN
-
-            CALL logger_error( &
-            &  " READ VAR VALUE: not enough space to put variable "//&
-            &  TRIM(td_var%c_name)//&
-            &  " in variable structure")
-
-         ENDIF
-         ! FillValue by default
-         td_var%d_value(:,:,:,:)=td_var%d_fill
-
-         ! reshape values to be ordered as ('x','y','z','t')
-         tl_dim(:)=td_var%t_dim(:)
-         td_var%d_value(:,:,:,:)=dim_reshape_2xyzt(tl_dim,dl_value(:,:,:,:))
-
-         DEALLOCATE(dl_value)
-
-         ! force to change _FillValue to avoid mistake 
-         ! with dummy zero _FillValue
-         IF( td_var%d_fill == 0._dp )THEN
-            CALL var_chg_FillValue(td_var)
-         ENDIF
+         &  "IOM CDF READ VAR VALUE: no variable "//TRIM(td_var%c_name)//&
+         &  " in file structure "//TRIM(td_file%c_name))
       ENDIF
 
    END SUBROUTINE iom_cdf__read_var_value
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write file structure in an opened netcdf file.
    !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf_write_file(td_file)
       IMPLICIT NONE
@@ -1800,14 +1700,14 @@
 
          CALL logger_error( &
-         &  " WRITE FILE: no id associated to file "//TRIM(td_file%c_name))
+         &  " IOM CDF WRITE FILE: no id associated to file "//TRIM(td_file%c_name))
 
       ELSE
          IF( td_file%l_wrt )THEN
 
-            ! delete dummy variable
-            CALL file_del_var( td_file, 'no0d' )
-            CALL file_del_var( td_file, 'no1d' )
-            CALL file_del_var( td_file, 'no2d' )
-            CALL file_del_var( td_file, 'no3d' )
+            ! remove dummy variable
+            CALL file_del_var(td_file,'no0d')
+            CALL file_del_var(td_file,'no1d')
+            CALL file_del_var(td_file,'no2d')
+            CALL file_del_var(td_file,'no3d')
 
             DO ji = 1, td_file%i_nvar
@@ -1816,9 +1716,13 @@
 
             ! save usefull dimension
-            tl_dim(:)=var_max_dim(td_file%t_var(:))
-
-            DO ji=1,ip_maxdim
-               IF( tl_dim(ji)%l_use ) CALL file_move_dim(td_file, tl_dim(ji))
-            ENDDO
+            IF( ASSOCIATED(td_file%t_var) )THEN
+               tl_dim(:)=var_max_dim(td_file%t_var(:))
+
+               DO ji=1,ip_maxdim
+                  IF( tl_dim(ji)%l_use ) CALL file_move_dim(td_file, tl_dim(ji))
+               ENDDO
+               ! clean
+               CALL dim_clean(tl_dim(:))
+            ENDIF
 
             ! write dimension in file
@@ -1836,6 +1740,10 @@
 
                   DEALLOCATE(il_value)
+
+                  ! do not use FillValue for dimension variable
+                  CALL var_del_att(tl_var, "_FillValue")
                    
                   CALL iom_cdf__write_var(td_file,tl_var)
+                  ! clean
                   CALL var_clean(tl_var)
 
@@ -1856,5 +1764,5 @@
 
             CALL logger_error( &
-            &  " WRITE FILE: try to write in file "//TRIM(td_file%c_name)//&
+            &  "IOM CDF WRITE FILE: try to write in file "//TRIM(td_file%c_name)//&
             &  ", not opened in write mode")
 
@@ -1863,5 +1771,4 @@
 
    END SUBROUTINE iom_cdf_write_file
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine write one dimension in an opened netcdf 
@@ -1869,10 +1776,9 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[inout] td_dim : dimension structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[inout] td_dim    dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__write_dim(td_file, td_dim)
       IMPLICIT NONE
@@ -1887,6 +1793,6 @@
       IF( .NOT. td_file%l_def )THEN
 
-         CALL logger_debug( &
-         &  " WRITE FILE DIM: Enter define mode, file "//TRIM(td_file%c_name))
+         CALL logger_trace( &
+         &  " IOM CDF WRITE FILE DIM: Enter define mode, file "//TRIM(td_file%c_name))
 
          ! Enter define mode
@@ -1901,6 +1807,6 @@
          IF( td_dim%l_uld )THEN
             ! write unlimited dimension
-            CALL logger_debug( &
-            &  " WRITE FILE DIM: write unlimited dimension "//&
+            CALL logger_trace( &
+            &  "IOM CDF WRITE FILE DIM: write unlimited dimension "//&
             &  TRIM(td_dim%c_name)//" in file "//TRIM(td_file%c_name))
 
@@ -1911,6 +1817,6 @@
          ELSE
             ! write not unlimited dimension
-            CALL logger_debug( &
-            &  " WRITE FILE DIM: write dimension "//TRIM(td_dim%c_name)//&
+            CALL logger_trace( &
+            &  "IOM CDF WRITE FILE DIM: write dimension "//TRIM(td_dim%c_name)//&
             &  " in file "//TRIM(td_file%c_name))
             
@@ -1923,5 +1829,4 @@
 
    END SUBROUTINE iom_cdf__write_dim
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write a variable attribute in
@@ -1929,12 +1834,11 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] id_varid : variable id. use NF90_GLOBAL to write global attribute
-   !> in a file
-   !> @param[in] td_att : attribute structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] id_varid     variable id. use NF90_GLOBAL to write 
+   !> global attribute in a file
+   !> @param[in] td_att       attribute structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__write_att(td_file, id_varid, td_att)
       IMPLICIT NONE
@@ -1950,6 +1854,6 @@
       IF( .NOT. td_file%l_def )THEN
 
-         CALL logger_debug( &
-         &  " WRITE FILE ATT: Enter define mode, file "//TRIM(td_file%c_name))
+         CALL logger_trace( &
+         &  "IOM CDF WRITE FILE ATT: Enter define mode, file "//TRIM(td_file%c_name))
 
          ! Enter define mode
@@ -1962,6 +1866,6 @@
 
       !! put attribute value
-      CALL logger_debug( &
-      &  " WRITE FILE ATT: write attribute "//TRIM(td_att%c_name)//&
+      CALL logger_trace( &
+      &  "IOM CDF WRITE FILE ATT: write attribute "//TRIM(td_att%c_name)//&
       &  " of variable "//TRIM(fct_str(id_varid))//&
       &  " in file "//TRIM(td_file%c_name))
@@ -1983,15 +1887,13 @@
 
    END SUBROUTINE iom_cdf__write_att
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine write a variable in an opened netcdf file.</br/>
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[inout] td_var : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !-------------------------------------------------------------------
+   !> @brief This subroutine write a variable in an opened netcdf file.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[inout] td_var    variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__write_var(td_file, td_var)
       IMPLICIT NONE
@@ -2002,10 +1904,14 @@
       ! local variable
       INTEGER(i4) :: il_status
+      LOGICAL     :: ll_chg
+      ! loop indices
+      INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
       IF( .NOT. td_file%l_def )THEN
 
-         CALL logger_debug( &
-         &  " WRITE FILE VAR: Enter define mode, file "//TRIM(td_file%c_name))
+         CALL logger_trace( &
+         &  " IOM CDF WRITE VAR: Enter define mode, file "//&
+         &  TRIM(td_file%c_name))
 
          ! Enter define mode
@@ -2023,6 +1929,20 @@
          CALL var_check_dim(td_var)
 
-         ! change fill value to NETCDF standard
-         CALL var_chg_FillValue(td_var)
+         ll_chg=.TRUE.
+         DO ji=1,ip_maxdim
+            IF( TRIM(fct_lower(cp_dimorder(ji:ji))) == &
+            &   TRIM(fct_lower(td_var%c_name)) )THEN
+               ll_chg=.FALSE.
+               CALL logger_trace(TRIM(fct_lower(td_var%c_name))//' is var dimension')
+               EXIT
+            ENDIF
+         ENDDO
+         IF( ll_chg )THEN
+            ! not a dimension variable
+            ! change FillValue
+
+            ! ugly patch until NEMO do not force to use 0. as FillValue 
+            CALL var_chg_FillValue(td_var,0._dp)
+         ENDIF
 
          ! define variable in file
@@ -2031,6 +1951,7 @@
          IF( td_file%l_def )THEN
 
-            CALL logger_debug( &
-            &  " WRITE FILE VAR: Leave define mode, file "//TRIM(td_file%c_name))
+            CALL logger_trace( &
+            &  " IOM CDF WRITE VAR: Leave define mode, file "//&
+            &  TRIM(td_file%c_name))
 
             ! Leave define mode
@@ -2050,16 +1971,14 @@
 
    END SUBROUTINE iom_cdf__write_var
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This function define variable in an opened netcdf file.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] td_var : variable structure
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] td_var    variable structure
    !> @return  variable id
    !-------------------------------------------------------------------
-   !> @code
    INTEGER(i4) FUNCTION iom_cdf__write_var_def(td_file, td_var)
       IMPLICIT NONE
@@ -2070,5 +1989,8 @@
       ! local variable
       INTEGER(i4)                       :: il_status
+      INTEGER(i4)                       :: il_ind
       INTEGER(i4), DIMENSION(ip_maxdim) :: il_dimid
+
+      TYPE(TVAR)                        :: tl_var
 
       ! loop indices
@@ -2077,12 +1999,11 @@
       !----------------------------------------------------------------
 
-      CALL logger_debug( &
-      &  " WRITE FILE VAR DEF: get dimension to be used for variable "//&
-      &  TRIM(td_var%c_name)//" in file "//TRIM(td_file%c_name))
-
-      IF( ALL( .NOT. td_var%t_dim(:)%l_use ) )THEN
+      ! copy structure
+      tl_var=var_copy(td_var)
+
+      IF( ALL( .NOT. tl_var%t_dim(:)%l_use ) )THEN
          ! scalar value
-         il_status = NF90_DEF_VAR(td_file%i_id, TRIM(td_var%c_name), &
-         &                        td_var%i_type, varid=iom_cdf__write_var_def) 
+         il_status = NF90_DEF_VAR(td_file%i_id, TRIM(tl_var%c_name), &
+         &                        tl_var%i_type, varid=iom_cdf__write_var_def) 
          CALL iom_cdf__check(il_status)
       ELSE
@@ -2093,20 +2014,19 @@
          ! reorder dimension, so unused dimension won't be written
          DO ji = 1,  ip_maxdim
-            IF( td_var%t_dim(ji)%l_use )THEN
+            IF( tl_var%t_dim(ji)%l_use )THEN
                jj=jj+1
-               CALL logger_debug(" get dim id for dimension "//TRIM(td_var%t_dim(ji)%c_name))
-               il_dimid(jj)=dim_get_id(td_file%t_dim(:),td_var%t_dim(ji)%c_name)
+               il_dimid(jj)=dim_get_id(td_file%t_dim(:),tl_var%t_dim(ji)%c_name)
             ENDIF
          ENDDO
 
-         CALL logger_debug( &
-         &  " WRITE FILE VAR DEF: define dimension to be used for variable "//&
-         &  TRIM(td_var%c_name)//" in file "//TRIM(td_file%c_name))
+         CALL logger_trace( &
+         &  "IOM CDF WRITE VAR DEF: define dimension to be used for variable "//&
+         &  TRIM(tl_var%c_name)//" in file "//TRIM(td_file%c_name))
 
          DO ji=1,jj
-            CALL logger_debug(" WRITE FILE VAR DEF: dimid "//TRIM(fct_str(il_dimid(ji))) )
+            CALL logger_trace("IOM CDF WRITE VAR DEF: dimid "//TRIM(fct_str(il_dimid(ji))) )
          ENDDO
-         il_status = NF90_DEF_VAR(td_file%i_id, TRIM(td_var%c_name),     &
-         &                        td_var%i_type,                         &
+         il_status = NF90_DEF_VAR(td_file%i_id, TRIM(tl_var%c_name),     &
+         &                        tl_var%i_type,                         &
          &                        il_dimid(1:jj),                        &
          &                        varid=iom_cdf__write_var_def           )
@@ -2114,45 +2034,52 @@
       ENDIF
 
-      DO ji = 1, td_var%i_natt
-         CALL logger_debug( &
-         &  " WRITE FILE VAR DEF: put attribute "//TRIM(td_var%t_att(ji)%c_name)//&
-         &  " for variable "//TRIM(td_var%c_name)//&
+      ! remove unuseful attribute
+      il_ind=att_get_index( tl_var%t_att(:), "ew_overlap" )
+      IF( il_ind /= 0 )THEN
+         IF( tl_var%t_att(il_ind)%d_value(1) == -1 )THEN
+            CALL var_del_att(tl_var, tl_var%t_att(il_ind))
+         ENDIF
+      ENDIF
+
+      DO ji = 1, tl_var%i_natt
+         CALL logger_trace( &
+         &  " IOM CDF WRITE VAR DEF: put attribute "//TRIM(tl_var%t_att(ji)%c_name)//&
+         &  " for variable "//TRIM(tl_var%c_name)//&
          &  " in file "//TRIM(td_file%c_name) )
 
-         IF( td_var%t_att(ji)%i_type == NF90_CHAR )THEN
-            !IF( TRIM(td_var%t_att(ji)%c_value) /= 'unknown' )THEN
-            IF( TRIM(td_var%t_att(ji)%c_value) /= '' )THEN
+         IF( tl_var%t_att(ji)%i_type == NF90_CHAR )THEN
+            IF( TRIM(tl_var%t_att(ji)%c_value) /= '' )THEN
                il_status = NF90_PUT_ATT(td_file%i_id, iom_cdf__write_var_def, &
-               &                        TRIM(td_var%t_att(ji)%c_name),        &
-               &                        TRIM(td_var%t_att(ji)%c_value)        )
+               &                        TRIM(tl_var%t_att(ji)%c_name),        &
+               &                        TRIM(tl_var%t_att(ji)%c_value)        )
                CALL iom_cdf__check(il_status)
             ENDIF
          ELSE
-            SELECT CASE(td_var%t_att(ji)%i_type)
+            SELECT CASE(tl_var%t_att(ji)%i_type)
                CASE(NF90_BYTE)
                   il_status = NF90_PUT_ATT(td_file%i_id,                   &
                   &                        iom_cdf__write_var_def,         &
-                  &                        TRIM(td_var%t_att(ji)%c_name),  &
-                  &                        INT(td_var%t_att(ji)%d_value(:),i1))
+                  &                        TRIM(tl_var%t_att(ji)%c_name),  &
+                  &                        INT(tl_var%t_att(ji)%d_value(:),i1))
                CASE(NF90_SHORT)
                   il_status = NF90_PUT_ATT(td_file%i_id,                   &
                   &                        iom_cdf__write_var_def,         &
-                  &                        TRIM(td_var%t_att(ji)%c_name),  &
-                  &                        INT(td_var%t_att(ji)%d_value(:),i2))
+                  &                        TRIM(tl_var%t_att(ji)%c_name),  &
+                  &                        INT(tl_var%t_att(ji)%d_value(:),i2))
                CASE(NF90_INT)
                   il_status = NF90_PUT_ATT(td_file%i_id,                   &
                   &                        iom_cdf__write_var_def,         &
-                  &                        TRIM(td_var%t_att(ji)%c_name),  &
-                  &                        INT(td_var%t_att(ji)%d_value(:),i4))
+                  &                        TRIM(tl_var%t_att(ji)%c_name),  &
+                  &                        INT(tl_var%t_att(ji)%d_value(:),i4))
                CASE(NF90_FLOAT)
                   il_status = NF90_PUT_ATT(td_file%i_id,                   &
                   &                        iom_cdf__write_var_def,         &
-                  &                        TRIM(td_var%t_att(ji)%c_name),  &
-                  &                        REAL(td_var%t_att(ji)%d_value(:),sp))
+                  &                        TRIM(tl_var%t_att(ji)%c_name),  &
+                  &                        REAL(tl_var%t_att(ji)%d_value(:),sp))
                CASE(NF90_DOUBLE)
                   il_status = NF90_PUT_ATT(td_file%i_id,                   &
                   &                        iom_cdf__write_var_def,         &
-                  &                        TRIM(td_var%t_att(ji)%c_name),  &
-                  &                        REAL(td_var%t_att(ji)%d_value(:),dp))
+                  &                        TRIM(tl_var%t_att(ji)%c_name),  &
+                  &                        REAL(tl_var%t_att(ji)%d_value(:),dp))
                END SELECT
             CALL iom_cdf__check(il_status)
@@ -2161,5 +2088,4 @@
 
    END FUNCTION iom_cdf__write_var_def
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine put variable value in an opened netcdf file.
@@ -2167,14 +2093,13 @@
    !> @details
    !> The variable is written in the type define in variable structure.
-   !> Only dimension used are printed, and fillValue in table are
+   !> Only dimension used are printed, and fillValue in array are
    !> replaced by default fill values defined in module netcdf for each type. 
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] td_var : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] td_var    variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_cdf__write_var_value(td_file, td_var)
       IMPLICIT NONE
@@ -2194,6 +2119,6 @@
 
       ! check which dimension use
-      CALL logger_debug( &
-      &  " WRITE FILE VAR VALUE: get dimension to be used for variable "//&
+      CALL logger_trace( &
+      &  "IOM CDF WRITE VAR VALUE: get dimension to be used for variable "//&
       &  TRIM(td_var%c_name)//" in file "//TRIM(td_file%c_name))
 
@@ -2202,6 +2127,4 @@
          IF( td_var%t_dim(ji)%l_use )THEN
             jj=jj+1
-            !il_order(ji)=jj
-            !il_shape(ji)=td_var%t_dim(jj)%i_len
             il_order(jj)=ji
             il_shape(jj)=td_var%t_dim(ji)%i_len
@@ -2212,6 +2135,4 @@
          IF( .NOT. td_var%t_dim(ji)%l_use )THEN
             jj=jj+1
-            !il_order(ji)=jj
-            !il_shape(ji)=td_var%t_dim(jj)%i_len
             il_order(jj)=ji
             il_shape(jj)=td_var%t_dim(ji)%i_len
@@ -2221,5 +2142,5 @@
       ALLOCATE( dl_value( il_shape(1),il_shape(2),il_shape(3),il_shape(4) ) )
 
-      ! reshape table, so unused dimension won't be written
+      ! reshape array, so unused dimension won't be written
       dl_value(:,:,:,:)=RESHAPE(source=td_var%d_value(:,:,:,:),&
       &                         SHAPE = il_shape(:), &
@@ -2227,6 +2148,6 @@
 
       ! put value
-      CALL logger_debug( &
-      &  " WRITE FILE VAR VALUE: put "//TRIM(td_var%c_name)//" value "//&
+      CALL logger_trace( &
+      &  "IOM CDF WRITE VAR VALUE: put "//TRIM(td_var%c_name)//" value "//&
       &  "in file "//TRIM(td_file%c_name))
 
@@ -2237,4 +2158,3 @@
 
    END SUBROUTINE iom_cdf__write_var_value
-   !> @endcode
 END MODULE iom_cdf
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_dom.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_dom.f90	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_dom.f90	(revision 5075)
@@ -0,0 +1,714 @@
+!----------------------------------------------------------------------
+! NEMO system team, System and Interface for oceanic RElocable Nesting
+!----------------------------------------------------------------------
+!
+! MODULE: iom_dom
+!
+! DESCRIPTION:
+!> @brief This module allow to read domain (defined as domain structure) in a mpp files.
+!>
+!> @details
+!>    to read one variable in an mpp files over domain defined as domain structure:<br/>
+!> @code
+!>    tl_var=iom_dom_read_var( td_mpp, id_varid, td_dom ) 
+!> @endcode
+!>    or
+!> @code
+!>    tl_var=iom_dom_read_var( td_mpp, cd_name, td_dom ) 
+!> @endcode
+!>       - td_mpp is a mpp structure
+!>       - id_varid is a variable id
+!>       - cd_name is variable name or standard name
+!>       - td_dom is a domain structure
+!>
+!> @author
+!> J.Paul
+! REVISION HISTORY:
+!> @date October, 2014 - Initial Version
+!>
+!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
+!----------------------------------------------------------------------
+MODULE iom_dom
+   USE netcdf                          ! nf90 library
+   USE global                          ! global parameter
+   USE kind                            ! F90 kind parameter
+   USE fct                             ! basic useful function
+   USE logger                          ! log file manager
+   USE dim                             ! dimension manager
+   USE att                             ! attribute manager
+   USE var                             ! variable manager
+   USE iom                             ! I/O manager
+   USE mpp                             ! mpp manager
+   USe dom                             ! domain manager
+   USE iom_mpp                         ! I/O mpp manager
+   IMPLICIT NONE
+   ! NOTE_avoid_public_variables_if_possible
+
+   ! function and subroutine
+   PUBLIC :: iom_dom_open                    !< open files composing mpp structure over domain to be used
+   PUBLIC :: iom_dom_read_var                !< read one variable in an mpp structure over domain to be used
+   PUBLIC :: iom_dom_close                   !< close file composing mpp structure over domain
+
+   PRIVATE :: iom_dom__read_var_id           ! read one variable in an mpp structure, given variable id
+   PRIVATE :: iom_dom__read_var_name         ! read one variable in an mpp structure, given variable name
+   PRIVATE :: iom_dom__read_var_value        ! read variable value in an mpp structure
+   PRIVATE :: iom_dom__no_pole_no_overlap    ! do not overlap north fold boundary or east-west boundary
+   PRIVATE :: iom_dom__no_pole_cyclic        ! do not overlap north fold boundary. However uses cyclic east-west boundary
+   PRIVATE :: iom_dom__no_pole_overlap       ! do not overlap north fold boundary. However overlaps east-west boundary
+!   PRIVATE :: iom_dom__pole_no_overlap       ! overlaps north fold boundary. However do not overlap east-west boundary
+!   PRIVATE :: iom_dom__pole_cyclic           ! overlaps north fold boundary and uses cyclic east-west boundary
+!   PRIVATE :: iom_dom__pole_overlap          ! overlaps north fold boundary and east-west boundary
+
+   INTERFACE iom_dom_read_var                   ! read one variable in an mpp structure
+      MODULE PROCEDURE iom_dom__read_var_id     ! given variable id
+      MODULE PROCEDURE iom_dom__read_var_name   ! given variable name 
+   END INTERFACE iom_dom_read_var
+
+CONTAINS
+   !-------------------------------------------------------------------
+   !> @brief This subroutine open files composing mpp structure 
+   !> over domain to be used.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !
+   !> @param[inout] td_mpp mpp structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_dom_open(td_mpp, td_dom, id_perio, id_ew)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP) , INTENT(INOUT) :: td_mpp
+      TYPE(TDOM) , INTENT(IN)    :: td_dom
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_perio
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_ew
+
+      ! local variable
+      ! loop indices
+      !----------------------------------------------------------------
+      ! check if mpp exist
+      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
+
+         CALL logger_error( " IOM DOM OPEN: domain decomposition not define "//&
+         &               " in mpp strcuture "//TRIM(td_mpp%c_name))
+
+      ELSE
+         ! get processor to be used
+         CALL mpp_get_use( td_mpp, td_dom%i_imin, td_dom%i_imax, &
+         &                         td_dom%i_jmin, td_dom%i_jmax )
+
+         CALL iom_mpp_open(td_mpp, id_perio, id_ew)
+
+      ENDIF
+
+   END SUBROUTINE iom_dom_open
+   !-------------------------------------------------------------------
+   !> @brief This subroutine close files composing mpp structure.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !
+   !> @param[in] td_mpp mpp structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_dom_close(td_mpp)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP), INTENT(INOUT) :: td_mpp
+
+      ! loop indices
+      !----------------------------------------------------------------
+
+      CALL iom_mpp_close(td_mpp)
+
+   END SUBROUTINE iom_dom_close
+   !-------------------------------------------------------------------
+   !> @brief This function read variable value in opened mpp files,
+   !> given variable id and domain strcuture.
+   !>
+   !> @details
+   !> Optionally start indices and number of point to be read could be specify.
+   !> as well as East West ovelap of the global domain.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !>
+   !> @param[in] td_mpp    mpp structure
+   !> @param[in] id_varid  variable id
+   !> @param[in] td_dom    domain structure
+   !> @return  variable structure 
+   !-------------------------------------------------------------------
+   TYPE(TVAR) FUNCTION iom_dom__read_var_id(td_mpp, id_varid, td_dom )
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP) , INTENT(IN) :: td_mpp
+      INTEGER(i4), INTENT(IN) :: id_varid
+      TYPE(TDOM) , INTENT(IN) :: td_dom
+
+      ! local variable
+      INTEGER(i4), DIMENSION(1) :: il_ind
+      !----------------------------------------------------------------
+      ! check if mpp exist
+      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
+
+         CALL logger_error( " IOM DOM READ VAR: domain decomposition "//&
+         &  "not define in mpp strcuture "//TRIM(td_mpp%c_name))
+
+      ELSE
+
+         IF( ANY(td_mpp%t_proc(:)%i_id /= 0) )THEN
+            ! look for variable id
+            il_ind(:)=MINLOC( td_mpp%t_proc(1)%t_var(:)%i_id, &
+            &           mask=(td_mpp%t_proc(1)%t_var(:)%i_id==id_varid))
+            IF( il_ind(1) /= 0 )THEN
+
+               iom_dom__read_var_id=var_copy(td_mpp%t_proc(1)%t_var(il_ind(1)))
+
+               !!! read variable value
+               CALL iom_dom__read_var_value(td_mpp, iom_dom__read_var_id, &
+               &                            td_dom)
+
+            ELSE
+               CALL logger_error( &
+               &  " IOM DOM READ VAR: there is no variable with id "//&
+               &  TRIM(fct_str(id_varid))//" in processor/file "//&
+               &  TRIM(td_mpp%t_proc(1)%c_name))
+            ENDIF
+         ELSE
+            CALL logger_error(" IOM DOM READ VAR: can't read variable, mpp "//&
+            &  TRIM(td_mpp%c_name)//" not opened")
+         ENDIF
+
+      ENDIF
+
+   END FUNCTION iom_dom__read_var_id
+   !-------------------------------------------------------------------
+   !> @brief This function read variable value in opened mpp files, 
+   !> given variable name or standard name, and domain structure.
+   !>
+   !> @details
+   !> Optionally start indices and number of point to be read could be specify.
+   !> as well as East West ovelap of the global domain.
+   !>
+   !> look first for variable name. If it doesn't
+   !> exist in file, look for variable standard name.<br/>
+   !> If variable name is not present, check variable standard name.<br/>
+   !
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !
+   !> @param[in] td_mpp    mpp structure
+   !> @param[in] cd_name   variable name
+   !> @param[in] td_dom    domain structure
+   !> @return  variable structure 
+   !-------------------------------------------------------------------
+   TYPE(TVAR) FUNCTION iom_dom__read_var_name(td_mpp, cd_name, td_dom )
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP),       INTENT(IN) :: td_mpp
+      CHARACTER(LEN=*), INTENT(IN) :: cd_name
+      TYPE(TDOM)      , INTENT(IN) :: td_dom
+
+      ! local variable
+      INTEGER(i4)       :: il_ind
+
+      !----------------------------------------------------------------
+      ! check if mpp exist
+      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
+
+         CALL logger_error( " IOM DOM READ VAR: domain decomposition not define "//&
+         &               " in mpp strcuture "//TRIM(td_mpp%c_name))
+
+      ELSE
+
+            il_ind=var_get_index( td_mpp%t_proc(1)%t_var(:), cd_name)
+            IF( il_ind /= 0 )THEN
+
+               iom_dom__read_var_name=var_copy(td_mpp%t_proc(1)%t_var(il_ind))
+
+               !!! read variable value
+               CALL iom_dom__read_var_value( td_mpp, &
+               &                             iom_dom__read_var_name, &
+               &                             td_dom )
+
+            ELSE
+
+               CALL logger_error( &
+               &  " IOM DOM READ VAR: there is no variable with "//&
+               &  "name or standard name"//TRIM(cd_name)//&
+               &  " in processor/file "//TRIM(td_mpp%t_proc(1)%c_name))
+            ENDIF
+
+      ENDIF
+ 
+   END FUNCTION iom_dom__read_var_name
+   !-------------------------------------------------------------------
+   !> @brief This subroutine read variable value
+   !> in an mpp structure, given domain structure.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !>
+   !> @todo
+   !> - handle north fold
+   !>
+   !> @param[in] td_mpp    mpp structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dom    domain structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_dom__read_var_value(td_mpp, td_var, td_dom )
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP),   INTENT(IN)    :: td_mpp
+      TYPE(TVAR),   INTENT(INOUT) :: td_var
+      TYPE(TDOM),   INTENT(IN)    :: td_dom
+
+      ! local variable
+      INTEGER(i4)                       :: il_status
+
+      TYPE(TATT)                        :: tl_att
+      TYPE(TMPP)                        :: tl_mpp
+      TYPE(TDOM)                        :: tl_dom
+
+      ! loop indices
+      INTEGER(i4)                       :: jk
+      !----------------------------------------------------------------
+
+      CALL logger_debug(" IOM DOM READ VAR VALUE: name "//&
+      &  TRIM(td_var%c_name)//" "//TRIM(td_var%c_point) )
+      CALL logger_debug(" IOM DOM READ VAR VALUE: ndim "//&
+      &  TRIM(fct_str(td_var%i_ndim)) )
+
+      ! copy mpp structure
+      tl_mpp=mpp_copy(td_mpp)
+      ! forced to keep same id
+      tl_mpp%t_proc(:)%i_id=td_mpp%t_proc(:)%i_id         
+
+      ! Allocate space to hold variable value in structure
+      IF( ASSOCIATED(td_var%d_value) )THEN
+         DEALLOCATE(td_var%d_value)   
+      ENDIF
+      
+      ! copy domain structure
+      tl_dom=dom_copy(td_dom)
+      DO jk=1,ip_maxdim
+         IF( .NOT. td_var%t_dim(jk)%l_use ) tl_dom%t_dim(jk)%i_len = 1
+      ENDDO
+
+      ! use domain dimension 
+      td_var%t_dim(1:2)%i_len=tl_dom%t_dim(1:2)%i_len
+
+      ALLOCATE(td_var%d_value( tl_dom%t_dim(1)%i_len, &
+      &                        tl_dom%t_dim(2)%i_len, &
+      &                        td_var%t_dim(3)%i_len, &
+      &                        td_var%t_dim(4)%i_len),&
+      &        stat=il_status)
+      IF(il_status /= 0 )THEN
+
+        CALL logger_error( &
+         &  " IOM DOM READ VAR VALUE: not enough space to put variable "//&
+         &  TRIM(td_var%c_name)//&
+         &  " in variable structure")
+
+      ENDIF
+      CALL logger_debug("IOM DOM READ VAR VALUE: shape ("//&
+      &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=1)))//","//&
+      &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=2)))//","//&
+      &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=3)))//","//&
+      &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=4)))//")" )         
+      ! FillValue by default
+      td_var%d_value(:,:,:,:)=td_var%d_fill
+
+      IF( tl_dom%i_perio0 < 3 .OR. &
+      &   tl_dom%i_jmax /= tl_dom%t_dim0(2)%i_len )THEN
+      ! no north pole
+
+         IF( (tl_dom%i_perio0 == 1 .OR. &
+         &    tl_dom%i_perio0 == 4 .OR. &
+         &    tl_dom%i_perio0 == 6) .AND. &
+         &   tl_dom%i_imin == 1 .AND. &
+         &   tl_dom%i_imax == tl_dom%t_dim0(1)%i_len )THEN
+         ! east west cyclic
+
+            CALL iom_dom__no_pole_cyclic(tl_mpp, td_var, tl_dom)
+
+         ELSEIF( tl_dom%i_imin <= tl_dom%i_imax )THEN
+         ! no east west overlap
+            
+            CALL iom_dom__no_pole_no_overlap(tl_mpp, td_var, tl_dom)
+
+            ! no more EW overlap in variable
+            td_var%i_ew=-1
+
+         ELSEIF( (tl_dom%i_perio0 == 1 .OR. &
+         &        tl_dom%i_perio0 == 4 .OR. &
+         &        tl_dom%i_perio0 == 6) .AND. &
+         &       tl_dom%i_imin > tl_dom%i_imax )THEN
+         ! east west overlap
+
+            CALL iom_dom__no_pole_overlap(tl_mpp, td_var, tl_dom)
+
+            ! no more EW overlap in variable
+            td_var%i_ew=-1
+
+         ELSE
+
+            CALL logger_fatal(" IOM DOM READ VAR VALUE: invalid domain definition.")
+
+         ENDIF
+
+      ELSE ! tl_dom%i_jmax == tl_dom%t_dim0(2)%i_len
+         ! north pole
+
+         CALL logger_error("IOM DOM READ VAR VALUE: "//&
+         &                 TRIM(fct_str(tl_dom%i_jmin))//" "//&
+         &                 TRIM(fct_str(tl_dom%i_jmax)) )
+         CALL logger_fatal("IOM DOM READ VAR VALUE: siren is not able to "//&
+         &                 "use north pole now, maybe in the next release")
+      !   IF( tl_dom%i_imin < tl_dom%i_imax )THEN
+      !   ! no east west overlap
+
+      !      CALL iom_dom__pole_no_overlap(tl_mpp, td_var, tl_dom)
+
+      !   ELSEIF(tl_dom%i_imin == tl_dom%i_imax)THEN
+      !   ! east west cyclic
+
+      !      CALL iom_dom__pole_cyclic(tl_mpp, td_var, tl_dom)
+
+      !    ELSE ! tl_dom%i_imin > tl_dom%i_imax
+      !    ! east west overlap
+
+      !      CALL iom_dom__pole_overlap(tl_mpp, td_var, tl_dom)
+
+      !   ENDIF
+      ENDIF
+
+      ! clean 
+      CALL mpp_clean(tl_mpp)
+      CALL dom_clean(tl_dom)
+
+      IF( td_var%t_dim(1)%l_use .AND. &
+      &   td_var%t_dim(1)%i_len == td_mpp%t_dim(1)%i_len )THEN
+         IF( td_mpp%i_ew >= 0 )THEN
+            tl_att=att_init("ew_overlap",td_mpp%i_ew)
+            CALL var_move_att(td_var,tl_att)
+            ! clean
+            CALL att_clean(tl_att)
+         ENDIF
+      ENDIF
+
+      ! force to change _FillValue to avoid mistake 
+      ! with dummy zero _FillValue
+      IF( td_var%d_fill == 0._dp )THEN
+         CALL var_chg_FillValue(td_var)
+      ENDIF      
+
+   END SUBROUTINE iom_dom__read_var_value
+   !-------------------------------------------------------------------
+   !> @brief This subroutine read variable value
+   !> in an mpp structure. 
+   !> @details
+   !> The output domain do not overlap
+   !> north fold boundary or east-west boundary.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !
+   !> @param[in] td_mpp    mpp structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dom    domain structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_dom__no_pole_no_overlap(td_mpp, td_var, td_dom )
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP),  INTENT(IN)    :: td_mpp
+      TYPE(TVAR),  INTENT(INOUT) :: td_var
+      TYPE(TDOM),  INTENT(IN)    :: td_dom
+
+      ! local variable
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count
+
+      TYPE(TDOM)                :: tl_dom
+
+      ! loop indices
+      !----------------------------------------------------------------
+      
+      ! copy domain structure
+      tl_dom=dom_copy(td_dom)
+
+      ! change dimension length if not use
+      IF( .NOT. td_var%t_dim(1)%l_use )THEN 
+         tl_dom%i_imin=1 ; tl_dom%i_imax=1
+      ENDIF
+      IF( .NOT. td_var%t_dim(2)%l_use )THEN 
+         tl_dom%i_jmin=1 ; tl_dom%i_jmax=1
+      ENDIF
+
+      il_start(:)=(/tl_dom%i_imin,tl_dom%i_jmin,1,1/)
+
+      il_count(:)=(/tl_dom%i_imax-tl_dom%i_imin+1, &
+      &             tl_dom%i_jmax-tl_dom%i_jmin+1, &
+      &             td_var%t_dim(3)%i_len, &
+      &             td_var%t_dim(4)%i_len/)
+
+      td_var=iom_mpp_read_var(td_mpp, TRIM(td_var%c_name), &
+      &                       il_start(:), il_count(:) )
+
+      CALL dom_clean(tl_dom)
+
+   END SUBROUTINE iom_dom__no_pole_no_overlap
+   !-------------------------------------------------------------------
+   !> @brief This subroutine read cyclic variable value
+   !> in an mpp structure. 
+   !> @details
+   !> The output domain do not overlap north fold boundary.
+   !> However it uses cyclic east-west boundary.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !>
+   !> @param[in] td_mpp    mpp structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dom    domain structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_dom__no_pole_cyclic(td_mpp, td_var, td_dom )
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP),   INTENT(IN   ) :: td_mpp
+      TYPE(TVAR),   INTENT(INOUT) :: td_var
+      TYPE(TDOM),   INTENT(IN   ) :: td_dom
+
+      ! local variable
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count
+
+      TYPE(TDOM)                :: tl_dom
+
+      ! loop indices
+      !----------------------------------------------------------------
+
+      ! copy domain structure
+      tl_dom=dom_copy(td_dom)
+
+      ! cyclic domain
+      tl_dom%i_imin=1
+      tl_dom%i_imax=tl_dom%t_dim(1)%i_len
+
+      ! change dimension length if not use
+      IF( .NOT. td_var%t_dim(1)%l_use )THEN 
+         tl_dom%i_imin=1 ; tl_dom%i_imax=1
+      ENDIF
+      IF( .NOT. td_var%t_dim(2)%l_use )THEN 
+         tl_dom%i_jmin=1 ; tl_dom%i_jmax=1
+      ENDIF
+
+      il_start(:)=(/tl_dom%i_imin,tl_dom%i_jmin,1,1/)
+
+      il_count(:)=(/tl_dom%i_imax-tl_dom%i_imin+1, &
+      &             tl_dom%i_jmax-tl_dom%i_jmin+1, &
+      &             td_var%t_dim(3)%i_len, &
+      &             td_var%t_dim(4)%i_len /)
+
+      td_var=iom_mpp_read_var(td_mpp, TRIM(td_var%c_name), &
+      &                       il_start(:), il_count(:) )
+
+      ! clean
+      CALL dom_clean(tl_dom)
+
+   END SUBROUTINE iom_dom__no_pole_cyclic
+   !-------------------------------------------------------------------
+   !> @brief This subroutine read East West overlap variable value
+   !> in an mpp structure.
+   !> @details
+   !> The output domain do not overlap north fold boundary. 
+   !> However it overlaps east-west boundary. 
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !>
+   !> @param[in] td_mpp    mpp structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dom    domain structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_dom__no_pole_overlap(td_mpp, td_var, td_dom )
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP),   INTENT(IN)    :: td_mpp
+      TYPE(TVAR),   INTENT(INOUT) :: td_var
+      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
+
+      ! local variable
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count
+
+      INTEGER(i4)               :: il_dim1
+      INTEGER(i4)               :: il_dim2
+
+      TYPE(TVAR)                :: tl_var1
+      TYPE(TVAR)                :: tl_var2
+
+      TYPE(TDOM)                :: tl_dom
+
+      ! loop indices
+      !----------------------------------------------------------------
+
+      ! copy domain structure
+      tl_dom=dom_copy(td_dom)
+
+      ! change dimension length if not use
+      IF( .NOT. td_var%t_dim(1)%l_use )THEN 
+         tl_dom%i_imin=1 ; tl_dom%i_imax=1
+      ENDIF
+      IF( .NOT. td_var%t_dim(2)%l_use )THEN 
+         tl_dom%i_jmin=1 ; tl_dom%i_jmax=1
+      ENDIF
+
+      ! get first part of domain
+      tl_var1=var_copy(td_var)
+      DEALLOCATE(tl_var1%d_value)
+
+      il_start(:)=(/tl_dom%i_imin,tl_dom%i_jmin,1,1/)
+
+      il_dim1 = td_mpp%t_dim(1)%i_len - td_mpp%i_ew - tl_dom%i_imin + 1
+
+      il_count(:)=(/il_dim1, &
+      &             tl_dom%i_jmax-tl_dom%i_jmin+1, &
+      &             td_var%t_dim(3)%i_len, &
+      &             td_var%t_dim(4)%i_len /)
+
+      ! dimension part 1
+      tl_var1%t_dim(:)%i_len=il_count(:)
+
+      ALLOCATE(tl_var1%d_value(tl_var1%t_dim(1)%i_len, &
+      &                        tl_var1%t_dim(2)%i_len, &
+      &                        tl_var1%t_dim(3)%i_len, &
+      &                        tl_var1%t_dim(4)%i_len) )
+
+      tl_var1=iom_mpp_read_var(td_mpp, TRIM(td_var%c_name), &
+      &                        il_start(:), il_count(:) )      
+
+      IF( td_var%t_dim(jp_I)%l_use )THEN
+         ! get second part of domain
+         tl_var2=var_copy(td_var)
+         DEALLOCATE(tl_var2%d_value)
+
+         il_start(:)=(/1,tl_dom%i_jmin,1,1/)
+
+         il_dim2 = tl_dom%i_imax
+
+         il_count(:)=(/il_dim2, &
+         &             tl_dom%i_jmax-tl_dom%i_jmin+1, &
+         &             td_var%t_dim(3)%i_len, &
+         &             td_var%t_dim(4)%i_len /)
+
+         ! dimension part 2
+         tl_var2%t_dim(:)%i_len=il_count(:)
+
+         ALLOCATE(tl_var2%d_value(tl_var2%t_dim(1)%i_len, &
+         &                        tl_var2%t_dim(2)%i_len, &
+         &                        tl_var2%t_dim(3)%i_len, &
+         &                        tl_var2%t_dim(4)%i_len) )
+
+         tl_var2=iom_mpp_read_var(td_mpp, TRIM(td_var%c_name), &
+         &                        il_start(:), il_count(:) ) 
+
+         ! concatenate both part
+         td_var=var_concat(tl_var1, tl_var2, jp_I)
+      
+         ! clean
+         CALL var_clean(tl_var1)
+         CALL var_clean(tl_var2)
+      ELSE
+         td_var=var_copy(tl_var1)
+         ! clean
+         CALL var_clean(tl_var1)
+      ENDIF
+
+      ! clean
+      CALL dom_clean(tl_dom)
+
+   END SUBROUTINE iom_dom__no_pole_overlap
+   !-------------------------------------------------------------------
+   !> @brief This subroutine read north fold variable value
+   !> in an mpp structure. 
+   !> @details
+   !> The output domain overlaps
+   !> north fold boundary. However it do not overlap east-west boundary.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !
+   !> @param[in] td_mpp    mpp structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dom    domain structure
+   !-------------------------------------------------------------------
+!   SUBROUTINE iom_dom__pole_no_overlap(td_mpp, td_var, td_dom )
+!      IMPLICIT NONE
+!      ! Argument      
+!      TYPE(TMPP),   INTENT(IN)    :: td_mpp
+!      TYPE(TVAR),   INTENT(INOUT) :: td_var
+!      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
+!
+!      ! local variable
+!
+!      ! loop indices
+!      !----------------------------------------------------------------
+!
+!   END SUBROUTINE iom_dom__pole_no_overlap
+   !-------------------------------------------------------------------
+   !> @brief This subroutine read semi global variable value
+   !> in an mpp structure. 
+   !> @details
+   !> The output domain overlaps north fold boundary.
+   !> and uses cyclic east-west boundary.
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !
+   !> @param[in] td_mpp    mpp structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dom    domain structure
+   !> @return variable structure completed 
+   !-------------------------------------------------------------------
+!   SUBROUTINE iom_dom__pole_cyclic(td_mpp, td_var, td_dom )
+!      IMPLICIT NONE
+!      ! Argument      
+!      TYPE(TMPP),   INTENT(IN)    :: td_mpp
+!      TYPE(TVAR),   INTENT(INOUT) :: td_var
+!      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
+!
+!      ! local variable
+!
+!      ! loop indices
+!      !----------------------------------------------------------------
+!
+!   END SUBROUTINE iom_dom__pole_cyclic
+   !-------------------------------------------------------------------
+   !> @brief This subroutine read north fold East West overlap variable value
+   !> in an mpp structure. 
+   !> @details
+   !> The output domain overlaps north fold boundary. 
+   !> and east-west boundary. 
+   !>
+   !> @author J.Paul
+   !> - October, 2014- Initial Version
+   !
+   !> @param[in] td_mpp    mpp structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dom    domain structure
+   !> @return variable structure completed 
+   !-------------------------------------------------------------------
+!   SUBROUTINE iom_dom__pole_overlap(td_mpp, td_var, td_dom )
+!      IMPLICIT NONE
+!      ! Argument      
+!      TYPE(TMPP),   INTENT(IN)    :: td_mpp
+!      TYPE(TVAR),   INTENT(INOUT) :: td_var
+!      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
+!
+!      ! local variable
+!
+!      ! loop indices
+!      !----------------------------------------------------------------
+!
+!   END SUBROUTINE iom_dom__pole_overlap
+
+END MODULE iom_dom
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_mpp.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_mpp.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_mpp.f90	(revision 5075)
@@ -6,36 +6,81 @@
 !
 ! DESCRIPTION:
-!> @brief massively parallel processing Input/Output manager :  
-!> Library to read/write mpp files<br/>
+!> @brief This module manage massively parallel processing Input/Output manager.
+!> Library to read/write mpp files.
 !>
 !> @details
-!> 
 !>    to open mpp files (only file to be used (see mpp_get_use) 
 !>    will be open):<br/>
+!> @code
 !>    CALL iom_mpp_open(td_mpp)
+!> @endcode
 !>       - td_mpp is a mpp structure
 !>
 !>    to creates mpp files:<br/>
+!> @code
 !>    CALL iom_mpp_create(td_mpp)
+!> @endcode
 !>       - td_mpp is a mpp structure
 !>
 !>    to write in mpp files :<br/>
+!> @code
 !>    CALL  iom_mpp_write_file(td_mpp)
+!> @endcode
 !>       - td_mpp is a mpp structure
 !>
 !>    to close mpp files:<br/>
+!> @code
 !>    CALL iom_mpp_close(td_mpp)
+!> @endcode
 !>
 !>    to read one variable in an mpp files:<br/>
-!>    - tl_var=iom_mpp_read_var( td_mpp, id_varid, [td_dom,] [ld_border] ) 
-!>    - tl_var=iom_mpp_read_var( td_mpp, [cd_name,] [td_dom,] [ld_border,] [cd_stdname] ) 
+!> @code
+!>    tl_var=iom_mpp_read_var( td_mpp, id_varid, [id_start, id_count] [,id_ew] ) 
+!> @endcode
+!>    or
+!> @code
+!>    tl_var=iom_mpp_read_var( td_mpp, cd_name, [id_start, id_count] [,id_ew] ) 
+!> @endcode
 !>       - td_mpp is a mpp structure
 !>       - id_varid is a variable id
-!>       - td_dom is a domain structure (optional, can't be used with ld_border)
-!>       - ld_border is true if we want to read border of global domain only
-!>       (optional, can't be used with td_dom)
-!>       - cd_name is variable name (optional, cd_name and/or cd_stdname should be specify.)
-!>       - cd_stdname is variable standard name (optional, cd_name and/or cd_stdname should be specify.)
-!>
+!>       - cd_name is variable name or standard name
+!>       - id_start is a integer(4) 1D array of index from which the data 
+!>          values will be read [optional]
+!>       - id_count is a integer(4) 1D array of the number of indices selected
+!>          along each dimension [optional]
+!>       - id_ew East West overlap [optional]
+!>
+!>    to fill variable value in mpp structure:<br/>
+!> @code
+!>    CALL iom_mpp_fill_var(td_mpp, id_varid, [id_start, id_count] [,id_ew] )
+!> @endcode
+!>    or<br/>
+!> @code
+!>    CALL iom_mpp_fill_var(td_mpp, cd_name, [id_start, id_count] [,id_ew] )
+!> @endcode
+!>       - td_mpp is mpp structure
+!>       - id_varid is variable id
+!>       - cd_name is variable name or standard name
+!>       - id_start is a integer(4) 1D array of index from which the data 
+!>          values will be read [optional]
+!>       - id_count is a integer(4) 1D array of the number of indices selected
+!>          along each dimension [optional]
+!>       - id_ew East West overlap [optional]
+!>
+!>    to fill all variable in mpp structure:<br/>
+!> @code
+!>    CALL iom_mpp_fill_var(td_mpp, [id_start, id_count] [,id_ew] )
+!> @endcode
+!>       - td_mpp is mpp structure
+!>       - id_start is a integer(4) 1D array of index from which the data 
+!>          values will be read [optional]
+!>       - id_count is a integer(4) 1D array of the number of indices selected
+!>          along each dimension [optional]
+!>       - id_ew East West overlap
+!>
+!>    to write files composong mpp strucutre:<br/>
+!> @code
+!>    CALL iom_mpp_write_file(td_mpp) 
+!> @endcode
 !>
 !> @author
@@ -43,19 +88,13 @@
 ! REVISION HISTORY:
 !> @date Nov, 2013 - Initial Version
-!
+!>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
-!> - add read var with start and count as in iom
-!> - add iom_mpp_fill_var_value : cf iom_fill_var_value 
-!> - not so easy to use that it should be, have to work on it
-!> - improve mpp init
-!> - improve mpp_get_use
-!> - imporve dom_init
 !----------------------------------------------------------------------
 MODULE iom_mpp
    USE netcdf                          ! nf90 library
+   USE global                          ! global parameter
    USE kind                            ! F90 kind parameter
    USE fct                             ! basic useful function
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE dim                             ! dimension manager
    USE att                             ! attribute manager
@@ -64,41 +103,27 @@
    USE iom                             ! I/O manager
    USE mpp                             ! mpp manager
-   USE dom                             ! domain manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! function and subroutine
-   PUBLIC :: iom_mpp_open                    !< open files composing mpp structure to be used
-   PUBLIC :: iom_mpp_create                  !< creates files composing mpp structure to be used
+   PUBLIC :: iom_mpp_open                    !< open all files composing mpp structure
+   PUBLIC :: iom_mpp_create                  !< creates files composing mpp structure
    PUBLIC :: iom_mpp_close                   !< close file composing mpp structure
    PUBLIC :: iom_mpp_read_var                !< read one variable in an mpp structure
-   PUBLIC :: iom_mpp_fill_var                !< fill variable value in mpp structure
    PUBLIC :: iom_mpp_write_file              !< write mpp structure in files
 
-   PRIVATE :: iom_mpp__read_var_id           !< read one variable in an mpp structure, given variable id
-   PRIVATE :: iom_mpp__read_var_name         !< read one variable in an mpp structure, given variable name
-   PRIVATE :: iom_mpp__read_var_value        !< read variable value in an mpp structure
-   PRIVATE :: iom_mpp__no_pole_no_overlap    !< do not overlap north fold boundary or east-west boundary
-   PRIVATE :: iom_mpp__no_pole_cyclic        !< do not overlap north fold boundary. However uses cyclic east-west boundary
-   PRIVATE :: iom_mpp__no_pole_overlap       !< do not overlap north fold boundary. However overlaps east-west boundary
-!   PRIVATE :: iom_mpp__pole_no_overlap       !< overlaps north fold boundary. However do not overlap east-west boundary
-!   PRIVATE :: iom_mpp__pole_cyclic           !< overlaps north fold boundary and uses cyclic east-west boundary
-!   PRIVATE :: iom_mpp__pole_overlap          !< overlaps north fold boundary and east-west boundary
-
-   INTERFACE iom_mpp_read_var                   !< read one variable in an mpp structure
-      MODULE PROCEDURE iom_mpp__read_var_id     !< given variable id
-      MODULE PROCEDURE iom_mpp__read_var_name   !< given variable name 
+   PRIVATE :: iom_mpp__read_var_id           ! read one variable in an mpp structure, given variable id
+   PRIVATE :: iom_mpp__read_var_name         ! read one variable in an mpp structure, given variable name
+   PRIVATE :: iom_mpp__read_var_value        ! read variable value in an mpp structure
+
+   INTERFACE iom_mpp_read_var                   ! read one variable in an mpp structure
+      MODULE PROCEDURE iom_mpp__read_var_id     ! given variable id
+      MODULE PROCEDURE iom_mpp__read_var_name   ! given variable name 
    END INTERFACE iom_mpp_read_var
 
-   INTERFACE iom_mpp_fill_var                !< fill variable value in an mpp structure
-      MODULE PROCEDURE iom_mpp__fill_var_id   !< given variable id
-      MODULE PROCEDURE iom_mpp__fill_var_name !< given variable name
-      MODULE PROCEDURE iom_mpp__fill_var_all  !< fill all variable
-   END INTERFACE iom_mpp_fill_var
-
 CONTAINS
    !-------------------------------------------------------------------
-   !> @brief This subroutine open files composing mpp structure to be used<br/>
+   !> @brief This subroutine open files composing mpp structure to be used.
+   !> @details
    !> If try to open a file in write mode that did not exist, create it.<br/>
    !> 
@@ -112,13 +137,14 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_mpp : mpp structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_mpp_open(td_mpp)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_mpp mpp structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_mpp_open(td_mpp, id_perio, id_ew)
       IMPLICIT NONE
       ! Argument      
-      TYPE(TMPP), INTENT(INOUT)  :: td_mpp
+      TYPE(TMPP) , INTENT(INOUT)  :: td_mpp
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_perio
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_ew
 
       ! local variable
@@ -135,59 +161,68 @@
 
       ELSE
-         IF( ANY(td_mpp%t_proc(:)%l_use) )THEN
-
-            ! add suffix to mpp name
-            td_mpp%c_name=file_add_suffix( TRIM(td_mpp%c_name), &
-                                         & TRIM(td_mpp%c_type) )
-
-            td_mpp%t_proc(:)%c_type=TRIM(td_mpp%c_type) 
-            IF( td_mpp%i_nproc > 1 )THEN
-               DO ji=1,td_mpp%i_nproc
-                  IF( td_mpp%t_proc(ji)%l_use )THEN
-
+         ! if no processor file selected
+         ! force to open all files 
+         IF( .NOT. ANY( td_mpp%t_proc(:)%l_use ) )THEN
+            td_mpp%t_proc(:)%l_use=.TRUE.
+         ENDIF
+
+         ! add suffix to mpp name
+         td_mpp%c_name=file_add_suffix( TRIM(td_mpp%c_name), &
+                                      & TRIM(td_mpp%c_type) )
+
+         td_mpp%t_proc(:)%c_type=TRIM(td_mpp%c_type) 
+         IF( td_mpp%i_nproc > 1 )THEN
+            DO ji=1,td_mpp%i_nproc
+               IF( td_mpp%t_proc(ji)%l_use )THEN
+
+                  SELECT CASE(TRIM(td_mpp%c_type))
+                  CASE('cdf')
+                     cl_name=TRIM( file_rename(td_mpp%c_name, ji-1) )
+                  CASE('dimg')
                      cl_name=TRIM( file_rename(td_mpp%c_name, ji) )
-                     td_mpp%t_proc(ji)%c_name=TRIM(cl_name)
-
-                     CALL iom_open(td_mpp%t_proc(ji))
-
-                  ENDIF
-               ENDDO
-            ELSE ! td_mpp%i_nproc == 1 
-                  cl_name=TRIM( file_rename(td_mpp%c_name) )
-                  td_mpp%t_proc(1)%c_name=TRIM(cl_name)
-
-                  CALL iom_open(td_mpp%t_proc(1))
-            ENDIF
-
-         ELSE
-
-            IF( ANY(td_mpp%t_proc(:)%l_ctr) )THEN
-
-               CALL logger_warn("IOM MPP OPEN: open file on border")
-               DO ji=1,td_mpp%i_nproc
-                  IF( td_mpp%t_proc(ji)%l_ctr )THEN
-                     CALL iom_open(td_mpp%t_proc(ji))
-                  ENDIF
-               ENDDO
-
-            ELSE
-               CALL logger_error( " IOM MPP OPEN: no processor to be used.")
-               CALL logger_debug( " use mpp_get_use before running iom_mpp_open")
-            ENDIF
-         ENDIF
+                  CASE DEFAULT
+                     CALL logger_fatal("IOM MPP OPEN: can not open file "//&
+                     &  "of type "//TRIM(td_mpp%c_type))
+                  END SELECT
+
+                  td_mpp%t_proc(ji)%c_name=TRIM(cl_name)
+
+                  CALL iom_open(td_mpp%t_proc(ji))
+
+               ENDIF
+            ENDDO
+         ELSE ! td_mpp%i_nproc == 1 
+               cl_name=TRIM( file_rename(td_mpp%c_name) )
+               td_mpp%t_proc(1)%c_name=TRIM(cl_name)
+
+               CALL iom_open(td_mpp%t_proc(1))
+         ENDIF
+
+         IF( PRESENT(id_ew) )THEN
+            td_mpp%i_ew=id_ew
+            ! add east west overlap to each variable
+            DO ji=1,td_mpp%i_nproc
+               WHERE(td_mpp%t_proc(ji)%t_var(:)%t_dim(1)%l_use)
+                  td_mpp%t_proc(ji)%t_var(:)%i_ew=td_mpp%i_ew
+               ENDWHERE
+            ENDDO
+         ENDIF
+
+         IF( PRESENT(id_perio) )THEN
+            td_mpp%i_perio=id_perio
+         ENDIF
+
       ENDIF
 
    END SUBROUTINE iom_mpp_open
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine create files, composing mpp structure to be used,
-   !> in write mode<br/>
+   !> in write mode.
    !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_mpp : mpp structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_mpp mpp structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_mpp_create(td_mpp)
       IMPLICIT NONE
@@ -209,14 +244,12 @@
 
    END SUBROUTINE iom_mpp_create
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine close files composing mpp structure.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp : mpp structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_mpp mpp structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_mpp_close(td_mpp)
       IMPLICIT NONE
@@ -239,35 +272,36 @@
             ENDIF
          ENDDO
+         td_mpp%t_proc(:)%l_use=.FALSE.
       ENDIF
 
    END SUBROUTINE iom_mpp_close
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read variable value in opened mpp files,
-   !> given variable id.</br/>
+   !> given variable id.
    !>
    !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor   
-   !>
-   !
+   !> Optionally start indices and number of point to be read could be specify.
+   !> as well as East West ovelap of the global domain.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp : mpp structure
-   !> @param[in] id_varid : variable id
-   !> @param[in] td_dom : domain structure
-   !> @param[in] ld_border : read only border
+   !> - November, 2013- Initial Version
+   !> @date October, 2014
+   !> - use start and count array instead of domain structure.
+   !>
+   !> @param[in] td_mpp    mpp structure
+   !> @param[in] id_varid  variable id
+   !> @param[in] id_start  index in the variable from which the data values 
+   !> will be read
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom_mpp__read_var_id(td_mpp, id_varid,&
-   &                                        td_dom, ld_border)
+   &                                        id_start, id_count)
       IMPLICIT NONE
       ! Argument      
-      TYPE(TMPP),    INTENT(IN) :: td_mpp
-      INTEGER(i4),   INTENT(IN) :: id_varid
-      TYPE(TDOM) ,   INTENT(IN), OPTIONAL :: td_dom
-      LOGICAL,       INTENT(IN), OPTIONAL :: ld_border
+      TYPE(TMPP),                INTENT(IN) :: td_mpp
+      INTEGER(i4),               INTENT(IN) :: id_varid
+      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_count      
 
       ! local variable
@@ -288,9 +322,9 @@
             IF( il_ind(1) /= 0 )THEN
 
-               iom_mpp__read_var_id=td_mpp%t_proc(1)%t_var(il_ind(1))
+               iom_mpp__read_var_id=var_copy(td_mpp%t_proc(1)%t_var(il_ind(1)))
 
                !!! read variable value
                CALL iom_mpp__read_var_value(td_mpp, iom_mpp__read_var_id, &
-               &                            td_dom, ld_border)
+               &                            id_start, id_count)
 
             ELSE
@@ -308,13 +342,12 @@
 
    END FUNCTION iom_mpp__read_var_id
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read variable value in opened mpp files, 
-   !> given variable name or standard name.</br/>
+   !> given variable name or standard name.
+   !>
    !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor
-   !
-   !> @details
+   !> Optionally start indices and number of point to be read could be specify.
+   !> as well as East West ovelap of the global domain.
+   !>
    !> look first for variable name. If it doesn't
    !> exist in file, look for variable standard name.<br/>
@@ -322,24 +355,26 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp : mpp structure
-   !> @param[in] cd_name : variable name
-   !> @param[in] td_dom : domain structure
-   !> @param[in] ld_border : read only border 
+   !> - November, 2013- Initial Version
+   !> @date October, 2014
+   !> - use start and count array instead of domain structure.
+   !
+   !> @param[in] td_mpp    mpp structure
+   !> @param[in] cd_name   variable name
+   !> @param[in] id_start  index in the variable from which the data values 
+   !> will be read
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom_mpp__read_var_name(td_mpp, cd_name,    &
-   &                                          td_dom, ld_border   )
+   &                                          id_start, id_count )
       IMPLICIT NONE
       ! Argument      
-      TYPE(TMPP),       INTENT(IN) :: td_mpp
-      CHARACTER(LEN=*), INTENT(IN) :: cd_name
-      TYPE(TDOM) ,      INTENT(IN), OPTIONAL :: td_dom
-      LOGICAL,          INTENT(IN), OPTIONAL :: ld_border
+      TYPE(TMPP),                INTENT(IN) :: td_mpp
+      CHARACTER(LEN=*),          INTENT(IN) :: cd_name
+      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_count      
 
       ! local variable
-      INTEGER(i4)       :: il_varid
+      INTEGER(i4)       :: il_ind
       !----------------------------------------------------------------
       ! check if mpp exist
@@ -351,13 +386,13 @@
       ELSE
 
-            il_varid=var_get_id( td_mpp%t_proc(1)%t_var(:), cd_name)
-            IF( il_varid /= 0 )THEN
-
-               iom_mpp__read_var_name=td_mpp%t_proc(1)%t_var(il_varid)
+            il_ind=var_get_index( td_mpp%t_proc(1)%t_var(:), cd_name)
+            IF( il_ind /= 0 )THEN
+
+               iom_mpp__read_var_name=var_copy(td_mpp%t_proc(1)%t_var(il_ind))
 
                !!! read variable value
                CALL iom_mpp__read_var_value( td_mpp, &
                &                             iom_mpp__read_var_name, &
-               &                             td_dom, ld_border)
+               &                             id_start, id_count)
 
             ELSE
@@ -372,174 +407,4 @@
       
    END FUNCTION iom_mpp__read_var_name
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill all variable value in opened mpp files,
-   !> given variable id.</br/>
-   !>
-   !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor   
-   !> 
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_mpp : mpp structure
-   !> @param[in] td_dom : domain structure
-   !> @param[in] ld_border : read only border
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_mpp__fill_var_all(td_mpp, td_dom, ld_border)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TMPP),    INTENT(INOUT) :: td_mpp
-      TYPE(TDOM) ,   INTENT(IN),   OPTIONAL :: td_dom
-      LOGICAL,       INTENT(IN),   OPTIONAL :: ld_border
-
-      ! local variable
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-      ! check if mpp exist
-      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
-
-         CALL logger_error( " IOM MPP FILL VAR : domain decomposition not define "//&
-         &               " in mpp strcuture "//TRIM(td_mpp%c_name))
-
-      ELSE
-
-         DO ji=1,td_mpp%t_proc(1)%i_nvar
-            CALL iom_mpp_fill_var(td_mpp, ji, td_dom, ld_border )
-         ENDDO
-
-      ENDIF
-
-   END SUBROUTINE iom_mpp__fill_var_all
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill variable value in opened mpp files,
-   !> given variable id.</br/>
-   !>
-   !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor   
-   !> 
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_mpp : mpp structure
-   !> @param[in] id_varid : variable id
-   !> @param[in] td_dom : domain structure
-   !> @param[in] ld_border : read only border
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_mpp__fill_var_id(td_mpp, id_varid, td_dom, ld_border)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TMPP),    INTENT(INOUT) :: td_mpp
-      INTEGER(i4),   INTENT(IN)    :: id_varid
-      TYPE(TDOM) ,   INTENT(IN),   OPTIONAL :: td_dom
-      LOGICAL,       INTENT(IN),   OPTIONAL :: ld_border
-
-      ! local variable
-      INTEGER(i4), DIMENSION(1) :: il_ind
-      !----------------------------------------------------------------
-      ! check if mpp exist
-      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
-
-         CALL logger_error( " IOM MPP FILL VAR: domain decomposition not define "//&
-         &               " in mpp strcuture "//TRIM(td_mpp%c_name))
-
-      ELSE
-
-         IF( ANY(td_mpp%t_proc(:)%i_id /= 0) )THEN
-            ! look for variable id
-            il_ind(:)=MINLOC( td_mpp%t_proc(1)%t_var(:)%i_id, &
-            &           mask=(td_mpp%t_proc(1)%t_var(:)%i_id==id_varid))
-            IF( il_ind(1) /= 0 )THEN
-
-               !!! read variable value
-               CALL iom_mpp__read_var_value( td_mpp, &
-               &                     td_mpp%t_proc(1)%t_var(il_ind(1)), &
-               &                     td_dom, ld_border)
-
-            ELSE
-               CALL logger_error( &
-               &  " IOM MPP FILL VAR : there is no variable with id "//&
-               &  TRIM(fct_str(id_varid))//" in processor/file "//&
-               &  TRIM(td_mpp%t_proc(1)%c_name))
-            ENDIF
-         ELSE
-            CALL logger_error(" IOM MPP FILL VAR : can't read variable, mpp "//&
-            &  TRIM(td_mpp%c_name)//" not opened")
-         ENDIF
-
-      ENDIF
-
-   END SUBROUTINE iom_mpp__fill_var_id
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill variable value in opened mpp files, 
-   !> given variable name or standard name.</br/>
-   !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor   
-   !
-   !> @details
-   !> look first for variable name. If it doesn't
-   !> exist in file, look for variable standard name.<br/>
-   !> If variable name is not present, check variable standard name.<br/>
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_mpp : mpp structure
-   !> @param[in] cd_name : variable name or standard name
-   !> @param[in] td_dom : domain structure
-   !> @param[in] ld_border : read only border 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_mpp__fill_var_name(td_mpp, cd_name, td_dom, ld_border )
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TMPP),       INTENT(INOUT) :: td_mpp
-      CHARACTER(LEN=*), INTENT(IN   ) :: cd_name
-      TYPE(TDOM) ,      INTENT(IN   ), OPTIONAL :: td_dom
-      LOGICAL,          INTENT(IN   ), OPTIONAL :: ld_border
-
-      ! local variable
-      INTEGER(i4)       :: il_ind
-      !----------------------------------------------------------------
-      ! check if mpp exist
-      IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
-
-         CALL logger_error( " IOM MPP FILL VAR : domain decomposition not define "//&
-         &               " in mpp strcuture "//TRIM(td_mpp%c_name))
-
-      ELSE
-
-            il_ind=var_get_id( td_mpp%t_proc(1)%t_var(:), cd_name, cd_name)
-            IF( il_ind /= 0 )THEN
-
-               !!! read variable value
-               CALL iom_mpp__read_var_value(td_mpp, &
-               &                    td_mpp%t_proc(1)%t_var(il_ind), &
-               &                    td_dom, ld_border)
-
-            ELSE
-
-               CALL logger_error( &
-               &  " IOM MPP FILL VAR : there is no variable with "//&
-               &  "name or standard name "//TRIM(cd_name)//&
-               &  " in processor/file "//TRIM(td_mpp%t_proc(1)%c_name))
-
-            ENDIF
-
-      ENDIF
-      
-   END SUBROUTINE iom_mpp__fill_var_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine read variable value
@@ -547,28 +412,26 @@
    !>
    !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor
+   !> Optionally start indices and number of point to be read could be specify.
+   !> as well as East West ovelap of the global domain.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp    : mpp structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dom    : domain structure
-   !> @param[in] ld_border : read only border
-   !> @return variable structure completed 
-   !
-   !> @todo
-   !> - modif en fonction dimension de la variable lu pour cas dom
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !> @date October, 2014
+   !> - use start and count array instead of domain structure.
+   !>
+   !> @param[in] td_mpp    mpp structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] id_start  index in the variable from which the data values 
+   !> will be read
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
    SUBROUTINE iom_mpp__read_var_value(td_mpp, td_var, &
-   &                                  td_dom, ld_border )
+   &                                  id_start, id_count )
       IMPLICIT NONE
       ! Argument      
       TYPE(TMPP),   INTENT(IN)    :: td_mpp
       TYPE(TVAR),   INTENT(INOUT) :: td_var
-      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
-      LOGICAL,      INTENT(IN),   OPTIONAL :: ld_border
+      INTEGER(i4), DIMENSION(:), INTENT(IN),   OPTIONAL :: id_start
+      INTEGER(i4), DIMENSION(:), INTENT(IN),   OPTIONAL :: id_count      
 
       ! local variable
@@ -579,9 +442,18 @@
       INTEGER(i4)                       :: il_j1p
       INTEGER(i4)                       :: il_j2p
-
-      LOGICAL                           :: ll_border
+      INTEGER(i4)                       :: il_i1
+      INTEGER(i4)                       :: il_i2
+      INTEGER(i4)                       :: il_j1
+      INTEGER(i4)                       :: il_j2
+
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_start
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_end
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_count      
+
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_strt
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_cnt      
+
+      TYPE(TATT)                        :: tl_att
       TYPE(TVAR)                        :: tl_var
-      TYPE(TMPP)                        :: tl_mpp
-      TYPE(TDOM)                        :: tl_dom
 
       ! loop indices
@@ -589,381 +461,54 @@
       !----------------------------------------------------------------
 
-      ll_border=.FALSE.
-      IF( PRESENT(ld_border) ) ll_border=ld_border
-      ! check td_dom and ld_border optionals parameters...
-      IF( ll_border .AND. PRESENT(td_dom) )THEN
-         CALL logger_error( "IOM MPP READ VAR VALUE: &
-         &                domain and border can't be both specify")
-      ENDIF
-
-      IF( ll_border )THEN
-           
-         ! copy mpp structure
-         tl_mpp=td_mpp
-         ! forced to keep same id
-         tl_mpp%t_proc(:)%i_id=td_mpp%t_proc(:)%i_id
-
-         IF( ALL(td_mpp%t_proc(:)%l_ctr) )THEN
-            CALL logger_warn( "IOM MPP READ VAR VALUE: &
-            &               contour not define. look for it")
-            ! get contour
-            CALL mpp_get_contour( tl_mpp )
-         ENDIF
-         
-         ! Allocate space to hold variable value in structure
-         IF( ASSOCIATED(td_var%d_value) )THEN
-            DEALLOCATE(td_var%d_value)   
-         ENDIF
-
-         DO jk=1,ip_maxdim
-            IF( .NOT. td_var%t_dim(jk)%l_use ) tl_mpp%t_dim(jk)%i_len = 1
-         ENDDO
-  
-         ! use mpp global dimension 
-         td_var%t_dim(:)%i_len=tl_mpp%t_dim(:)%i_len
-
-         ALLOCATE(td_var%d_value( td_var%t_dim(1)%i_len, &
-         &                        td_var%t_dim(2)%i_len, &
-         &                        td_var%t_dim(3)%i_len, &
-         &                        td_var%t_dim(4)%i_len),&
-         &        stat=il_status)
-         IF(il_status /= 0 )THEN
-
-           CALL logger_error( &
-            &  " IOM MPP READ VAR VALUE: not enough space to put variable "//&
-            &  TRIM(td_var%c_name)//&
-            &  " in variable structure")
-
-         ENDIF
-
-         ! read border processor
-         DO jk=1,tl_mpp%i_nproc
-            IF( tl_mpp%t_proc(jk)%l_ctr )THEN
-                
-               CALL logger_debug(" IOM MPP READ VAR VALUE: name "//TRIM(td_var%c_name) )
-               CALL logger_debug(" IOM MPP READ VAR VALUE: ndim "//TRIM(fct_str(td_var%i_ndim)) )
-               tl_var=iom_read_var( tl_mpp%t_proc(jk), td_var%c_name )
-
-               ! get processor indices
-               il_ind(:)=mpp_get_proc_index( tl_mpp, jk )
-               il_i1p = il_ind(1)
-               il_i2p = il_ind(2)
-               il_j1p = il_ind(3)
-               il_j2p = il_ind(4)
-
-               IF( .NOT. td_var%t_dim(1)%l_use )THEN
-                  il_i1p=1 
-                  il_i2p=1 
-               ENDIF
-
-               IF( .NOT. td_var%t_dim(2)%l_use )THEN
-                  il_j1p=1 
-                  il_j2p=1 
-               ENDIF
-
-               ! replace value in mpp domain
-               td_var%d_value(il_i1p:il_i2p,il_j1p:il_j2p,:,:) = &
-               &  tl_var%d_value(:,:,:,:)
-
-               ! clean variable
-               CALL var_clean(tl_var)
-            ENDIF
-         ENDDO
-
-      ENDIF
-
-      IF( PRESENT(td_dom) )THEN
-
-         ! copy mpp structure
-         tl_mpp=td_mpp
-         ! forced to keep same id
-         tl_mpp%t_proc(:)%i_id=td_mpp%t_proc(:)%i_id         
-
-         IF( ALL(.NOT. td_mpp%t_proc(:)%l_use) )THEN
-            CALL logger_warn( "IOM MPP READ VAR VALUE: &
-            &               processor to be used not defined. look for it")
-            ! get processor to be used
-            CALL mpp_get_use( tl_mpp, td_dom )
-         ENDIF
-
-         ! Allocate space to hold variable value in structure
-         IF( ASSOCIATED(td_var%d_value) )THEN
-            DEALLOCATE(td_var%d_value)   
-         ENDIF
-         
-         tl_dom=td_dom
-         DO jk=1,ip_maxdim
-            IF( .NOT. td_var%t_dim(jk)%l_use ) tl_dom%t_dim(jk)%i_len = 1
-         ENDDO
-
-         ! use domain dimension 
-         td_var%t_dim(1:2)%i_len=tl_dom%t_dim(1:2)%i_len
-
-         ALLOCATE(td_var%d_value( tl_dom%t_dim(1)%i_len, &
-         &                        tl_dom%t_dim(2)%i_len, &
-         &                        td_var%t_dim(3)%i_len, &
-         &                        td_var%t_dim(4)%i_len),&
-         &        stat=il_status)
-         IF(il_status /= 0 )THEN
-
-           CALL logger_error( &
-            &  " IOM MPP READ VAR VALUE: not enough space to put variable "//&
-            &  TRIM(td_var%c_name)//&
-            &  " in variable structure")
-
-         ENDIF
-         CALL logger_debug("IOM MPP READ VAR VALUE: shape ("//&
-         &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=1)))//","//&
-         &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=2)))//","//&
-         &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=3)))//","//&
-         &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=4)))//")" )         
-         ! FillValue by default
-         td_var%d_value(:,:,:,:)=td_var%d_fill
-
-         IF( tl_dom%i_jmin < tl_dom%i_jmax )THEN
-         ! no north pole
-
-            IF( tl_dom%i_imin == 1 .AND. &
-            &   tl_dom%i_imax == tl_dom%t_dim0(1)%i_len )THEN
-            ! east west cyclic
-
-               CALL iom_mpp__no_pole_cyclic(tl_mpp, td_var, tl_dom)
-
-            ELSEIF( tl_dom%i_imin < tl_dom%i_imax )THEN
-            ! no east west overlap
-               
-               CALL iom_mpp__no_pole_no_overlap(tl_mpp, td_var, tl_dom)
-
-               ! no more EW overlap in variable
-               td_var%i_ew=-1
-
-            ELSEIF( tl_dom%i_imin > tl_dom%i_imax )THEN
-            ! east west overlap
-
-               CALL iom_mpp__no_pole_overlap(tl_mpp, td_var, tl_dom)
-
-               ! no more EW overlap in variable
-               td_var%i_ew=-1
-
-            ELSE
-
-               CALL logger_error(" IOM MPP READ VAR VALUE: invalid domain definition.")
-
-            ENDIF
-
-         ELSE ! tl_dom%i_jmin >= tl_dom%i_jmax
-         ! north pole
-
-         CALL logger_error("IOM MPP READ VAR VALUE: siren is not able to do so now "//&
-         &  "maybe in the next release")
-         !   IF( tl_dom%i_imin < tl_dom%i_imax )THEN
-         !   ! no east west overlap
-
-         !      CALL iom_mpp__pole_no_overlap(tl_mpp, td_var, tl_dom)
-
-         !   ELSEIF(tl_dom%i_imin == tl_dom%i_imax)THEN
-         !   ! east west cyclic
-
-         !      CALL iom_mpp__pole_cyclic(tl_mpp, td_var, tl_dom)
-
-         !    ELSE ! tl_dom%i_imin > tl_dom%i_imax
-         !    ! east west overlap
-
-         !      CALL iom_mpp__pole_overlap(tl_mpp, td_var, tl_dom)
-
-         !   ENDIF
-         ENDIF
-
-      ENDIF
-
-      ! force to change _FillValue to avoid mistake 
-      ! with dummy zero _FillValue
-      IF( td_var%d_fill == 0._dp )THEN
-         CALL var_chg_FillValue(td_var)
-      ENDIF      
-
-   END SUBROUTINE iom_mpp__read_var_value
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine read variable value
-   !> in an mpp structure. The output domain do not overlap
-   !> north fold boundary or east-west boundary.
-   !>
-   !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp    : mpp structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dom    : domain structure
-   !> @return variable structure completed 
-   !
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_mpp__no_pole_no_overlap(td_mpp, td_var, td_dom )
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TMPP),  INTENT(IN)    :: td_mpp
-      TYPE(TVAR),  INTENT(INOUT) :: td_var
-      TYPE(TDOM),  INTENT(IN),   OPTIONAL :: td_dom
-
-      ! local variable
-      INTEGER(i4), DIMENSION(4) :: il_ind
-      INTEGER(i4)               :: il_i1p
-      INTEGER(i4)               :: il_j1p
-      INTEGER(i4)               :: il_i2p
-      INTEGER(i4)               :: il_j2p
-
-      INTEGER(i4)               :: il_i1
-      INTEGER(i4)               :: il_j1
-      INTEGER(i4)               :: il_i2
-      INTEGER(i4)               :: il_j2
-
-      INTEGER(i4), DIMENSION(4) :: il_start
-      INTEGER(i4), DIMENSION(4) :: il_count
-      TYPE(TVAR)                :: tl_var
-      TYPE(TDOM)                :: tl_dom
-
-      ! loop indices
-      INTEGER(i4) :: jk
-      !----------------------------------------------------------------
-      
-      ! change dimension length if not use
-      tl_dom=td_dom
-      IF( .NOT. td_var%t_dim(1)%l_use )THEN 
-         tl_dom%i_imin=1 ; tl_dom%i_imax=1
-      ENDIF
-      IF( .NOT. td_var%t_dim(2)%l_use )THEN 
-         tl_dom%i_jmin=1 ; tl_dom%i_jmax=1
-      ENDIF
-!      IF( .NOT. td_var%t_dim(3)%l_use )THEN 
-!         tl_dom%i_kmin=1 ; tl_dom%i_kmax=1
-!      ENDIF
-!      IF( .NOT. td_var%t_dim(4)%l_use )THEN 
-!         tl_dom%i_lmin=1 ; tl_dom%i_lmax=1
-!      ENDIF
-
-      ! read processor 
-      DO jk=1,td_mpp%i_nproc
-         IF( td_mpp%t_proc(jk)%l_use )THEN
-
-            ! get processor indices
-            il_ind(:)=mpp_get_proc_index( td_mpp, jk )
-            il_i1p = il_ind(1)
-            il_i2p = il_ind(2)
-            il_j1p = il_ind(3)
-            il_j2p = il_ind(4)
-
-            IF( .NOT. td_var%t_dim(1)%l_use )THEN
-               il_i1p=tl_dom%i_imin ; il_i2p=tl_dom%i_imax
-            ENDIF
-            IF( .NOT. td_var%t_dim(2)%l_use )THEN
-               il_j1p=tl_dom%i_jmin ; il_j2p=tl_dom%i_jmax
-            ENDIF
-
-            il_i1=MAX(il_i1p, tl_dom%i_imin)
-            il_i2=MIN(il_i2p, tl_dom%i_imax)
-
-            il_j1=MAX(il_j1p, tl_dom%i_jmin)
-            il_j2=MIN(il_j2p, tl_dom%i_jmax)
-
-            IF( (il_i1<=il_i2).AND.(il_j1<=il_j2) )THEN
-
-               il_start(:)=(/ il_i1-il_i1p+1, &
-               &              il_j1-il_j1p+1, &
-               &              1,1 /)
-!               &              tl_dom%i_kmin,  &
-!               &              tl_dom%i_lmin /)
-
-               il_count(:)=(/ il_i2-il_i1+1,         &
-               &              il_j2-il_j1+1,         &
-               &              td_var%t_dim(3)%i_len, &
-               &              td_var%t_dim(4)%i_len /)
-!               &              tl_dom%t_dim(3)%i_len, &
-!               &              tl_dom%t_dim(4)%i_len /)
-
-               tl_var=iom_read_var( td_mpp%t_proc(jk), td_var%c_name,&
-               &                    il_start(:), il_count(:) )
-
-               ! replace value in output variable structure
-               td_var%d_value( il_i1 - tl_dom%i_imin + 1 : &
-               &               il_i2 - tl_dom%i_imin + 1, &
-               &               il_j1 - tl_dom%i_jmin + 1 : &
-               &               il_j2 - tl_dom%i_jmin + 1, &
-               &               :,:) = tl_var%d_value(:,:,:,:)
-
-            ENDIF
-
-         ENDIF
+      il_start(:)=1
+      IF( PRESENT(id_start) ) il_start(:)=id_start(:)
+
+      il_count(:)=td_mpp%t_dim(:)%i_len
+      IF( PRESENT(id_count) ) il_count(:)=id_count(:)
+
+      DO jk=1,ip_maxdim
+         IF( .NOT. td_var%t_dim(jk)%l_use )THEN
+            il_start(jk) = 1
+            il_count(jk) = 1
+         ENDIF
+
+         il_end(jk)=il_start(jk)+il_count(jk)-1
       ENDDO
 
-   END SUBROUTINE iom_mpp__no_pole_no_overlap
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine read variable value
-   !> in an mpp structure. The output domain do not overlap north fold boundary.
-   !> However it uses cyclic east-west boundary.
-   !>
-   !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp    : mpp structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dom    : domain structure
-   !> @return variable structure completed 
-   !
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_mpp__no_pole_cyclic(td_mpp, td_var, td_dom )
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TMPP),   INTENT(IN   ) :: td_mpp
-      TYPE(TVAR),   INTENT(INOUT) :: td_var
-      TYPE(TDOM),   INTENT(IN   ), OPTIONAL :: td_dom
-
-      ! local variable
-      INTEGER(i4), DIMENSION(4) :: il_ind
-      INTEGER(i4)               :: il_i1p
-      INTEGER(i4)               :: il_j1p
-      INTEGER(i4)               :: il_i2p
-      INTEGER(i4)               :: il_j2p
-
-      INTEGER(i4)               :: il_i1
-      INTEGER(i4)               :: il_j1
-      INTEGER(i4)               :: il_i2
-      INTEGER(i4)               :: il_j2
-
-      INTEGER(i4), DIMENSION(4) :: il_start
-      INTEGER(i4), DIMENSION(4) :: il_count
-      TYPE(TVAR)                :: tl_var
-      TYPE(TDOM)                :: tl_dom
-
-      ! loop indices
-      INTEGER(i4) :: jk
-      !----------------------------------------------------------------
-
-      ! change dimension length if not use
-      tl_dom=td_dom
-      IF( .NOT. td_var%t_dim(1)%l_use )THEN 
-         tl_dom%i_imin=1 ; tl_dom%i_imax=1
-      ENDIF
-      IF( .NOT. td_var%t_dim(2)%l_use )THEN 
-         tl_dom%i_jmin=1 ; tl_dom%i_jmax=1
-      ENDIF
-!      IF( .NOT. td_var%t_dim(3)%l_use )THEN 
-!         tl_dom%i_kmin=1 ; tl_dom%i_kmax=1
-!      ENDIF
-!      IF( .NOT. td_var%t_dim(4)%l_use )THEN 
-!         tl_dom%i_lmin=1 ; tl_dom%i_lmax=1
-!      ENDIF
+
+      IF( ANY(il_end(:) > td_mpp%t_dim(:)%i_len) )THEN
+            CALL logger_fatal("IOM MPP READ VAR VALUE: start + count "//&
+            &                 "exceed dimension bound.")
+      ENDIF
+
+      ! use domain dimension 
+      td_var%t_dim(:)%i_len=il_count(:)
+
+      ! Allocate space to hold variable value in structure
+      IF( ASSOCIATED(td_var%d_value) )THEN
+         DEALLOCATE(td_var%d_value)   
+      ENDIF
+
+      ALLOCATE(td_var%d_value( il_count(1), &
+      &                        il_count(2), &
+      &                        il_count(3), &
+      &                        il_count(4)),&
+      &        stat=il_status)
+      IF(il_status /= 0 )THEN
+
+        CALL logger_error( &
+         &  " IOM MPP READ VAR VALUE: not enough space to put variable "//&
+         &  TRIM(td_var%c_name)//&
+         &  " in variable structure")
+
+      ENDIF
+
+      CALL logger_debug("IOM MPP READ VAR VALUE: shape ("//&
+      &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=1)))//","//&
+      &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=2)))//","//&
+      &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=3)))//","//&
+      &  TRIM(fct_str(SIZE(td_var%d_value(:,:,:,:),DIM=4)))//")" )
+      ! FillValue by default
+      td_var%d_value(:,:,:,:)=td_var%d_fill
 
       ! read processor 
@@ -977,322 +522,71 @@
             il_j1p = il_ind(3)
             il_j2p = il_ind(4)
-
+ 
             IF( .NOT. td_var%t_dim(1)%l_use )THEN
-               il_i1p=tl_dom%i_imin ; il_i2p=tl_dom%i_imax
+               il_i1p=il_start(1) ; il_i2p=il_end(1)
             ENDIF
             IF( .NOT. td_var%t_dim(2)%l_use )THEN
-               il_j1p=tl_dom%i_jmin ; il_j2p=tl_dom%i_jmax
+               il_j1p=il_start(2) ; il_j2p=il_end(2)
+            ENDIF            
+            
+            il_i1=MAX(il_i1p, il_start(1))
+            il_i2=MIN(il_i2p, il_end(1))
+
+            il_j1=MAX(il_j1p, il_start(2))
+            il_j2=MIN(il_j2p, il_end(2))
+
+            IF( (il_i1<=il_i2).AND.(il_j1<=il_j2) )THEN
+               il_strt(:)=(/ il_i1-il_i1p+1, &
+               &             il_j1-il_j1p+1, &
+               &             1,1 /)
+
+               il_cnt(:)=(/ il_i2-il_i1+1,         &
+               &            il_j2-il_j1+1,         &
+               &            td_var%t_dim(3)%i_len, &
+               &            td_var%t_dim(4)%i_len /)
+
+               tl_var=iom_read_var( td_mpp%t_proc(jk), td_var%c_name,&
+               &                    il_strt(:), il_cnt(:) )
+               ! replace value in output variable structure
+               td_var%d_value( il_i1 - il_start(1) + 1 : &
+               &               il_i2 - il_start(1) + 1,  &
+               &               il_j1 - il_start(2) + 1 : &
+               &               il_j2 - il_start(2) + 1,  &
+               &               :,:) = tl_var%d_value(:,:,:,:)
+
+               ! clean
+               CALL var_clean(tl_var)
             ENDIF
 
-            il_i1=il_i1p
-            il_j1=MAX(il_j1p, td_dom%i_jmin)
-
-            il_i2=il_i2p
-            il_j2=MIN(il_j2p, td_dom%i_jmax)
-
-            IF( (il_i1<=il_i2).AND.(il_j1<=il_j2) )THEN
-
-               il_start(:)=(/ il_i1,          &
-               &              il_j1-il_j1p+1, &
-               &              1,1 /)
-!               &              tl_dom%i_kmin,  &
-!               &              tl_dom%i_lmin /)
-
-               il_count(:)=(/ il_i2-il_i1+1,         &
-               &              il_j2-il_j1+1,         &
-               &              td_var%t_dim(3)%i_len, &
-               &              td_var%t_dim(4)%i_len /)
-!               &              tl_dom%t_dim(3)%i_len, &
-!               &              tl_dom%t_dim(4)%i_len /)
-
-               tl_var=iom_read_var( td_mpp%t_proc(jk), td_var%c_name,&
-               &                    il_start(:), il_count(:) )
-
-               ! replace value in output variable structure
-               td_var%d_value( il_i1 : il_i2,  &
-               &               il_j1 - td_dom%i_jmin + 1 : &
-               &               il_j2 - td_dom%i_jmin + 1,  &
-               &               :,:) = tl_var%d_value(:,:,:,:)
-
-            ENDIF
-
          ENDIF
       ENDDO
 
-   END SUBROUTINE iom_mpp__no_pole_cyclic
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine read variable value
-   !> in an mpp structure. The output domain do not overlap north fold boundary. 
-   !> However it overlaps east-west boundary. 
-   !>
+      IF( td_var%t_dim(1)%l_use .AND. &
+      &   td_var%t_dim(1)%i_len == td_mpp%t_dim(1)%i_len )THEN
+         IF( td_mpp%i_ew >= 0 )THEN
+            tl_att=att_init("ew_overlap",td_mpp%i_ew)
+            CALL var_move_att(td_var,tl_att)
+            ! clean 
+            CALL att_clean(tl_att)
+         ENDIF
+      ENDIF
+
+      ! force to change _FillValue to avoid mistake 
+      ! with dummy zero _FillValue
+      IF( td_var%d_fill == 0._dp )THEN
+         CALL var_chg_FillValue(td_var)
+      ENDIF      
+
+   END SUBROUTINE iom_mpp__read_var_value
+   !-------------------------------------------------------------------
+   !> @brief This subroutine write files composing mpp structure.
+   !
    !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp    : mpp structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dom    : domain structure
-   !> @return variable structure completed 
-   !
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_mpp__no_pole_overlap(td_mpp, td_var, td_dom )
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TMPP),   INTENT(IN)    :: td_mpp
-      TYPE(TVAR),   INTENT(INOUT) :: td_var
-      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
-
-      ! local variable
-      INTEGER(i4), DIMENSION(4) :: il_ind
-      INTEGER(i4)               :: il_i1p
-      INTEGER(i4)               :: il_j1p
-      INTEGER(i4)               :: il_i2p
-      INTEGER(i4)               :: il_j2p
-
-      INTEGER(i4)               :: il_i1
-      INTEGER(i4)               :: il_j1
-      INTEGER(i4)               :: il_i2
-      INTEGER(i4)               :: il_j2
-
-      INTEGER(i4)               :: il_ioffset
-
-      INTEGER(i4), DIMENSION(4) :: il_start
-      INTEGER(i4), DIMENSION(4) :: il_count
-      TYPE(TVAR)                :: tl_var
-      TYPE(TDOM)                :: tl_dom
-
-      ! loop indices
-      INTEGER(i4) :: jk
-      !----------------------------------------------------------------
-
-      il_ioffset  = (td_mpp%t_dim(1)%i_len-2) - td_dom%i_imin + 1
-
-      ! change dimension length if not use
-      tl_dom=td_dom
-      IF( .NOT. td_var%t_dim(1)%l_use )THEN 
-         tl_dom%i_imin=1 ; tl_dom%i_imax=1
-         il_ioffset=0
-      ENDIF
-      IF( .NOT. td_var%t_dim(2)%l_use )THEN 
-         tl_dom%i_jmin=1 ; tl_dom%i_jmax=1
-      ENDIF
-!      IF( .NOT. td_var%t_dim(3)%l_use )THEN 
-!         tl_dom%i_kmin=1 ; tl_dom%i_kmax=1
-!      ENDIF
-!      IF( .NOT. td_var%t_dim(4)%l_use )THEN 
-!         tl_dom%i_lmin=1 ; tl_dom%i_lmax=1
-!      ENDIF
-
-      ! read processor 
-      DO jk=1,td_mpp%i_nproc
-         IF( td_mpp%t_proc(jk)%l_use )THEN
-             
-            ! get processor indices
-            il_ind(:)=mpp_get_proc_index( td_mpp, jk )
-            il_i1p = il_ind(1)
-            il_i2p = il_ind(2)
-            il_j1p = il_ind(3)
-            il_j2p = il_ind(4)
-
-            IF( .NOT. td_var%t_dim(1)%l_use )THEN
-               il_i1p=tl_dom%i_imin ; il_i2p=tl_dom%i_imax
-            ENDIF
-            IF( .NOT. td_var%t_dim(2)%l_use )THEN
-               il_j1p=tl_dom%i_jmin ; il_j2p=tl_dom%i_jmax
-            ENDIF
-            
-            !!!!!! get first part of domain
-            il_i1=MAX(il_i1p, td_dom%i_imin)
-            il_j1=MAX(il_j1p, td_dom%i_jmin)
-
-            il_i2=MIN(il_i2p, td_mpp%t_dim(1)%i_len-td_var%i_ew) ! east-west overlap
-            il_j2=MIN(il_j2p, td_dom%i_jmax)
-
-            IF( (il_i1<=il_i2).AND.(il_j1<=il_j2) )THEN
-
-               il_start(:)=(/ il_i1-il_i1p+1, &
-               &              il_j1-il_j1p+1, &
-               &              1,1 /)
-!               &              tl_dom%i_kmin,  &
-!               &              tl_dom%i_lmin /)
-
-               il_count(:)=(/ il_i2-il_i1+1,         &
-               &              il_j2-il_j1+1,         &
-               &              td_var%t_dim(3)%i_len, &
-               &              td_var%t_dim(4)%i_len /)
-!               &              tl_dom%t_dim(3)%i_len, &
-!               &              tl_dom%t_dim(4)%i_len /)
-
-               tl_var=iom_read_var( td_mpp%t_proc(jk), td_var%c_name,&
-               &                    il_start(:), il_count(:) )
-
-               ! replace value in output variable structure
-               td_var%d_value( il_i1 - td_dom%i_imin + 1 : &
-               &               il_i2 - td_dom%i_imin + 1,  &
-               &               il_j1 - td_dom%i_jmin + 1 : &
-               &               il_j2 - td_dom%i_jmin + 1,  &
-               &               :,:) = tl_var%d_value(:,:,:,:)
-
-            ENDIF
-
-            !!!!! get second part of domain
-            il_i1=MAX(il_i1p, 1)
-            il_j1=MAX(il_j1p, td_dom%i_jmin)
-
-            il_i2=MIN(il_i2p, td_dom%i_imax)
-            il_j2=MIN(il_j2p, td_dom%i_jmax)
-
-            IF( (il_i1<=il_i2).AND.(il_j1<=il_j2) )THEN
-
-               il_start(:)=(/ il_i1,          &
-               &              il_j1-il_j1p+1, &
-               &              1,1 /)
-!               &              tl_dom%i_kmin,  &
-!               &              tl_dom%i_lmin /)
-
-               il_count(:)=(/ il_i2-il_i1+1,         &
-               &              il_j2-il_j1+1,         &
-               &              td_var%t_dim(3)%i_len, &
-               &              td_var%t_dim(4)%i_len /)
-!               &              tl_dom%t_dim(3)%i_len, &
-!               &              tl_dom%t_dim(4)%i_len /)
-
-               tl_var=iom_read_var( td_mpp%t_proc(jk), td_var%c_name,&
-               &                    il_start(:), il_count(:) )
-
-               ! replace value in output variable structure
-               td_var%d_value( il_ioffset + il_i1 :  &
-               &               il_ioffset + il_i2,   &
-               &               il_j1 - td_dom%i_jmin + 1 : &
-               &               il_j2 - td_dom%i_jmin + 1,  &
-               &               :,:) = tl_var%d_value(:,:,:,:)
-
-            ENDIF
-
-         ENDIF
-      ENDDO
-
-   END SUBROUTINE iom_mpp__no_pole_overlap
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine read variable value
-   !> in an mpp structure. The output domain overlaps
-   !> north fold boundary. However it do not overlap east-west boundary.
-   !>
-   !> @details
-   !> If domain is given, read only domain.
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp    : mpp structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dom    : domain structure
-   !> @return variable structure completed 
-   !
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
-!   SUBROUTINE iom_mpp__pole_no_overlap(td_mpp, td_var, td_dom )
-!      IMPLICIT NONE
-!      ! Argument      
-!      TYPE(TMPP),   INTENT(IN)    :: td_mpp
-!      TYPE(TVAR),   INTENT(INOUT) :: td_var
-!      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
-!
-!      ! local variable
-!
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END SUBROUTINE iom_mpp__pole_no_overlap
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine read variable value
-   !> in an mpp structure. The output domain overlaps north fold boundary.
-   !> and uses cyclic east-west boundary.
-   !>
-   !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp    : mpp structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dom    : domain structure
-   !> @param[in] ld_border : read only border
-   !> @return variable structure completed 
-   !
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
-!   SUBROUTINE iom_mpp__pole_cyclic(td_mpp, td_var, td_dom )
-!      IMPLICIT NONE
-!      ! Argument      
-!      TYPE(TMPP),   INTENT(IN)    :: td_mpp
-!      TYPE(TVAR),   INTENT(INOUT) :: td_var
-!      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
-!
-!      ! local variable
-!
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END SUBROUTINE iom_mpp__pole_cyclic
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine read variable value
-   !> in an mpp structure. The output domain overlaps north fold boundary. 
-   !> and east-west boundary. 
-   !>
-   !> @details
-   !> If domain is given, read only domain.
-   !> If border is .TRUE., read only border processor
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp    : mpp structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dom    : domain structure
-   !> @param[in] ld_border : read only border
-   !> @return variable structure completed 
-   !
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
-!   SUBROUTINE iom_mpp__pole_overlap(td_mpp, td_var, td_dom )
-!      IMPLICIT NONE
-!      ! Argument      
-!      TYPE(TMPP),   INTENT(IN)    :: td_mpp
-!      TYPE(TVAR),   INTENT(INOUT) :: td_var
-!      TYPE(TDOM),   INTENT(IN),   OPTIONAL :: td_dom
-!
-!      ! local variable
-!
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END SUBROUTINE iom_mpp__pole_overlap
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine write mpp structure in opened files.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_mpp mpp structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_mpp_write_file(td_mpp)
       IMPLICIT NONE
@@ -1300,4 +594,5 @@
       TYPE(TMPP), INTENT(INOUT) :: td_mpp
 
+      ! local variable
       ! loop indices
       INTEGER(i4) :: ji
@@ -1312,4 +607,7 @@
          DO ji=1, td_mpp%i_nproc
             IF( td_mpp%t_proc(ji)%i_id /= 0 )THEN
+               !CALL file_del_att(td_mpp%t_proc(ji), 'periodicity')
+               !CALL file_del_att(td_mpp%t_proc(ji), 'ew_overlap')
+
                CALL iom_write_file(td_mpp%t_proc(ji))
             ELSE
@@ -1320,4 +618,3 @@
       ENDIF
    END SUBROUTINE iom_mpp_write_file
-   !> @endcode
 END MODULE iom_mpp
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_rstdimg.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_rstdimg.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/iom_rstdimg.f90	(revision 5075)
@@ -10,66 +10,73 @@
 !>
 !> @details
-!>
 !>    to open dimg file (create file structure):<br/>
+!> @code
 !>    CALL iom_rstdimg_open(td_file)
+!> @endcode
 !>       - td_file is file structure (see file.f90)
 !>
 !>    to write in dimg file:<br/>
+!> @code
 !>    CALL  iom_rstdimg_write_file(td_file)
+!> @endcode
 !>
 !>    to close dimg file:<br/>
+!> @code
 !>    CALL iom_rstdimg_close(tl_file)
+!> @endcode
 !>
 !>    to read one dimension in dimg file:<br/>
-!>    tl_dim = iom_rstdimg_read_dim(tl_file, id_dimid)<br/>
-!>    or<br/>
+!> @code
+!>    tl_dim = iom_rstdimg_read_dim(tl_file, id_dimid)
+!> @endcode
+!>    or
+!> @code
 !>    tl_dim = iom_rstdimg_read_dim(tl_file, cd_name)
+!> @endcode
 !>       - id_dimid is dimension id<br/>
 !>       - cd_name is dimension name
 !>
-!>    to read one global attribute in dimg file:<br/>
-!>    tl_att = iom_rstdimg_read_att(tl_file, id_varid, id_attid)<br/>
-!>    or<br/>
-!>    tl_att = iom_rstdimg_read_att(tl_file, id_varid, cd_name)
-!>       - id_varid is variable id
-!>       - id_attid is attribute id<br/>
-!>       - cd_name is attribute name
-!>  
 !>    to read one variable in dimg file:<br/>
-!>    tl_var = iom_rstdimg_read_var(td_file, id_varid, [id_start, id_count])<br/>
-!>    or<br/>
-!>    tl_var = iom_rstdimg_read_var(td_file, cd_name, [id_start, [id_count,]] [cd_stdname])
+!> @code
+!>    tl_var = iom_rstdimg_read_var(td_file, id_varid, [id_start, id_count])
+!> @endcode
+!>    or
+!> @code
+!>    tl_var = iom_rstdimg_read_var(td_file, cd_name, [id_start, [id_count]])
+!> @endcode
 !>       - id_varid is variabale id
-!>       - cd_name is variabale name
-!>       - id_start is a integer(4) 1D table of index from which the data 
-!>          values will be read (optional)
-!>       - id_count is a integer(4) 1D table of the number of indices selected
-!>          along each dimension (optional)
-!>       - cd_stdname is variable standard name (optional)
+!>       - cd_name is variabale name or standard name
+!>       - id_start is a integer(4) 1D array of index from which the data 
+!>          values will be read [optional]
+!>       - id_count is a integer(4) 1D array of the number of indices selected
+!>          along each dimension [optional]
+!>
+!>    to get sub domain decomppistion in a dimg file:<br/>
+!> @code
+!>    CALL iom_rstdimg_get_mpp(td_file)
+!> @endcode
 !>
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
-!> @param MyModule_type : brief_description
+!> @date November, 2013 - Initial Version
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!
-!> @todo
 !----------------------------------------------------------------------
 MODULE iom_rstdimg
    USE netcdf                          ! nf90 library
+   USE global                          ! global parameter
    USE kind                            ! F90 kind parameter
    USE fct                             ! basic useful function
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE att                             ! attribute manager
    USE dim                             ! dimension manager
    USE var                             ! variable manager
    USE file                            ! file manager
-   USE dom                             ! domain manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
+
+   ! type and variable
+   PRIVATE ::  im_vnl !< variable name length 
 
    ! function and subroutine
@@ -78,27 +85,24 @@
    PUBLIC :: iom_rstdimg_read_dim    !< read one dimension in an opened dimg file, return variable structure
    PUBLIC :: iom_rstdimg_read_var    !< read one variable  in an opened dimg file, return dimension structure
-   PUBLIC :: iom_rstdimg_fill_var    !< fill variable value in an opened dimg file
    PUBLIC :: iom_rstdimg_write_file  !< write file structure contents in an opened dimg file
    PUBLIC :: iom_rstdimg_get_mpp     !< get sub domain decomppistion in a dimg file
 
-   PRIVATE :: iom_rstdimg__get_info       !< get global information in an opened dimg file
-   PRIVATE :: iom_rstdimg__get_file_var   !< read information about variable on an opened dimg file.
-   PRIVATE :: iom_rstdimg__get_file_var_0d !< put information about scalar variable in file structure
-   PRIVATE :: iom_rstdimg__get_file_var_1d !< put information about variable 1D in file structure
-   PRIVATE :: iom_rstdimg__get_file_var_2d !< put information about variable 2D in file structure
-   PRIVATE :: iom_rstdimg__get_file_var_3d !< put information about variable 3D in file structure
-   PRIVATE :: iom_rstdimg__read_dim_id    !< read dimension structure in an opened dimg file, given variable id.
-   PRIVATE :: iom_rstdimg__read_dim_name  !< read dimension structure in an opened dimg file, given variable name or standard name.
-   PRIVATE :: iom_rstdimg__read_var_id    !< read variable value in an opened dimg file, given variable id.
-   PRIVATE :: iom_rstdimg__read_var_name  !< read variable value in an opened dimg file, given variable name or standard name.
-   PRIVATE :: iom_rstdimg__read_var_value !< read variable value in an opened dimg file, for variable 1,2,3d
-   PRIVATE :: iom_rstdimg__write_header   !< write header in an opened dimg file
-   PRIVATE :: iom_rstdimg__write_var      !< write variables in an opened dimg file 
-   PRIVATE :: iom_rstdimg__fill_var_id    !< fill variable value in an opened dimg file, given variable id
-   PRIVATE :: iom_rstdimg__fill_var_name  !< fill variable value in an opened dimg file, given variable name
-   PRIVATE :: iom_rstdimg__fill_var_all   !< fill all variable value in an opened dimg file
+   PRIVATE :: iom_rstdimg__get_info        ! get global information in an opened dimg file
+   PRIVATE :: iom_rstdimg__get_file_var    ! read information about variable on an opened dimg file.
+   PRIVATE :: iom_rstdimg__get_file_var_0d ! put information about scalar variable in file structure
+   PRIVATE :: iom_rstdimg__get_file_var_1d ! put information about variable 1D in file structure
+   PRIVATE :: iom_rstdimg__get_file_var_2d ! put information about variable 2D in file structure
+   PRIVATE :: iom_rstdimg__get_file_var_3d ! put information about variable 3D in file structure
+   PRIVATE :: iom_rstdimg__read_dim_id     ! read dimension structure in an opened dimg file, given variable id.
+   PRIVATE :: iom_rstdimg__read_dim_name   ! read dimension structure in an opened dimg file, given variable name or standard name.
+   PRIVATE :: iom_rstdimg__read_var_id     ! read variable value in an opened dimg file, given variable id.
+   PRIVATE :: iom_rstdimg__read_var_name   ! read variable value in an opened dimg file, given variable name or standard name.
+   PRIVATE :: iom_rstdimg__read_var_value  ! read variable value in an opened dimg file, for variable 1,2,3d
+   PRIVATE :: iom_rstdimg__get_rec         ! compute record number before writing file
+   PRIVATE :: iom_rstdimg__write_header    ! write header in an opened dimg file
+   PRIVATE :: iom_rstdimg__write_var       ! write variables in an opened dimg file 
 
    ! module variable
-   INTEGER(i4), PARAMETER :: ip_vnl = 32 ! variable name length
+   INTEGER(i4), PARAMETER :: im_vnl = 32 ! variable name length
 
    INTERFACE iom_rstdimg_read_dim
@@ -112,13 +116,8 @@
    END INTERFACE iom_rstdimg_read_var
 
-   INTERFACE iom_rstdimg_fill_var
-      MODULE PROCEDURE iom_rstdimg__fill_var_id
-      MODULE PROCEDURE iom_rstdimg__fill_var_name
-      MODULE PROCEDURE iom_rstdimg__fill_var_all
-   END INTERFACE iom_rstdimg_fill_var   
-
 CONTAINS
    !-------------------------------------------------------------------
-   !> @brief This subroutine open a dimg file in read or write mode<br/>
+   !> @brief This subroutine open a dimg file in read or write mode.
+   !> @details
    !> if try to open a file in write mode that did not exist, create it.<br/>
    !> if file already exist, get information about:
@@ -128,12 +127,12 @@
    !> - the ID of the unlimited dimension
    !> - the file format
-   !> and finally read dimensions.
+   !> Finally it read dimensions, and 'longitude' variable to compute East-West
+   !> overlap.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg_open(td_file)
       IMPLICIT NONE
@@ -146,6 +145,4 @@
 
       INTEGER(i4)       :: il_status
-      
-      TYPE(TVAR)        :: tl_lon
       !----------------------------------------------------------------
 
@@ -180,5 +177,4 @@
             ENDIF
 
-
          ENDIF
 
@@ -224,5 +220,4 @@
             ENDIF
 
-
             IF( .NOT. td_file%l_wrt )THEN
 
@@ -240,5 +235,8 @@
                CALL fct_err(il_status)
                IF( il_status /= 0 )THEN
-                  CALL logger_error("OPEN: file "//TRIM(td_file%c_name)&
+                  CALL logger_debug("IOM RSTDIMG OPEN: open staus "//&
+                  &  TRIM(fct_str(il_status)))
+                  CALL logger_fatal("IOM RSTDIMG OPEN: file "//&
+                  &  TRIM(td_file%c_name)&
                   &  //" with record length "//TRIM(fct_str(td_file%i_recl)))
                ENDIF               
@@ -260,5 +258,8 @@
                CALL fct_err(il_status)
                IF( il_status /= 0 )THEN
-                  CALL logger_error("OPEN: file "//TRIM(td_file%c_name))
+                  CALL logger_debug("IOM RSTDIMG OPEN: open staus "//&
+                  &  TRIM(fct_str(il_status)))
+                  CALL logger_error("IOM RSTDIMG  OPEN: file "//&
+                  & TRIM(td_file%c_name))
                ENDIF        
 
@@ -274,12 +275,4 @@
             CALL iom_rstdimg__get_file_var(td_file)
 
-            ! get ew overlap
-            tl_lon=iom_rstdimg_read_var(td_file,'longitude')
-            td_file%i_ew=dom_get_ew_overlap(tl_lon)
-            WHERE( td_file%t_var(:)%t_dim(1)%l_use )
-               td_file%t_var(:)%i_ew=td_file%i_ew
-            ENDWHERE
-            CALL var_clean(tl_lon) 
-
          ENDIF
 
@@ -287,14 +280,12 @@
 
    END SUBROUTINE iom_rstdimg_open
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine close dimg file
+   !-------------------------------------------------------------------
+   !> @brief This subroutine close dimg file.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg_close(td_file)
       IMPLICIT NONE
@@ -327,21 +318,18 @@
 
    END SUBROUTINE iom_rstdimg_close
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine get global information in an opened dimg 
-   !> file.<br/>
+   !> file.
    !> @details
    !> It gets the number of variables, the  domain decompistion, 
-   !> the record of the header infos.<br/>
+   !> the record of the header.<br/>
    !> It read dimensions, and add it to dimension structure inside 
    !> file structure.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__get_info(td_file)
       IMPLICIT NONE
@@ -360,5 +348,5 @@
 
       CALL logger_debug( &
-      &  " GET INFO: about dimg file "//TRIM(td_file%c_name))
+      &  " IOM RSTDIMG GET INFO: about dimg file "//TRIM(td_file%c_name))
 
       ! read first record 
@@ -370,9 +358,8 @@
       CALL fct_err(il_status)
       IF( il_status /= 0 )THEN
-         CALL logger_error("GET INFO: read first line of "//TRIM(td_file%c_name))
-      ENDIF
-
-      CALL logger_trace( &
-      &  " GET INFO: about dimg file "//TRIM(td_file%c_name))
+         CALL logger_debug(" READ status: "//TRIM(fct_str(il_status)))
+         CALL logger_fatal("IOM RSTDIMG GET INFO: read first line of "//&
+         &  TRIM(td_file%c_name))
+      ENDIF
 
       td_file%c_type='dimg'
@@ -380,9 +367,9 @@
       ! add dimension to file structure
       tl_dim=dim_init('X', il_nx)
-      CALL file_add_dim(td_file, tl_dim)
+      CALL file_move_dim(td_file, tl_dim)
       tl_dim=dim_init('Y', il_ny)
-      CALL file_add_dim(td_file, tl_dim)
+      CALL file_move_dim(td_file, tl_dim)
       tl_dim=dim_init('Z', il_nz)
-      CALL file_add_dim(td_file, tl_dim)
+      CALL file_move_dim(td_file, tl_dim)
 
       ! reorder dimension to ('x','y','z','t')
@@ -401,17 +388,14 @@
 
    END SUBROUTINE iom_rstdimg__get_info
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine get sub domain decomposition in a dimg file.<br/>
+   !-------------------------------------------------------------------
+   !> @brief This subroutine get sub domain decomposition in a dimg file.
    !> @details
    !> domain decomposition informations are saved in attributes.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @return mpp structure 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg_get_mpp(td_file)
       IMPLICIT NONE
@@ -440,5 +424,6 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace( " GET MPP: dimg file "//TRIM(td_file%c_name))
+      CALL logger_debug( " IOM RSTDIMG GET MPP: dimg file "//&
+      &  TRIM(td_file%c_name))
 
       ! read first record 
@@ -453,22 +438,25 @@
       CALL fct_err(il_status)
       IF( il_status /= 0 )THEN
-         CALL logger_error("GET MPP: read first line of "//TRIM(td_file%c_name))
+         CALL logger_debug(" IOM RSTDIMG GET MPP: read status: "//&
+         &  TRIM(fct_str(il_status)))
+         CALL logger_error(" IOM RSTDIMG GET MPP: read first line of "//&
+         &  TRIM(td_file%c_name))
       ENDIF
 
       ! create attributes to save mpp value
       tl_att=att_init( "DOMAIN_number_total", il_nproc)
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_I_number_total", il_niproc)
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_J_number_total", il_njproc)
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_number", il_area)
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_size_global", (/il_iglo, il_jglo/))
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       ! allocate local variable
@@ -480,6 +468,6 @@
       IF(il_status /= 0 )THEN
 
-         CALL logger_error( " GET MPP: not enough space to put domain &
-         &  decomposition in file "//TRIM(td_file%c_name) )
+         CALL logger_error( " IOM RSTDIMG GET MPP: not enough space to put "//&
+         &  "domain decomposition in file "//TRIM(td_file%c_name) )
 
       ENDIF
@@ -500,39 +488,44 @@
       CALL fct_err(il_status)
       IF( il_status /= 0 )THEN
-         CALL logger_error("GET INFO: read domain decomposition on first &
-         &              line of "//TRIM(td_file%c_name))
+         CALL logger_debug(" IOM RSTDIMG GET MPP: read status: "//&
+         &  TRIM(fct_str(il_status)))
+         CALL logger_fatal("IOM RSTDIMG GET MPP: read domain decomposition "//&
+         &           "on first line of "//TRIM(td_file%c_name))
       ENDIF
 
       tl_att=att_init( "DOMAIN_position_first", (/il_impp(il_area), il_jmpp(il_area)/))
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_position_last", (/il_lci(il_area), il_lcj(il_area)/))
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_halo_size_start", (/il_ldi(il_area), il_ldj(il_area)/))
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_halo_size_end", (/il_lei(il_area), il_lej(il_area)/))
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_I_position_first", il_impp(:) )
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
       tl_att=att_init( "DOMAIN_J_position_first", il_jmpp(:) )
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_I_position_last", il_lci(:) )
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
       tl_att=att_init( "DOMAIN_J_position_last", il_lcj(:) )
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_I_halo_size_start", il_ldi(:) )
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
       tl_att=att_init( "DOMAIN_J_halo_size_start", il_ldj(:) )
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
 
       tl_att=att_init( "DOMAIN_I_halo_size_end", il_lei(:) )
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
       tl_att=att_init( "DOMAIN_J_halo_size_end", il_lej(:) )
-      CALL file_add_att(td_file, tl_att)
+      CALL file_move_att(td_file, tl_att)
+
+      ! clean
+      CALL att_clean(tl_att)
 
       DEALLOCATE( il_impp, il_jmpp,&
@@ -542,18 +535,17 @@
 
    END SUBROUTINE iom_rstdimg_get_mpp
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine read information about variable on an 
-   !> opened dimg file.<br/>
-   !> The variable structure inside file structure is then completed.
+   !> opened dimg file.
+   !> @details
+   !> The variables structures inside file structure are then completed.
+   !> Variables no0d, no1d, no2d, no3d are deleted from file strucutre.
    !> @note variable value are read only for scalar variable (0d).
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__get_file_var(td_file)
       IMPLICIT NONE
@@ -562,5 +554,5 @@
 
       ! local variable
-      CHARACTER(LEN=ip_vnl), DIMENSION(:), ALLOCATABLE :: cl_name
+      CHARACTER(LEN=im_vnl), DIMENSION(:), ALLOCATABLE :: cl_name
 
       REAL(dp)             , DIMENSION(:), ALLOCATABLE :: dl_value
@@ -605,4 +597,5 @@
 
          IF(ASSOCIATED(td_file%t_var))THEN
+            CALL var_clean(td_file%t_var(:))
             DEALLOCATE(td_file%t_var)
          ENDIF
@@ -638,23 +631,20 @@
 
    END SUBROUTINE iom_rstdimg__get_file_var
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine put information about scalar variable 
+   !-------------------------------------------------------------------
+   !> @brief This subroutine put informations about scalar variable 
    !> inside file structure.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name : table of variable name
-   !> @param[in] dd_value : table of variable value
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] cd_name      array of variable name
+   !> @param[in] dd_value     array of variable value
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__get_file_var_0d(td_file, cd_name, dd_value)
       IMPLICIT NONE
       ! Argument      
       TYPE(TFILE),                         INTENT(INOUT) :: td_file
-      CHARACTER(LEN=ip_vnl), DIMENSION(:), INTENT(IN)    :: cd_name
+      CHARACTER(LEN=im_vnl), DIMENSION(:), INTENT(IN)    :: cd_name
       REAL(dp),              DIMENSION(:), INTENT(IN)    :: dd_value
 
@@ -667,5 +657,5 @@
 
       ! define same dimension as in file
-      tl_dim(:)=td_file%t_dim(:)
+      tl_dim(:)=dim_copy(td_file%t_dim(:))
       ! do not use any dimension
       tl_dim(:)%l_use=.FALSE.
@@ -676,5 +666,6 @@
    
          td_file%t_var(ji)=var_init( TRIM(cd_name(ji)), NF90_DOUBLE, &
-         &                           tl_dim(:), id_id=ji, id_rec=1 )
+         &                           tl_dim(:), dd_fill=0._dp,       &
+         &                           id_id=ji, id_rec=1 )
 
          ! get value of scalar
@@ -688,24 +679,24 @@
       ENDDO
 
+      ! clean
+      CALL dim_clean(tl_dim(:))
+
    END SUBROUTINE iom_rstdimg__get_file_var_0d
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine put information about variable 1D 
+   !-------------------------------------------------------------------
+   !> @brief This subroutine put informations about variable 1D 
    !> inside file structure.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name : table of variable name
-   !> @param[in] dd_value : table of variable record
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] cd_name      array of variable name
+   !> @param[in] dd_value     array of variable record
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__get_file_var_1d(td_file, cd_name, dd_value)
       IMPLICIT NONE
       ! Argument      
       TYPE(TFILE),                         INTENT(INOUT) :: td_file
-      CHARACTER(LEN=ip_vnl), DIMENSION(:), INTENT(IN)    :: cd_name
+      CHARACTER(LEN=im_vnl), DIMENSION(:), INTENT(IN)    :: cd_name
       REAL(dp),              DIMENSION(:), INTENT(IN)    :: dd_value
 
@@ -722,5 +713,5 @@
 
          ! define same dimension as in file
-         tl_dim(:)=td_file%t_dim(:)
+         tl_dim(:)=dim_copy(td_file%t_dim(:))
          ! do not use X and Y dimension
          td_file%t_var(ji)%t_dim(1:2)%l_use=.FALSE.
@@ -728,29 +719,29 @@
       
          td_file%t_var(ji)=var_init( TRIM(cd_name(ji)), NF90_DOUBLE, &
-         &                           tl_dim(:), id_id=ji,            &
-         &                           id_rec=INT(dd_value(ji),i4) )
+         &                           tl_dim(:), dd_fill=0._dp,       &
+         &                           id_id=ji, id_rec=INT(dd_value(ji),i4) )
+
+         ! clean
+         CALL dim_clean(tl_dim(:))
 
       ENDDO
 
    END SUBROUTINE iom_rstdimg__get_file_var_1d
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine put information about variable 2D 
+   !-------------------------------------------------------------------
+   !> @brief This subroutine put informations about variable 2D 
    !> inside file structure.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name : table of variable name
-   !> @param[in] dd_value : table of variable record
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] cd_name      array of variable name
+   !> @param[in] dd_value     array of variable record
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__get_file_var_2d(td_file, cd_name, dd_value)
       IMPLICIT NONE
       ! Argument      
       TYPE(TFILE),                         INTENT(INOUT) :: td_file
-      CHARACTER(LEN=ip_vnl), DIMENSION(:), INTENT(IN)    :: cd_name
+      CHARACTER(LEN=im_vnl), DIMENSION(:), INTENT(IN)    :: cd_name
       REAL(dp),              DIMENSION(:), INTENT(IN)    :: dd_value
 
@@ -767,5 +758,5 @@
 
          ! define same dimension as in file
-         tl_dim(:)=td_file%t_dim(:)
+         tl_dim(:)=dim_copy(td_file%t_dim(:))
          ! do not use Z dimension
          tl_dim(3)%l_use=.FALSE.
@@ -773,29 +764,29 @@
 
          td_file%t_var(ji)=var_init( TRIM(cd_name(ji)), NF90_DOUBLE, &
-         &                           tl_dim(:), id_id=ji,            &
-         &                           id_rec=INT(dd_value(ji),i4) )
+         &                           tl_dim(:), dd_fill=0._dp,       &
+         &                           id_id=ji, id_rec=INT(dd_value(ji),i4) )
+
+         ! clean
+         CALL dim_clean(tl_dim(:))
 
       ENDDO
 
    END SUBROUTINE iom_rstdimg__get_file_var_2d
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine put information about variable 3D 
+   !-------------------------------------------------------------------
+   !> @brief This subroutine put informations about variable 3D 
    !> inside file structure.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name : table of variable name
-   !> @param[in] dd_value : table of variable record
-   !> @return file structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !> @param[in] cd_name      array of variable name
+   !> @param[in] dd_value     array of variable record
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__get_file_var_3d(td_file, cd_name, dd_value)
       IMPLICIT NONE
       ! Argument      
       TYPE(TFILE),                         INTENT(INOUT) :: td_file
-      CHARACTER(LEN=ip_vnl), DIMENSION(:), INTENT(IN)    :: cd_name
+      CHARACTER(LEN=im_vnl), DIMENSION(:), INTENT(IN)    :: cd_name
       REAL(dp),              DIMENSION(:), INTENT(IN)    :: dd_value
 
@@ -812,14 +803,16 @@
 
          ! define same dimension as in file
-         tl_dim(:)=td_file%t_dim(:) 
+         tl_dim(:)=dim_copy(td_file%t_dim(:)) 
 
          td_file%t_var(ji)=var_init( TRIM(cd_name(ji)), NF90_DOUBLE, &
-         &                           tl_dim(:), id_id=ji,            &
-         &                           id_rec=INT(dd_value(ji),i4) )
+         &                           tl_dim(:), dd_fill=0._dp,       &
+         &                           id_id=ji, id_rec=INT(dd_value(ji),i4) )
+
+         ! clean
+         CALL dim_clean(tl_dim(:))
 
       ENDDO
 
    END SUBROUTINE iom_rstdimg__get_file_var_3d
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read one dimension in an opened netcdf file, 
@@ -829,9 +822,8 @@
    !> - Nov, 2013- Initial Version
    !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_dimid : dimension id
+   !> @param[in] td_file   file structure
+   !> @param[in] id_dimid  dimension id
    !> @return  dimension structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TDIM) FUNCTION iom_rstdimg__read_dim_id(td_file, id_dimid)
       IMPLICIT NONE
@@ -866,5 +858,4 @@
 
    END FUNCTION iom_rstdimg__read_dim_id
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read one dimension in an opened netcdf file, 
@@ -874,9 +865,8 @@
    !> - Nov, 2013- Initial Version
    !
-   !> @param[in] td_file : file structure
-   !> @param[in] cd_name : dimension name
+   !> @param[in] td_file   file structure
+   !> @param[in] cd_name   dimension name
    !> @return  dimension structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TDIM) FUNCTION iom_rstdimg__read_dim_name(td_file, cd_name)
       IMPLICIT NONE
@@ -909,22 +899,21 @@
 
    END FUNCTION iom_rstdimg__read_dim_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function read variable value in an opened 
-   !> dimg file, given variable id.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
+   !> dimg file, given variable id.
+   !> @details
+   !> Optionaly, start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] id_varid : variable id
-   !> @param[in] id_start : index in the variable from which the data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] id_varid  variable id
+   !> @param[in] id_start  index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom_rstdimg__read_var_id(td_file, id_varid,&
    &                                            id_start, id_count)
@@ -935,9 +924,7 @@
       INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_start
       INTEGER(i4), DIMENSION(:), INTENT(IN), OPTIONAL :: id_count
-      !INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_start
-      !INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_count
 
       ! local variable
-      INTEGER(i4), DIMENSION(1) :: il_ind
+      INTEGER(i4), DIMENSION(1) :: il_varid
       !----------------------------------------------------------------
       ! check if file opened
@@ -950,8 +937,8 @@
 
          ! look for variable id
-         il_ind(:)=MINLOC(td_file%t_var(:)%i_id,mask=(td_file%t_var(:)%i_id==id_varid))
-         IF( il_ind(1) /= 0 )THEN
-
-            iom_rstdimg__read_var_id=td_file%t_var(il_ind(1))
+         il_varid(:)=MINLOC(td_file%t_var(:)%i_id,mask=(td_file%t_var(:)%i_id==id_varid))
+         IF( il_varid(1) /= 0 )THEN
+
+            iom_rstdimg__read_var_id=var_copy(td_file%t_var(il_varid(1)))
 
             IF( iom_rstdimg__read_var_id%i_ndim /= 0 )THEN
@@ -962,5 +949,5 @@
             ELSE
                CALL logger_debug( " READ VAR: variable 0d "//&
-               &               TRIM(td_file%t_var(il_ind(1))%c_name)//&
+               &               TRIM(td_file%t_var(il_varid(1))%c_name)//&
                &               " should be already read ")
             ENDIF            
@@ -974,27 +961,24 @@
       ENDIF
    END FUNCTION iom_rstdimg__read_var_id
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This function read variable value in an opened 
-   !> dimg file, given variable name or standard name.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
+   !> dimg file, given variable name or standard name.
    !> @details
+   !> Optionaly, start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !
    !> look first for variable name. If it doesn't
    !> exist in file, look for variable standard name.<br/>
-   !> If variable name is not present, check variable standard name.<br/>
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] cd_name  : variable name or standard name 
-   !> @param[in] id_start : index in the variable from which the data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[in] cd_name   variable name or standard name 
+   !> @param[in] id_start  index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
+   !> @param[in] id_count  number of indices selected along each dimension
    !> @return  variable structure 
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TVAR) FUNCTION iom_rstdimg__read_var_name(td_file, cd_name,   &
    &                                              id_start, id_count  )
@@ -1005,9 +989,7 @@
       INTEGER(i4),      DIMENSION(:),  INTENT(IN), OPTIONAL :: id_start
       INTEGER(i4),      DIMENSION(:),  INTENT(IN), OPTIONAL :: id_count
-      !INTEGER(i4),      DIMENSION(ip_maxdim),  INTENT(IN), OPTIONAL :: id_start
-      !INTEGER(i4),      DIMENSION(ip_maxdim),  INTENT(IN), OPTIONAL :: id_count
 
       ! local variable
-      INTEGER(i4)       :: il_ind
+      INTEGER(i4)       :: il_varid
       !----------------------------------------------------------------
       ! check if file opened
@@ -1019,10 +1001,10 @@
       ELSE
 
-         il_ind=var_get_id(td_file%t_var(:), cd_name)
-         IF( il_ind /= 0 )THEN
-
-            iom_rstdimg__read_var_name=td_file%t_var(il_ind)
-
-            IF( td_file%t_var(il_ind)%i_ndim /= 0 )THEN
+         il_varid=var_get_index(td_file%t_var(:), cd_name)
+         IF( il_varid /= 0 )THEN
+
+            iom_rstdimg__read_var_name=var_copy(td_file%t_var(il_varid))
+
+            IF( td_file%t_var(il_varid)%i_ndim /= 0 )THEN
                !!! read variable value
                CALL iom_rstdimg__read_var_value( td_file, &
@@ -1031,5 +1013,5 @@
             ELSE
                CALL logger_debug( " READ VAR: variable 0d "//&
-               &               TRIM(td_file%t_var(il_ind)%c_name)//&
+               &               TRIM(td_file%t_var(il_varid)%c_name)//&
                &               " should have been already read ")
             ENDIF
@@ -1047,197 +1029,19 @@
       
    END FUNCTION iom_rstdimg__read_var_name
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill all variable value in an opened 
-   !> dimg file.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_rstdimg__fill_var_all(td_file, id_start, id_count)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TFILE),               INTENT(INOUT) :: td_file
-      INTEGER(i4), DIMENSION(:), INTENT(IN),   OPTIONAL :: id_start
-      INTEGER(i4), DIMENSION(:), INTENT(IN),   OPTIONAL :: id_count
-      !INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL :: id_start
-      !INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL :: id_count
-
-      ! local variable
-
-      ! loop indices
-      INTEGER(i4) :: ji
-      !----------------------------------------------------------------
-      ! check if file opened
-      IF( td_file%i_id == 0 )THEN
-
-         CALL logger_error( &
-         &  " FILL VAR: no id associated to file "//TRIM(td_file%c_name))
-
-      ELSE
-
-         DO ji=1,td_file%i_nvar
-            CALL iom_rstdimg_fill_var(td_file, ji, id_start, id_count)
-         ENDDO
-
-      ENDIF
-   END SUBROUTINE iom_rstdimg__fill_var_all
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill variable value in an opened 
-   !> dimg file, given variable id.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] id_varid : variable id
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_rstdimg__fill_var_id(td_file, id_varid, id_start, id_count)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TFILE),               INTENT(INOUT) :: td_file
-      INTEGER(i4),               INTENT(IN)    :: id_varid
-      INTEGER(i4), DIMENSION(:), INTENT(IN),   OPTIONAL :: id_start
-      INTEGER(i4), DIMENSION(:), INTENT(IN),   OPTIONAL :: id_count
-      !INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL :: id_start
-      !INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL :: id_count
-
-      ! local variable
-      INTEGER(i4), DIMENSION(1) :: il_ind
-      TYPE(TVAR)                :: tl_var
-      !----------------------------------------------------------------
-      ! check if file opened
-      IF( td_file%i_id == 0 )THEN
-
-         CALL logger_error( &
-         &  " FILL VAR: no id associated to file "//TRIM(td_file%c_name))
-
-      ELSE
-
-         ! look for variable id
-         il_ind(:) = MINLOC( td_file%t_var(:)%i_id, &
-         &                   mask=(td_file%t_var(:)%i_id==id_varid))
-         IF( il_ind(1) /= 0 )THEN
-
-            IF( tl_var%i_ndim /= 0 )THEN
-               !!! read variable value
-               CALL iom_rstdimg__read_var_value(td_file, td_file%t_var(il_ind(1)), &
-               &                                id_start, id_count)
-
-            ELSE
-               CALL logger_debug( " FILL VAR: variable 0d "//&
-               &               TRIM(td_file%t_var(il_ind(1))%c_name)//&
-               &               " should be already read ")
-            ENDIF            
-
-         ELSE
-            CALL logger_error( &
-            &  " FILL VAR: there is no variable with id "//&
-            &  TRIM(fct_str(id_varid))//" in file "//TRIM(td_file%c_name))
-         ENDIF
-
-      ENDIF
-   END SUBROUTINE iom_rstdimg__fill_var_id
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine fill variable value in an opened 
-   !> dimg file, given variable name or standard name.</br/>
-   !> start indices and number of indices selected along each dimension 
-   !> could be specify in a 4 dimension table (/'x','y','z','t'/)
-   !
-   !> @details
-   !> look first for variable name. If it doesn't
-   !> exist in file, look for variable standard name.<br/>
-   !> If variable name is not present, check variable standard name.<br/>
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_file : file structure
-   !> @param[in] cd_name  : variable name or standard name
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @return  variable structure 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE iom_rstdimg__fill_var_name(td_file, cd_name, id_start, id_count )
-      IMPLICIT NONE
-      ! Argument 
-      TYPE(TFILE),                    INTENT(INOUT) :: td_file
-      CHARACTER(LEN=*),               INTENT(IN)    :: cd_name
-      INTEGER(i4),      DIMENSION(:), INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4),      DIMENSION(:), INTENT(IN), OPTIONAL :: id_count
-      !INTEGER(i4),      DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_start
-      !INTEGER(i4),      DIMENSION(ip_maxdim), INTENT(IN), OPTIONAL :: id_count
-      !CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
-
-      ! local variable
-      INTEGER(i4)       :: il_ind
-      !----------------------------------------------------------------
-      ! check if file opened
-      IF( td_file%i_id == 0 )THEN
-
-         CALL logger_error( &
-         &  " FILL VAR: no id associated to file "//TRIM(td_file%c_name))
-
-      ELSE
-
-         il_ind=var_get_id(td_file%t_var, cd_name)
-         IF( il_ind /= 0 )THEN
-
-            IF( td_file%t_var(il_ind)%i_ndim /= 0 )THEN
-               !!! read variable value
-               CALL iom_rstdimg__read_var_value( td_file, td_file%t_var(il_ind), &
-               &                                 id_start, id_count)
-
-            ELSE
-               CALL logger_debug( " FILL VAR: variable 0d "//&
-               &               TRIM(td_file%t_var(il_ind)%c_name)//&
-               &               " should have been already read ")
-            ENDIF
-
-         ELSE
-
-            CALL logger_error( &
-            &  " FILL VAR: there is no variable with "//&
-            &  " name or standard name "//TRIM(cd_name)//&
-            &  " in file "//TRIM(td_file%c_name))
-
-         ENDIF
-
-      ENDIF
-      
-   END SUBROUTINE iom_rstdimg__fill_var_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine read variable value in an opened dimg file, for
    !> variable 1,2,3d.
-   !
+   !> @details
+   !> Optionaly,start indices and number of indices selected along each dimension 
+   !> could be specify in a 4 dimension array (/'x','y','z','t'/)
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[inout] td_var : variable structure
-   !> @param[in] id_start : index in the variable from which the data values will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @return variable structure completed 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file structure
+   !> @param[inout] td_var variable structure
+   !> @param[in] id_start  index in the variable from which the data values will be read
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__read_var_value(td_file, td_var, &
    &                                      id_start, id_count )
@@ -1248,6 +1052,4 @@
       INTEGER(i4), DIMENSION(:), INTENT(IN),  OPTIONAL :: id_start
       INTEGER(i4), DIMENSION(:), INTENT(IN),  OPTIONAL :: id_count
-      !INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),  OPTIONAL :: id_start
-      !INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),  OPTIONAL :: id_count
 
       ! local variable
@@ -1273,5 +1075,5 @@
          IF( SIZE(id_start(:)) /= ip_maxdim .OR. &
          &   SIZE(id_count(:)) /= ip_maxdim )THEN
-            CALL logger_error("READ VAR: dimension of table start or count "//&
+            CALL logger_error("READ VAR: dimension of array start or count "//&
             &      " are invalid to read variable "//TRIM(td_var%c_name)//&
             &      " in file "//TRIM(td_file%c_name) )
@@ -1328,5 +1130,5 @@
             &  " READ VAR VALUE: not enough space to put variable "//&
             &  TRIM(td_var%c_name)//&
-            &  " in temporary table")
+            &  " in temporary array")
 
          ENDIF
@@ -1358,5 +1160,5 @@
             ENDIF
          ELSEIF( td_var%t_dim(3)%l_use )THEN
-            ! 1d variable (Z)
+            ! 1D variable (Z)
             READ(td_file%i_id, IOSTAT=il_status, REC=td_var%i_rec ) &
             &  dl_value(:,:,:,:)
@@ -1403,16 +1205,17 @@
 
    END SUBROUTINE iom_rstdimg__read_var_value
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine write file structure in an opened dimg file.
+   !-------------------------------------------------------------------
+   !> @brief This subroutine write dimg file from file structure.
    !
    !> @details
-   !
+   !> dimg file have to be already opened in write mode.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !> @date September, 2014
+   !> - use iom_rstdimg__get_rec
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg_write_file(td_file)
       IMPLICIT NONE
@@ -1421,6 +1224,6 @@
 
       ! local variable
-      INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_attid
+      INTEGER(i4)           :: il_status
+      INTEGER(i4)           :: il_ind
       !----------------------------------------------------------------
       ! check if file opened
@@ -1433,17 +1236,36 @@
          IF( td_file%l_wrt )THEN
 
+            ! check dimension
+            IF( td_file%t_dim(jp_L)%l_use .AND. &
+            &   td_file%t_dim(jp_L)%i_len /= 1 )THEN
+               CALL logger_fatal("WRITE FILE: can not write dimg file with "//&
+               &  " several time step.")
+            ENDIF
+
             ! close and open file with right record length
             CALL iom_rstdimg_close(td_file)
 
+            ! compute record number to be used 
+            ! and add variable no0d, no1d,.. if need be
+            CALL iom_rstdimg__get_rec(td_file)
+
             ! compute record length
-            il_attid=att_get_id(td_file%t_att(:),"DOMAIN_number_total")
-            IF( il_attid /= 0 )THEN
+            il_ind=att_get_index(td_file%t_att(:),"DOMAIN_number_total")
+            IF( il_ind /= 0 )THEN
                td_file%i_recl = MAX( &
                &     td_file%t_dim(1)%i_len * td_file%t_dim(2)%i_len * 8, &
-               &     ( 8 * INT(td_file%t_att(il_attid)%d_value(1)) + 15 ) * 4 )
+               &     ( 8 * INT(td_file%t_att(il_ind)%d_value(1)) + 15 ) * 4 )
             ELSE
                td_file%i_recl = td_file%t_dim(1)%i_len * &
                &                td_file%t_dim(2)%i_len * 8
             ENDIF
+            ! check record length
+            IF( td_file%i_nvar*(im_vnl+dp) > td_file%i_recl )THEN
+               CALL logger_fatal("WRITE FILE: record length is too small. "//&
+               &  " Try to reduce the output number of processor.")
+            ENDIF
+
+            ! get free unit
+            td_file%i_id=fct_getunit()
 
             OPEN( td_file%i_id, FILE=TRIM(td_file%c_name),&
@@ -1456,8 +1278,8 @@
             CALL fct_err(il_status)
             IF( il_status /= 0 )THEN
-               CALL logger_error("REPLACE: file "//TRIM(td_file%c_name)//&
+               CALL logger_error("WRITE FILE: REPLACE file "//TRIM(td_file%c_name)//&
                &  " with record length "//TRIM(fct_str(td_file%i_recl)))
             ELSE
-               CALL logger_debug("REPLACE: file "//TRIM(td_file%c_name)//&
+               CALL logger_debug("WRITE FILE: REPLACE file "//TRIM(td_file%c_name)//&
                &  " with record length "//TRIM(fct_str(td_file%i_recl)))
             ENDIF
@@ -1479,5 +1301,111 @@
 
    END SUBROUTINE iom_rstdimg_write_file
-   !> @endcode
+   !-------------------------------------------------------------------
+   !> @brief This subroutine compute record number to be used.
+   !>
+   !> @details
+   !> Moreover it adds variable no0d, no1d, no2d and no3d if need be.
+   !>
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
+   SUBROUTINE iom_rstdimg__get_rec(td_file)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TFILE), INTENT(INOUT) :: td_file
+
+      ! local variable
+      INTEGER(i4) :: il_rec
+      TYPE(TVAR)  :: tl_var
+
+      INTEGER(i4), DIMENSION(:)    , ALLOCATABLE :: il_tmp1d
+      INTEGER(i4), DIMENSION(:,:)  , ALLOCATABLE :: il_tmp2d
+      INTEGER(i4), DIMENSION(:,:,:), ALLOCATABLE :: il_tmp3d
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      ! add dummy variable if necessary
+      IF( td_file%i_n0d == 0 )THEN
+         ! create var
+         tl_var=var_init('no0d')
+
+         CALL file_add_var( td_file, tl_var )
+      ENDIF
+
+      IF( td_file%i_n1d == 0 )THEN
+         ! create var
+         ALLOCATE( il_tmp1d( td_file%t_dim(3)%i_len ) )
+         il_tmp1d(:)=-1
+
+         tl_var=var_init( 'no1d', il_tmp1d(:)) 
+
+         DEALLOCATE( il_tmp1d )
+
+         CALL file_add_var( td_file, tl_var ) 
+      ENDIF
+ 
+      IF( td_file%i_n2d == 0 )THEN
+         ! create var
+         ALLOCATE( il_tmp2d( td_file%t_dim(1)%i_len, &
+         &                   td_file%t_dim(2)%i_len ) )
+         il_tmp2d(:,:)=-1
+
+         tl_var=var_init('no2d', il_tmp2d(:,:) )
+
+         DEALLOCATE( il_tmp2d )
+
+         CALL file_add_var( td_file, tl_var ) 
+
+      ENDIF
+ 
+      IF( td_file%i_n3d == 0 )THEN
+         ! create var
+         ALLOCATE( il_tmp3d( td_file%t_dim(1)%i_len, &
+         &                   td_file%t_dim(2)%i_len, &
+         &                   td_file%t_dim(3)%i_len ) )
+         il_tmp3d(:,:,:)=-1
+
+         tl_var=var_init('no3d', il_tmp3d(:,:,:) )
+
+         DEALLOCATE( il_tmp3d )
+
+         CALL file_add_var( td_file, tl_var ) 
+      ENDIF
+
+      ! clean
+      CALL var_clean(tl_var)
+
+      il_rec=2
+      DO ji=1,td_file%i_nvar
+         SELECT CASE(td_file%t_var(ji)%i_ndim)
+            CASE(0)
+               IF( INDEX(td_file%t_var(ji)%c_name, 'no0d' ) == 0 )THEN
+                  td_file%t_var(ji)%i_rec=il_rec
+                  il_rec = il_rec  + 0
+               ENDIF
+            CASE(1)
+               IF( INDEX(td_file%t_var(ji)%c_name, 'no1d' ) == 0 )THEN
+                  td_file%t_var(ji)%i_rec=il_rec
+                  il_rec = il_rec  + 1
+               ENDIF
+            CASE(2)
+               IF( INDEX(td_file%t_var(ji)%c_name, 'no2d' ) == 0 )THEN
+                  td_file%t_var(ji)%i_rec=il_rec
+                  il_rec = il_rec  + 1
+               ENDIF
+            CASE(3)
+               IF( INDEX(td_file%t_var(ji)%c_name, 'no3d' ) == 0 )THEN
+                  td_file%t_var(ji)%i_rec=il_rec
+                  il_rec = il_rec  + td_file%t_dim(3)%i_len
+               ENDIF
+         END SELECT
+      ENDDO
+      td_file%i_rhd  = il_rec
+
+      END SUBROUTINE iom_rstdimg__get_rec
    !-------------------------------------------------------------------
    !> @brief This subroutine write header in an opened dimg 
@@ -1485,11 +1413,8 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file structure
-   !> @param[in] td_dim : dimension structure
-   !> @return  dimension id 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_file   file structure
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__write_header(td_file)
       IMPLICIT NONE
@@ -1499,5 +1424,5 @@
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_attid
+      INTEGER(i4) :: il_ind
       INTEGER(i4) :: il_nproc
       INTEGER(i4) :: il_niproc
@@ -1537,20 +1462,20 @@
 
       ! get domain decomposition
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_number_total" )
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_number_total" )
       il_nproc = 1
-      IF( il_attid /= 0 )THEN
-         il_nproc = INT(td_file%t_att(il_attid)%d_value(1))
-      ENDIF
-
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_I_number_total" )
+      IF( il_ind /= 0 )THEN
+         il_nproc = INT(td_file%t_att(il_ind)%d_value(1))
+      ENDIF
+
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_I_number_total" )
       il_niproc = 0
-      IF( il_attid /= 0 )THEN
-         il_niproc = INT(td_file%t_att(il_attid)%d_value(1))
-      ENDIF
-
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_J_number_total" )
+      IF( il_ind /= 0 )THEN
+         il_niproc = INT(td_file%t_att(il_ind)%d_value(1))
+      ENDIF
+
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_J_number_total" )
       il_njproc = 0
-      IF( il_attid /= 0 )THEN
-         il_njproc = INT(td_file%t_att(il_attid)%d_value(1))
+      IF( il_ind /= 0 )THEN
+         il_njproc = INT(td_file%t_att(il_ind)%d_value(1))
       ENDIF
 
@@ -1570,17 +1495,17 @@
       
       ! get domain number
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_number" )
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_number" )
       il_area = 0
-      IF( il_attid /= 0 )THEN
-         il_area = INT(td_file%t_att(il_attid)%d_value(1))
+      IF( il_ind /= 0 )THEN
+         il_area = INT(td_file%t_att(il_ind)%d_value(1))
       ENDIF
 
       ! get domain global size
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_size_global" )
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_size_global" )
       il_iglo = 0
       il_jglo = 0
-      IF( il_attid /= 0 )THEN
-         il_iglo = INT(td_file%t_att(il_attid)%d_value(1))
-         il_jglo = INT(td_file%t_att(il_attid)%d_value(2))
+      IF( il_ind /= 0 )THEN
+         il_iglo = INT(td_file%t_att(il_ind)%d_value(1))
+         il_jglo = INT(td_file%t_att(il_ind)%d_value(2))
       ENDIF
 
@@ -1600,19 +1525,19 @@
       ! allocate local variable
       ALLOCATE( il_impp(il_nproc), il_jmpp(il_nproc),&
-      &         il_lci(il_niproc),  il_lcj(il_njproc), &
-      &         il_ldi(il_niproc),  il_ldj(il_njproc), &
-      &         il_lei(il_niproc),  il_lej(il_njproc) )
+      &         il_lci(il_nproc),  il_lcj(il_nproc), &
+      &         il_ldi(il_nproc),  il_ldj(il_nproc), &
+      &         il_lei(il_nproc),  il_lej(il_nproc) )
 
       ! get domain first poistion
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_I_position_first" )
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_I_position_first" )
       il_impp(:) = 0
-      IF( il_attid /= 0 )THEN
-         il_impp(:) = INT(td_file%t_att(il_attid)%d_value(:))
-      ENDIF
-
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_J_position_first" )
+      IF( il_ind /= 0 )THEN
+         il_impp(:) = INT(td_file%t_att(il_ind)%d_value(:))
+      ENDIF
+
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_J_position_first" )
       il_jmpp(:) = 0
-      IF( il_attid /= 0 )THEN
-         il_jmpp(:) = INT(td_file%t_att(il_attid)%d_value(:))
+      IF( il_ind /= 0 )THEN
+         il_jmpp(:) = INT(td_file%t_att(il_ind)%d_value(:))
       ENDIF
       
@@ -1623,14 +1548,14 @@
 
       ! get domain last poistion
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_I_position_last" )
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_I_position_last" )
       il_lci(:) = 0
-      IF( il_attid /= 0 )THEN
-         il_lci(:) = INT(td_file%t_att(il_attid)%d_value(:))
-      ENDIF
-
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_J_position_last" )
+      IF( il_ind /= 0 )THEN
+         il_lci(:) = INT(td_file%t_att(il_ind)%d_value(:))
+      ENDIF
+
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_J_position_last" )
       il_lcj(:) = 0
-      IF( il_attid /= 0 )THEN
-         il_lcj(:) = INT(td_file%t_att(il_attid)%d_value(:))
+      IF( il_ind /= 0 )THEN
+         il_lcj(:) = INT(td_file%t_att(il_ind)%d_value(:))
       ENDIF
 
@@ -1641,14 +1566,14 @@
 
       ! get halo size start
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_I_halo_size_start" )
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_I_halo_size_start" )
       il_ldi(:) = 0
-      IF( il_attid /= 0 )THEN
-         il_ldi(:) = INT(td_file%t_att(il_attid)%d_value(:))
-      ENDIF
-
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_J_halo_size_start" )
+      IF( il_ind /= 0 )THEN
+         il_ldi(:) = INT(td_file%t_att(il_ind)%d_value(:))
+      ENDIF
+
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_J_halo_size_start" )
       il_ldj(:) = 0
-      IF( il_attid /= 0 )THEN
-         il_ldj(:) = INT(td_file%t_att(il_attid)%d_value(:))
+      IF( il_ind /= 0 )THEN
+         il_ldj(:) = INT(td_file%t_att(il_ind)%d_value(:))
       ENDIF
       
@@ -1659,14 +1584,14 @@
 
       ! get halo size end
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_I_halo_size_end" )
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_I_halo_size_end" )
       il_lei(:) = 0
-      IF( il_attid /= 0 )THEN
-         il_lei(:) = INT(td_file%t_att(il_attid)%d_value(:))
-      ENDIF
-
-      il_attid=att_get_id( td_file%t_att, "DOMAIN_J_halo_size_end" )
+      IF( il_ind /= 0 )THEN
+         il_lei(:) = INT(td_file%t_att(il_ind)%d_value(:))
+      ENDIF
+
+      il_ind=att_get_index( td_file%t_att, "DOMAIN_J_halo_size_end" )
       il_lej(:) = 0
-      IF( il_attid /= 0 )THEN
-         il_lej(:) = INT(td_file%t_att(il_attid)%d_value(:))
+      IF( il_ind /= 0 )THEN
+         il_lej(:) = INT(td_file%t_att(il_ind)%d_value(:))
       ENDIF
 
@@ -1690,8 +1615,8 @@
       &  il_area,                &
       &  il_iglo, il_jglo,       &
-      &  il_impp(:), il_jmpp(:), &
       &  il_lci(:), il_lcj(:),   &
       &  il_ldi(:), il_ldj(:),   &
-      &  il_lei(:), il_lej(:)
+      &  il_lei(:), il_lej(:),   &
+      &  il_impp(:), il_jmpp(:)
 
       DEALLOCATE( il_impp, il_jmpp,&
@@ -1701,14 +1626,12 @@
 
       END SUBROUTINE iom_rstdimg__write_header
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine write variables in an opened dimg file.</br/>
-   !
+   !-------------------------------------------------------------------
+   !> @brief This subroutine write variables in an opened dimg file.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] id_fileid : file id
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] id_fileid file id
+   !-------------------------------------------------------------------
    SUBROUTINE iom_rstdimg__write_var(td_file)
       IMPLICIT NONE
@@ -1718,91 +1641,52 @@
       ! local variable
       INTEGER(i4) :: il_status
-      TYPE(TVAR)  :: tl_var
+      INTEGER(i4) :: il_rec
 
       INTEGER(i4),            DIMENSION(:), ALLOCATABLE :: il_start
       INTEGER(i4),            DIMENSION(:), ALLOCATABLE :: il_count
-      CHARACTER(LEN=ip_vnl),  DIMENSION(:), ALLOCATABLE :: cl_name
+      CHARACTER(LEN=im_vnl),  DIMENSION(:), ALLOCATABLE :: cl_name
       REAL(dp),               DIMENSION(:), ALLOCATABLE :: dl_value
-
-      INTEGER(i4),            DIMENSION(:,:,:,:), ALLOCATABLE :: il_tmp
 
       ! loop indices
       INTEGER(i4) :: ji
+      INTEGER(i4) :: jk
       !----------------------------------------------------------------
-
-      ! add dummy variable if necessary
-      IF( td_file%i_n0d == 0 )THEN
-         ! create var
-         tl_var=var_init('no0d')
-         ! add value
-         ALLOCATE( il_tmp(1,1,1,1) )
-         il_tmp(:,:,:,:)=-1
-         CALL var_add_value(tl_var, il_tmp)
-         DEALLOCATE( il_tmp )
-
-         CALL file_add_var( td_file, tl_var )
-      ENDIF
-
-      IF( td_file%i_n1d == 0 )THEN
-         ! create var
-         tl_var=var_init('no1d')
-         ! add dimension
-         CALL var_add_dim(tl_var, td_file%t_dim(3))
-         ! add value
-         ALLOCATE( il_tmp(1,1,td_file%t_dim(3)%i_len, 1) )
-         il_tmp(:,:,:,:)=-1
-         CALL var_add_value(tl_var, il_tmp)
-         DEALLOCATE( il_tmp )
-
-         CALL file_add_var( td_file, tl_var ) 
-      ENDIF
- 
-      IF( td_file%i_n2d == 0 )THEN
-         ! create var
-         tl_var=var_init('no2d' )
-         ! add dimension
-         CALL var_add_dim(tl_var, td_file%t_dim(1))
-         CALL var_add_dim(tl_var, td_file%t_dim(2))
-         ! add value
-         ALLOCATE( il_tmp( td_file%t_dim(1)%i_len, &
-         &                 td_file%t_dim(2)%i_len, &
-         &                            1,             &
-         &                            1            ) )
-         il_tmp(:,:,:,:)=-1
-         CALL var_add_value(tl_var, il_tmp)
-         DEALLOCATE( il_tmp )
-
-         CALL file_add_var( td_file, tl_var ) 
-      ENDIF
- 
-      IF( td_file%i_n3d == 0 )THEN
-         ! create var
-         tl_var=var_init('no3d' )
-         ! add dimension
-         CALL var_add_dim(tl_var, td_file%t_dim(1))
-         CALL var_add_dim(tl_var, td_file%t_dim(2))
-         CALL var_add_dim(tl_var, td_file%t_dim(3))
-         ! add value
-         ALLOCATE( il_tmp( td_file%t_dim(1)%i_len, &
-         &                 td_file%t_dim(2)%i_len, &
-         &                 td_file%t_dim(3)%i_len, &
-         &                            1            ) )
-         il_tmp(:,:,:,:)=-1
-         CALL var_add_value(tl_var, il_tmp)
-         DEALLOCATE( il_tmp )
-
-         CALL file_add_var( td_file, tl_var ) 
-      ENDIF
 
       ! reform name and record
       ALLOCATE( cl_name(td_file%i_nvar), dl_value(td_file%i_nvar) )
+
       DO ji=1,td_file%i_nvar
+
+         ! change FillValue to 0.
+         CALL var_chg_FillValue(td_file%t_var(ji),0._dp)
+
          cl_name(ji)  = TRIM(td_file%t_var(ji)%c_name)
          dl_value(ji) = REAL(td_file%t_var(ji)%i_rec,dp)
-      ENDDO
-
-      ! special case for 0d
-      DO ji=1,td_file%i_n0d
-         dl_value(ji)=td_file%t_var(ji)%d_value(1,1,1,1)
+         
+         SELECT CASE (TRIM(td_file%t_var(ji)%c_name))
+            CASE('no0d','no1d','no2d','no3d')
+            CASE DEFAULT
+               DO jk=1,td_file%t_var(ji)%t_dim(3)%i_len
+                  SELECT CASE (td_file%t_var(ji)%i_ndim)
+                     CASE(0)
+                        ! special case for 0d, value save in rec
+                        dl_value(ji)=td_file%t_var(ji)%d_value(1,1,1,1)
+                        il_rec = td_file%t_var(ji)%i_rec
+                     CASE(1,2)
+                        il_rec = td_file%t_var(ji)%i_rec
+                     CASE(3)
+                        il_rec = td_file%t_var(ji)%i_rec + jk -1
+                  END SELECT 
+                  WRITE( td_file%i_id, IOSTAT=il_status, REC=il_rec ) &
+                  &  td_file%t_var(ji)%d_value(:,:,jk,1)
+                  CALL fct_err(il_status)
+                  IF( il_status /= 0 )THEN
+                     CALL logger_error("IOM RSTDIMG WRITE VAR: can not "//&
+                     &  "write variable "//TRIM(td_file%t_var(ji)%c_name)//&
+                     &  " in record "//TRIM(fct_str(il_rec)))
+                  ENDIF
+               ENDDO
+            END SELECT
+
       ENDDO
 
@@ -1820,5 +1704,4 @@
       il_start(4) = 1 + il_count(3)
       il_count(4) = il_start(4) - 1 + td_file%i_n3d
- 
 
       WRITE(td_file%i_id, IOSTAT=il_status, REC=td_file%i_rhd )&
@@ -1827,8 +1710,14 @@
       &  cl_name(il_start(3):il_count(3)), dl_value(il_start(3):il_count(3)),&
       &  cl_name(il_start(4):il_count(4)), dl_value(il_start(4):il_count(4))
-
+      CALL fct_err(il_status)
+      IF( il_status /= 0 )THEN
+         CALL logger_error("IOM RSTDIMG WRITE VAR: can not "//&
+         &  "write restart header in record "//TRIM(fct_str(td_file%i_rhd)))
+      ENDIF
+
+      ! clean
+      DEALLOCATE( cl_name, dl_value )
       DEALLOCATE( il_start, il_count )
 
    END SUBROUTINE iom_rstdimg__write_var
-   !> @endcode   
 END MODULE iom_rstdimg
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/kind.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/kind.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/kind.f90	(revision 5075)
@@ -16,12 +16,11 @@
 !>  - add a standard length of character strings
 !
-!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!
 !> @todo
 !> - check i8 max value
+!
+!> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
 !----------------------------------------------------------------------
 MODULE kind
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/logger.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/logger.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/logger.f90	(revision 5075)
@@ -6,6 +6,7 @@
 !
 ! DESCRIPTION:
-!> @brief This module create logger file and inform it depending 
-!>  of verbosity choose between :
+!> @brief This module create logger file and allow to fill it depending of verbosity.
+!> @details
+!> verbosity could be choosen between :
 !>    - trace : Most detailed information.
 !>    - debug : Detailed information on the flow through the system.
@@ -18,82 +19,108 @@
 !>  default verbosity is warning
 !
-!> @details
-!>    If total number of error exceeded maximum number 
-!>    authorized, program stop.
-!>
-!>    to open/create logger file:<br/>
+!> If total number of error exceeded maximum number 
+!> authorized, program stop.
+!>
+!> to open/create logger file:<br/>
+!> @code
 !>    CALL logger_open(cd_file, [cd_verbosity,] [id_loggerid,] [id_maxerror])
-!>       - cd_file is logger file name
-!>       - cd_verbosity is verbosity to be used (optional, default 'warning')
-!>       - id_loggerid is file id (optional, use only to flush)
-!>       - id_maxerror is the mximum number of error authorized before stop program (optional, default 5)
-!>
-!>    to close logger file:<br/>
-!>    CALL logger_close()
-!>
-!>    to write header in logger file:<br/>
-!>    CALL logger_header()
-!>
-!>    to write footer in logger file:<br/>
-!>    CALL logger_footer()
-!>
-!>    to flushing output:<br/>
-!>    CALL logger_flush()
-!>
-!>    to write TRACE message in logger file:<br/>
-!>    CALL logger_trace(cd_msg)
-!>       - cd_msg is TRACE message
-!>
-!>    to write DEBUG message in logger file:<br/>
-!>    CALL logger_debug(cd_msg)
-!>       - cd_msg is DEBUG message
-!>
-!>    to write INFO message in logger file:<br/>
-!>    CALL logger_info(cd_msg)
-!>       - cd_msg is INFO message
-!>
-!>    to write WARNING message in logger file:<br/>
-!>    CALL logger_warn(cd_msg)
-!>       - cd_msg is WARNING message
-!>
-!>    to write ERROR message in logger file:<br/>
-!>    CALL logger_error(cd_msg)
-!>       - cd_msg is ERROR message
-!>
-!>    to write FATAL message in logger file:<br/>
-!>    CALL logger_fatal(cd_msg)
-!>       - cd_msg is FATAL message
-!>
-!>  Examples :<br />
+!> @endcode
+!> - cd_file is logger file name
+!> - cd_verbosity is verbosity to be used [optional, default 'warning']
+!> - id_loggerid is file id [optional, use only to flush]
+!> - id_maxerror is the maximum number of error authorized before program stop [optional, default 5]
+!>
+!> to close logger file:<br/>
+!> @code
+!> CALL logger_close()
+!> @endcode
+!>
+!> to write header in logger file:<br/>
+!> @code
+!> CALL logger_header()
+!> @endcode
+!>
+!> to write footer in logger file:<br/>
+!> @code
+!> CALL logger_footer()
+!> @endcode
+!>
+!> to flushing output:<br/>
+!> @code
+!> CALL logger_flush()
+!> @endcode
+!>
+!> to write TRACE message in logger file:<br/>
+!> @code
+!> CALL logger_trace(cd_msg [,ld_flush])
+!> @endcode
+!>    - cd_msg is TRACE message
+!>    - ld_flush to flush output [optional]
+!>
+!> to write DEBUG message in logger file:<br/>
+!> @code
+!> CALL logger_debug(cd_msg [,ld_flush])
+!> @endcode
+!>    - cd_msg is DEBUG message
+!>    - ld_flush to flush output [optional]
+!>
+!> to write INFO message in logger file:<br/>
+!> @code
+!> CALL logger_info(cd_msg [,ld_flush])
+!> @endcode
+!>    - cd_msg is INFO message
+!>    - ld_flush to flush output [optional]
+!>
+!> to write WARNING message in logger file:<br/>
+!> @code
+!> CALL logger_warn(cd_msg [,ld_flush])
+!> @endcode
+!>    - cd_msg is WARNING message
+!>    - ld_flush to flush output [optional]
+!>
+!> to write ERROR message in logger file:<br/>
+!> @code
+!> CALL logger_error(cd_msg [,ld_flush])
+!> @endcode
+!>    - cd_msg is ERROR message
+!>    - ld_flush to flush output [optional]
+!>
+!> to write FATAL message in logger file:<br/>
+!> @code
+!> CALL logger_fatal(cd_msg)
+!> @endcode
+!>    - cd_msg is FATAL message
+!>
+!> Examples :<br />
+!> @code
 !>   CALL logger_open('loggerfile.txt','info')
 !>
-!>   CALL logger_header()<br />
-!>   CALL logger_info('une petite info')<br />
-!>   CALL logger_debug('une info de debug')<br />
-!>   CALL logger_warn('une info de warning')<br />
-!>   CALL logger_error('une info d erreur')<br />
-!>   CALL logger_footer()<br />
-!>   CALL logger_close()<br />
-!>
-!> !--------------------------------------------------------------------<br />
+!>   CALL logger_header()
+!>   CALL logger_debug('une info de debug')
+!>   CALL logger_info('une info')
+!>   CALL logger_warn('un warning')
+!>   CALL logger_error('une erreur')
+!>   CALL logger_footer()
+!>   CALL logger_close()
+!> @endcode
+!>
+!> @code
 !>   CALL logger_open('loggerfile.txt')
 !>
-!>   CALL logger_header()<br />
-!>   CALL logger_info('une petite info')<br />
-!>   CALL logger_debug('une info de debug')<br />
-!>   CALL logger_warn('une info de warning')<br />
-!>   CALL logger_error('une info d erreur')<br />
-!>   CALL logger_footer()<br />
-!>   CALL logger_close()<br />
+!>   CALL logger_header()
+!>   CALL logger_debug('une info de debug')
+!>   CALL logger_info('une info')
+!>   CALL logger_warn('un warning')
+!>   CALL logger_error('une erreur')
+!>   CALL logger_footer()
+!>   CALL logger_close()
+!> @endcode
 !
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013- Initial Version
+!> @date November, 2013- Initial Version
 !>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!>
-!> @todo
-!> - verifier flush remet pas compteur error à zero
 !----------------------------------------------------------------------
 MODULE logger
@@ -101,31 +128,33 @@
    USE fct                             ! basic useful function
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
-   !PUBLIC :: TLOGGER            ! logger structure
+   PRIVATE :: TLOGGER            !< logger structure
+
+   PRIVATE :: tm_logger          !< logger structure
+   PRIVATE :: im_nverbosity      !< number of log level
+   PRIVATE :: cm_verbosity       !< verbosity array
 
    ! function and subroutine
-   PUBLIC :: logger_open        ! create a log file with given verbosity
-   PUBLIC :: logger_close       ! close log file
-   PUBLIC :: logger_flush       ! flushing output
-   PUBLIC :: logger_header      ! write header on log file
-   PUBLIC :: logger_footer      ! write footer on log file
-   PUBLIC :: logger_trace       ! write trace    message in log file
-   PUBLIC :: logger_debug       ! write debug    message in log file 
-   PUBLIC :: logger_info        ! write info     message in log file
-   PUBLIC :: logger_warn        ! write warning  message in log file
-   PUBLIC :: logger_error       ! write error    message in log file
-   PUBLIC :: logger_fatal       ! write fatal    message in log file, and stop
+   PUBLIC :: logger_open        !< create a log file with given verbosity
+   PUBLIC :: logger_close       !< close log file
+   PUBLIC :: logger_header      !< write header on log file
+   PUBLIC :: logger_footer      !< write footer on log file
+   PUBLIC :: logger_flush       !< flushing output
+   PUBLIC :: logger_trace       !< write trace    message in log file
+   PUBLIC :: logger_debug       !< write debug    message in log file 
+   PUBLIC :: logger_info        !< write info     message in log file
+   PUBLIC :: logger_warn        !< write warning  message in log file
+   PUBLIC :: logger_error       !< write error    message in log file
+   PUBLIC :: logger_fatal       !< write fatal    message in log file, and stop
 
    PRIVATE :: logger__write     ! cut message to get maximum of 80 character by line in log file
 
-   !> @struct TLOG
-   TYPE TLOGGER
+   TYPE TLOGGER   !< logger structure
       INTEGER(i4)       :: i_id = 0                 !< log file id
       CHARACTER(LEN=lc) :: c_name                   !< log file name
       CHARACTER(LEN=lc) :: c_verbosity = "warning"  !< verbosity choose
-      CHARACTER(LEN=lc) :: c_verb = ""              !< table of "verbosities" to used 
+      CHARACTER(LEN=lc) :: c_verb = ""              !< array of "verbosities" to used 
       INTEGER(i4)       :: i_nerror   = 0           !< number of error
       INTEGER(i4)       :: i_nfatal   = 0           !< number of fatal error
@@ -135,5 +164,5 @@
    !  module variable
    INTEGER(i4), PARAMETER :: im_nverbosity=6     !< number of log level
-   CHARACTER(len=*), DIMENSION(im_nverbosity), PARAMETER :: cm_verbosity= & !< verbosity table 
+   CHARACTER(len=*), DIMENSION(im_nverbosity), PARAMETER :: cm_verbosity= & !< verbosity array 
    &               (/ 'trace   ',&
    &                  'debug   ',&
@@ -147,15 +176,19 @@
 CONTAINS
    !-------------------------------------------------------------------
-   !> @brief This subroutine create a log file with given verbosity.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_file : log file name
-   !> @param[in] cd_verbosity : log file verbosity
-   !> @param[in] id_logid : log file id (use to flush)
-   !> @param[in] id_maxerror : maximum number of error
-   !-------------------------------------------------------------------
-   ! @code
+   !> @brief This subroutine create a log file with default verbosity
+   !> ('warning').
+   !> @details
+   !> Optionally verbosity could be change to 
+   !> ('trace','debug','info',warning','error','fatal').<br/>
+   !> Optionally maximum number of error allowed could be change.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_file      log file name
+   !> @param[in] cd_verbosity log file verbosity
+   !> @param[in] id_logid     log file id (use to flush)
+   !> @param[in] id_maxerror  maximum number of error
+   !-------------------------------------------------------------------
    SUBROUTINE logger_open(cd_file, cd_verbosity, id_logid, id_maxerror)
       IMPLICIT NONE
@@ -212,13 +245,10 @@
 
    END SUBROUTINE logger_open
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine close a log file.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !-------------------------------------------------------------------
    SUBROUTINE logger_close()
       IMPLICIT NONE
@@ -227,4 +257,5 @@
       !----------------------------------------------------------------
       IF( tm_logger%i_id /= 0 )THEN
+         tm_logger%i_id = 0
          CLOSE( tm_logger%i_id, &
          &      IOSTAT=il_status)      
@@ -237,13 +268,10 @@
 
    END SUBROUTINE logger_close
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine flushing output into log file.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !-------------------------------------------------------------------
    SUBROUTINE logger_flush()
       IMPLICIT NONE
@@ -260,25 +288,22 @@
 
    END SUBROUTINE logger_flush
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write header on log file.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !-------------------------------------------------------------------
    RECURSIVE SUBROUTINE logger_header()
       IMPLICIT NONE
       ! local variable
-      INTEGER(i4) :: il_status
+      INTEGER(i4)       :: il_status
       !----------------------------------------------------------------
       IF( tm_logger%i_id /= 0 )THEN
          WRITE( tm_logger%i_id,    &
-            &   FMT='(a/a/a)',     &
+            &   FMT='(4(a/))',     &
             &   IOSTAT=il_status ) &
-            &   "--------------------------------------------------", &
-            &   "INIT     : log start with verbosity "//&
-            &   TRIM(tm_logger%c_verbosity), &
+            &   "--------------------------------------------------",&
+            &   "INIT     : verbosity "//TRIM(tm_logger%c_verbosity),&
+            &   "INIT     : max error "//TRIM(fct_str(tm_logger%i_maxerror)), &
             &   "--------------------------------------------------"
          CALL fct_err(il_status)
@@ -290,24 +315,21 @@
 
    END SUBROUTINE logger_header
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write footer on log file.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !-------------------------------------------------------------------
    SUBROUTINE logger_footer()
       IMPLICIT NONE
       ! local variable
-      INTEGER(i4) :: il_status
+      INTEGER(i4)       :: il_status
       !----------------------------------------------------------------
       IF( tm_logger%i_id /= 0 )THEN
          WRITE( tm_logger%i_id,    &
-            &   FMT='(a/a/a/a/a)',     &
+            &   FMT='(4(/a))',     &
             &   IOSTAT=il_status ) &
             &   "--------------------------------------------------",&
-            &   "END      : log ended ",                             &
+            &   "END      : log ended ",              &
             &   "END      : "//TRIM(fct_str(tm_logger%i_nerror))//   &
             &   " ERROR detected ",                                  &
@@ -322,16 +344,15 @@
       ENDIF
    END SUBROUTINE logger_footer
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write trace message on log file.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_msg : message to write
-   !> @param[in] ld_flush : flushing ouput
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> @details
+   !> Optionally you could flush output.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_msg    message to write
+   !> @param[in] ld_flush  flushing ouput
+   !-------------------------------------------------------------------
    SUBROUTINE logger_trace(cd_msg, ld_flush)
       IMPLICIT NONE
@@ -357,16 +378,15 @@
       ENDIF
    END SUBROUTINE logger_trace
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write debug message on log file.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_msg : message to write
-   !> @param[in] ld_flush : flushing ouput
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> @details
+   !> Optionally you could flush output.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_msg    message to write
+   !> @param[in] ld_flush  flushing ouput
+   !-------------------------------------------------------------------
    SUBROUTINE logger_debug(cd_msg, ld_flush)
       IMPLICIT NONE
@@ -392,16 +412,15 @@
       ENDIF
    END SUBROUTINE logger_debug
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write info message on log file.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_msg : message to write
-   !> @param[in] ld_flush : flushing ouput
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> @details
+   !> Optionally you could flush output.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_msg    message to write
+   !> @param[in] ld_flush  flushing ouput
+   !-------------------------------------------------------------------
    SUBROUTINE logger_info(cd_msg, ld_flush)
       IMPLICIT NONE
@@ -427,16 +446,15 @@
       ENDIF
    END SUBROUTINE logger_info
-   ! @endcode    
    !-------------------------------------------------------------------
    !> @brief This subroutine write warning message on log file.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_msg : message to write
-   !> @param[in] ld_flush : flushing ouput
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> @details
+   !> Optionally you could flush output.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_msg    message to write
+   !> @param[in] ld_flush  flushing ouput
+   !-------------------------------------------------------------------
    SUBROUTINE logger_warn(cd_msg, ld_flush)
       IMPLICIT NONE
@@ -462,16 +480,15 @@
       ENDIF
    END SUBROUTINE logger_warn
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write error message on log file.
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_msg : message to write
-   !> @param[in] ld_flush : flushing ouput
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> @details
+   !> Optionally you could flush output.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_msg    message to write
+   !> @param[in] ld_flush  flushing ouput
+   !-------------------------------------------------------------------
    SUBROUTINE logger_error(cd_msg, ld_flush)
       IMPLICIT NONE
@@ -510,5 +527,4 @@
 
    END SUBROUTINE logger_error
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine write fatal error message on log file, 
@@ -516,10 +532,8 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_msg : message to write
-   !
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_msg message to write
+   !-------------------------------------------------------------------
    RECURSIVE SUBROUTINE logger_fatal(cd_msg)
       IMPLICIT NONE
@@ -537,4 +551,5 @@
             CALL logger_close()
 
+            WRITE(*,*) 'FATAL ERROR'
             STOP
          ENDIF
@@ -545,5 +560,4 @@
       ENDIF
    END SUBROUTINE logger_fatal
-   ! @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine cut message to get maximum of 80 character 
@@ -551,10 +565,9 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_verb : verbosity of the message to write
-   !> @param[in] cd_msg : message to write
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_verb   verbosity of the message to write
+   !> @param[in] cd_msg    message to write
+   !-------------------------------------------------------------------
    SUBROUTINE logger__write(cd_verb, cd_msg)
       IMPLICIT NONE
@@ -602,5 +615,4 @@
 
    END SUBROUTINE logger__write
-   ! @endcode   
 END MODULE logger
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/merge_bathy.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/merge_bathy.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/merge_bathy.f90	(revision 5075)
@@ -7,25 +7,121 @@
 !
 ! DESCRIPTION:
+!> @file
 !> @brief 
 !> This program merge bathymetry file at boundaries.
 !>
 !> @details
+!> @section sec1 method
 !> Coarse grid Bathymetry is interpolated on fine grid. 
-!> Then fine Bathymetry and refined coarse bathymetry are merged at boundaries.
-!>
-!> BathyFine= weight * BathyCoarse + (1-weight)*BathyFine
-!>
-!> The weight function used is : 0.5 + 0.5*COS( (pi*dist) / width ) 
-!>
-!> @author
-!> J.Paul
+!> Then fine Bathymetry and refined coarse bathymetry are merged at boundaries.<br/>
+!>    @f[BathyFine= Weight * BathyCoarse + (1-Weight)*BathyFine@f]
+!> The weight function used is :<br/>
+!>       @f[Weight = 0.5 + 0.5*COS( \frac{\pi*dist}{width} )@f]<br/>
+!> with
+!> - dist : number of point to border 
+!> - width : boundary size
+!>
+!> @section sec2 how to
+!>    to merge bathymetry file:<br/>
+!> @code{.sh}
+!>    ./SIREN/bin/merge_bathy merge_bathy.nam
+!> @endcode
+!>    
+!>    merge_bathy.nam comprise 8 namelists:
+!>       - logger namelist (namlog)
+!>       - config namelist (namcfg)
+!>       - coarse grid namelist (namcrs)
+!>       - fine grid namelist (namfin)
+!>       - variable namelist (namvar)
+!>       - nesting namelist (namnst)
+!>       - boundary namelist (nambdy)
+!>       - output namelist (namout)
+!> 
+!>    @note 
+!>       All namelists have to be in file merge_bathy.nam, 
+!>       however variables of those namelists are all optional.
+!>
+!>    * _logger namelist (namlog)_:
+!>       - cn_logfile   : logger filename
+!>       - cn_verbosity : verbosity ('trace','debug','info',
+!>  'warning','error','fatal')
+!>       - in_maxerror  : maximum number of error allowed
+!>
+!>    * _config namelist (namcfg)_:
+!>       - cn_varcfg : variable configuration file (see ./SIREN/cfg/variable.cfg)
+!>
+!>    * _coarse grid namelist (namcrs)_:
+!>       - cn_bathy0 : bathymetry file
+!>       - in_perio0 : NEMO periodicity index (see Model Boundary Condition in
+!> [NEMO documentation](http://www.nemo-ocean.eu/About-NEMO/Reference-manuals))
+!>
+!>    * _fine grid namelist (namfin)_:
+!>       - cn_bathy1 : bathymetry file
+!>       - in_perio1 : NEMO periodicity index
+!>
+!>    * _variable namelist (namvar)_:
+!>       - cn_varinfo : list of variable and extra information about request(s) 
+!>       to be used.<br/>
+!>          each elements of *cn_varinfo* is a string character.<br/>
+!>          it is composed of the variable name follow by ':', 
+!>          then request(s) to be used on this variable.<br/> 
+!>          request could be:
+!>             - interpolation method
+!> 
+!>                requests must be separated by ';'.<br/>
+!>                order of requests does not matter.<br/>
+!>
+!>          informations about available method could be find in 
+!>          @ref interp modules.<br/>
+!>          Example: 'bathymetry: cubic'
+!>          @note 
+!>             If you do not specify a method which is required, 
+!>             default one is apply.
+!>          @warning 
+!>             variable name must be __Bathymetry__ here.
+!>
+!>    * _nesting namelist (namnst)_:
+!>       - in_rhoi  : refinement factor in i-direction
+!>       - in_rhoj  : refinement factor in j-direction
+!>
+!>    * _boundary namelist (nambdy)_:
+!>       - ln_north : use north boundary or not
+!>       - ln_south : use south boundary or not
+!>       - ln_east  : use east  boundary or not
+!>       - ln_west  : use west  boundary or not
+!>       - cn_north : north boundary indices on fine grid<br/>
+!>          *cn_north* is a string character defining boundary
+!>          segmentation.<br/>
+!>          segments are separated by '|'.<br/>
+!>          each segments of the boundary is composed of:
+!>             - orthogonal indice (.ie. for north boundary,
+!>             J-indice where boundary are). 
+!>             - first indice of boundary (I-indice for north boundary) 
+!>             - last  indice of boundary (I-indice for north boundary)<br/>
+!>                indices must be separated by ',' .<br/>
+!>             - optionally, boundary size could be added between '(' and ')' 
+!>             in the first segment defined.
+!>                @note 
+!>                   boundary size is the same for all segments of one boundary.
+!>
+!>          Examples:
+!>             - cn_north='index1,first1,last1(width)'
+!>             - cn_north='index1(width),first1,last1|index2,first2,last2'
+!>       - cn_south : south boundary indices on fine grid<br/>
+!>       - cn_east  : east  boundary indices on fine grid<br/>
+!>       - cn_west  : west  boundary indices on fine grid<br/>
+!>       - ln_oneseg: use only one segment for each boundary or not
+!>
+!>    * _output namelist (namout)_:
+!>       - cn_fileout : merged bathymetry file
+!>
+!> @author J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
+!> @date November, 2013 - Initial Version
+!> @date Sepember, 2014 
+!> - add header for user
+!>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!>
-!> @todo
 !----------------------------------------------------------------------
-!> @code
 PROGRAM merge_bathy
 
@@ -43,5 +139,4 @@
    USE boundary                        ! boundary manager
    USE iom                             ! I/O manager
-   USE dom                             ! domain manager
    USE grid                            ! grid manager
    USE extrap                          ! extrapolation manager
@@ -49,5 +144,7 @@
    USE filter                          ! filter manager
    USE mpp                             ! MPP manager
+   USE dom                             ! domain manager
    USE iom_mpp                         ! MPP I/O manager
+   USE iom_dom                         ! DOM I/O manager
 
    IMPLICIT NONE
@@ -60,5 +157,5 @@
    INTEGER(i4)                                        :: il_status
    INTEGER(i4)                                        :: il_fileid
-   INTEGER(i4)                                        :: il_attid
+   INTEGER(i4)                                        :: il_attind
    INTEGER(i4)                                        :: il_imin0
    INTEGER(i4)                                        :: il_imax0
@@ -66,7 +163,5 @@
    INTEGER(i4)                                        :: il_jmax0
    INTEGER(i4)      , DIMENSION(ip_maxdim)            :: il_rho
-   INTEGER(i4)      , DIMENSION(2,2)                  :: il_offset
-   INTEGER(i4)      , DIMENSION(2,2,2)                :: il_ind
-!   INTEGER(i4)      , DIMENSION(:,:,:,:), ALLOCATABLE :: il_value
+   INTEGER(i4)      , DIMENSION(2,2)                  :: il_ind
 
    LOGICAL                                            :: ll_exist
@@ -76,6 +171,6 @@
    REAL(dp)         , DIMENSION(:,:,:,:), ALLOCATABLE :: dl_weight
 
-   TYPE(TFILE)                                        :: tl_bathy0
-   TYPE(TFILE)                                        :: tl_bathy1
+   TYPE(TMPP)                                         :: tl_bathy0
+   TYPE(TMPP)                                         :: tl_bathy1
    TYPE(TFILE)                                        :: tl_fileout
    
@@ -85,6 +180,4 @@
    TYPE(TVAR)                                         :: tl_lon
    TYPE(TVAR)                                         :: tl_lat
-!   TYPE(TVAR)                                         :: tl_depth
-!   TYPE(TVAR)                                         :: tl_time
    
    TYPE(TDIM)       , DIMENSION(ip_maxdim)            :: tl_dim
@@ -98,24 +191,28 @@
 
    ! namelist variable
+   ! namlog
    CHARACTER(LEN=lc)                       :: cn_logfile = 'merge_bathy.log' 
    CHARACTER(LEN=lc)                       :: cn_verbosity = 'warning' 
-
+   INTEGER(i4)                             :: in_maxerror = 5
+
+   ! namcfg
+   CHARACTER(LEN=lc)                       :: cn_varcfg = 'variable.cfg' 
+
+   ! namcrs
    CHARACTER(LEN=lc)                       :: cn_bathy0 = '' 
    INTEGER(i4)                             :: in_perio0 = -1
 
+   ! namfin
    CHARACTER(LEN=lc)                       :: cn_bathy1 = '' 
    INTEGER(i4)                             :: in_perio1 = -1
 
-   CHARACTER(LEN=lc)                       :: cn_varcfg = 'variable.cfg' 
-
-   CHARACTER(LEN=lc), DIMENSION(ig_maxvar) :: cn_varinfo = ''
-
-   INTEGER(i4)                             :: in_imin0 = 0
-   INTEGER(i4)                             :: in_imax0 = 0
-   INTEGER(i4)                             :: in_jmin0 = 0
-   INTEGER(i4)                             :: in_jmax0 = 0
+   ! namvar
+   CHARACTER(LEN=lc), DIMENSION(ip_maxvar) :: cn_varinfo = ''
+
+   ! namnst
    INTEGER(i4)                             :: in_rhoi  = 0
    INTEGER(i4)                             :: in_rhoj  = 0
 
+   ! nambdy
    LOGICAL                                 :: ln_north = .TRUE.
    LOGICAL                                 :: ln_south = .TRUE.
@@ -128,4 +225,5 @@
    CHARACTER(LEN=lc)                       :: cn_west  = ''
 
+   ! namout
    CHARACTER(LEN=lc)                       :: cn_fileout = 'bathy_merged.nc' 
    !-------------------------------------------------------------------
@@ -152,8 +250,4 @@
    
    NAMELIST /namnst/ &  !< nesting namelist
-   &  in_imin0,   &     !< i-direction lower left  point indice on coarse grid 
-   &  in_imax0,   &     !< i-direction upper right point indice on coarse grid
-   &  in_jmin0,   &     !< j-direction lower left  point indice on coarse grid
-   &  in_jmax0,   &     !< j-direction upper right point indice on coarse grid
    &  in_rhoi,    &     !< refinement factor in i-direction
    &  in_rhoj           !< refinement factor in j-direction
@@ -171,9 +265,9 @@
 
    NAMELIST /namout/ &  !< output namelist
-   &  cn_fileout       !< fine grid merged bathymetry file   
+   &  cn_fileout        !< fine grid merged bathymetry file   
    !-------------------------------------------------------------------
 
-   !1- namelist
-   !1-1 get namelist
+   ! namelist
+   ! get namelist
    il_narg=COMMAND_ARGUMENT_COUNT() !f03 intrinsec
    IF( il_narg/=1 )THEN
@@ -184,5 +278,5 @@
    ENDIF
    
-   !1-2 read namelist
+   ! read namelist
    INQUIRE(FILE=TRIM(cl_namelist), EXIST=ll_exist)
    IF( ll_exist )THEN
@@ -203,10 +297,10 @@
 
       READ( il_fileid, NML = namlog )
-      !1-2-1 define log file
-      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity))
+      ! define log file
+      CALL logger_open(TRIM(cn_logfile),TRIM(cn_verbosity), in_maxerror)
       CALL logger_header()
 
       READ( il_fileid, NML = namcfg )
-      !1-2-2 get variable extra information
+      ! get variable extra information
       CALL var_def_extra(TRIM(cn_varcfg))
 
@@ -214,5 +308,5 @@
       READ( il_fileid, NML = namfin )
       READ( il_fileid, NML = namvar )
-      !1-2-3 add user change in extra information
+      ! add user change in extra information
       CALL var_chg_extra(cn_varinfo)
 
@@ -234,8 +328,8 @@
    ENDIF
 
-   !2- open files
+   ! open files
    IF( TRIM(cn_bathy0) /= '' )THEN
-      tl_bathy0=file_init(TRIM(cn_bathy0),id_perio=in_perio0)
-      CALL iom_open(tl_bathy0)
+      tl_bathy0=mpp_init( file_init(TRIM(cn_bathy0)), id_perio=in_perio0)
+      CALL grid_get_info(tl_bathy0)
    ELSE
       CALL logger_fatal("MERGE BATHY: can not find coarse grid bathymetry "//&
@@ -244,6 +338,6 @@
 
    IF( TRIM(cn_bathy1) /= '' )THEN
-      tl_bathy1=file_init(TRIM(cn_bathy1),id_perio=in_perio1)
-      CALL iom_open(tl_bathy1)
+      tl_bathy1=mpp_init( file_init(TRIM(cn_bathy1)), id_perio=in_perio1)
+      CALL grid_get_info(tl_bathy1)
    ELSE
       CALL logger_fatal("MERGE BATHY: can not find fine grid bathymetry "//&
@@ -251,6 +345,6 @@
    ENDIF
 
-   !3- check
-   !3-1 check output file do not already exist
+   ! check
+   ! check output file do not already exist
    INQUIRE(FILE=TRIM(cn_fileout), EXIST=ll_exist)
    IF( ll_exist )THEN
@@ -259,6 +353,6 @@
    ENDIF
 
-   !3-2 check namelist
-   !3-2-1 check refinament factor
+   ! check namelist
+   ! check refinament factor
    il_rho(:)=1
    IF( in_rhoi < 1 .OR. in_rhoj < 1 )THEN
@@ -270,25 +364,16 @@
    ENDIF
 
-   !3-2-2 check domain indices
-   IF( in_imin0 < 1 .OR. in_imax0 < 1 .OR. in_jmin0 < 1 .OR. in_jmax0 < 1)THEN
-      ! compute coarse grid indices around fine grid
-      il_ind(:,:,:)=grid_get_coarse_index(tl_bathy0, tl_bathy1 )
-
-      il_imin0=il_ind(1,1,1) ; il_imax0=il_ind(1,2,1)
-      il_jmin0=il_ind(2,1,1) ; il_jmax0=il_ind(2,2,1)
-
-      il_offset(:,:)=il_ind(:,:,2)
-   ELSE
-      il_imin0=in_imin0 ; il_imax0=in_imax0
-      il_jmin0=in_jmin0 ; il_jmax0=in_jmax0
-
-      il_offset(1,:)=FLOOR(REAL(il_rho(jp_I)-1,dp)*0.5)
-      il_offset(2,:)=FLOOR(REAL(il_rho(jp_J)-1,dp)*0.5)
-   ENDIF
-
-   !3-3 check domain validity
+   ! check domain indices
+   ! compute coarse grid indices around fine grid
+   il_ind(:,:)=grid_get_coarse_index(tl_bathy0, tl_bathy1, &
+   &                                 id_rho=il_rho(:) )
+
+   il_imin0=il_ind(1,1) ; il_imax0=il_ind(1,2)
+   il_jmin0=il_ind(2,1) ; il_jmax0=il_ind(2,2)
+
+   ! check domain validity
    CALL grid_check_dom(tl_bathy0, il_imin0, il_imax0, il_jmin0, il_jmax0)
 
-   !3-4 check coincidence between coarse and fine grid
+   ! check coincidence between coarse and fine grid
    CALL grid_check_coincidence( tl_bathy0, tl_bathy1, &
    &                            il_imin0, il_imax0, &
@@ -296,6 +381,12 @@
    &                            il_rho(:) )
 
-   !4- read or compute boundary
-   tl_var=iom_read_var(tl_bathy1,'Bathymetry')
+   ! open mpp files
+   CALL iom_mpp_open(tl_bathy1)
+
+   ! read or compute boundary
+   tl_var=iom_mpp_read_var(tl_bathy1,'Bathymetry')
+
+   ! close mpp files
+   CALL iom_mpp_close(tl_bathy1)
 
    tl_bdy(:)=boundary_init(tl_var, ln_north, ln_south, ln_east, ln_west, &
@@ -303,6 +394,6 @@
    &                               ln_oneseg ) 
 
-   !5- get boundary on coarse grid
-   !5-1 define refined bathymetry table (for coarse grid)
+   ! get boundary on coarse grid
+   ! define refined bathymetry array (for coarse grid)
    dl_fill=tl_var%d_fill
    ALLOCATE( dl_refined(tl_var%t_dim(1)%i_len, &
@@ -313,5 +404,5 @@
    dl_refined(:,:,:,:)=dl_fill
 
-   !5-2 define weight table
+   ! define weight array
    ALLOCATE( dl_weight(tl_var%t_dim(1)%i_len, &
    &                   tl_var%t_dim(2)%i_len, &
@@ -320,7 +411,6 @@
    dl_weight(:,:,:,:)=dl_fill 
 
-   !5-3 compute coarse grid refined bathymetry on boundary.
+   ! compute coarse grid refined bathymetry on boundary.
    DO jk=1,ip_ncard
-
       CALL merge_bathy_get_boundary(tl_bathy0, tl_bathy1, tl_bdy(jk), &
       &                             il_rho(:),                        &
@@ -330,5 +420,5 @@
    ENDDO
 
-   !6- merge bathy on boundary
+   ! merge bathy on boundary
    DO jl=1,tl_var%t_dim(4)%i_len
       DO jk=1,tl_var%t_dim(3)%i_len
@@ -348,9 +438,9 @@
    DEALLOCATE(dl_refined)
 
-   !7- create file
+   ! create file
    tl_fileout=file_init(TRIM(cn_fileout),id_perio=in_perio1)
 
-   !7-1 add dimension
-   tl_dim(:)=tl_var%t_dim(:)
+   ! add dimension
+   tl_dim(:)=dim_copy(tl_var%t_dim(:))
 
    DO ji=1,ip_maxdim
@@ -358,15 +448,21 @@
    ENDDO
 
-   !7-2 add variables
+   ! add variables
    IF( ALL( tl_dim(1:2)%l_use ) )THEN
-
-      tl_lon=iom_read_var(tl_bathy1,'longitude')
+      ! open mpp files
+      CALL iom_mpp_open(tl_bathy1)
+
+      ! add longitude
+      tl_lon=iom_mpp_read_var(tl_bathy1,'longitude')
       CALL file_add_var(tl_fileout, tl_lon)
       CALL var_clean(tl_lon)
 
-      tl_lat=iom_read_var(tl_bathy1,'latitude')
+      ! add latitude
+      tl_lat=iom_mpp_read_var(tl_bathy1,'latitude')
       CALL file_add_var(tl_fileout, tl_lat)
       CALL var_clean(tl_lat)
 
+      ! close mpp files
+      CALL iom_mpp_close(tl_bathy1)      
    ENDIF
 
@@ -375,5 +471,5 @@
 
    ! only 2 first dimension to be used
-   tl_dim(:)=tl_fileout%t_dim(:)
+   tl_dim(:)=dim_copy(tl_fileout%t_dim(:))
    tl_dim(3:4)%l_use=.FALSE.
    tl_var=var_init('weight',dl_weight(:,:,:,:),td_dim=tl_dim(:),dd_fill=dl_fill)
@@ -381,5 +477,5 @@
    CALL var_clean(tl_var)
 
-   !7-3 add some attribute
+   ! add some attribute
    tl_att=att_init("Created_by","SIREN merge_bathy")
    CALL file_add_att(tl_fileout, tl_att)
@@ -395,40 +491,37 @@
    CALL file_add_att(tl_fileout, tl_att)
 
-   ! a voir
    ! add attribute periodicity
-   il_attid=0
+   il_attind=0
    IF( ASSOCIATED(tl_fileout%t_att) )THEN
-      il_attid=att_get_id(tl_fileout%t_att(:),'periodicity')
-   ENDIF
-   IF( tl_bathy1%i_perio >= 0 .AND. il_attid == 0 )THEN
+      il_attind=att_get_index(tl_fileout%t_att(:),'periodicity')
+   ENDIF
+   IF( tl_bathy1%i_perio >= 0 .AND. il_attind == 0 )THEN
       tl_att=att_init('periodicity',tl_bathy1%i_perio)
       CALL file_add_att(tl_fileout,tl_att)
    ENDIF
 
-   il_attid=0
+   il_attind=0
    IF( ASSOCIATED(tl_fileout%t_att) )THEN
-      il_attid=att_get_id(tl_fileout%t_att(:),'ew_overlap')
-   ENDIF
-   IF( tl_bathy1%i_ew >= 0 .AND. il_attid == 0 )THEN
+      il_attind=att_get_index(tl_fileout%t_att(:),'ew_overlap')
+   ENDIF
+   IF( tl_bathy1%i_ew >= 0 .AND. il_attind == 0 )THEN
       tl_att=att_init('ew_overlap',tl_bathy1%i_ew)
       CALL file_add_att(tl_fileout,tl_att)
    ENDIF
 
-   !7-4 create file
+   ! create file
    CALL iom_create(tl_fileout)
 
-   !7-5 write file
+   ! write file
    CALL iom_write_file(tl_fileout)
 
-   !7-6 close file
+   ! close file
    CALL iom_close(tl_fileout)
 
-   CALL iom_close(tl_bathy1)
-   CALL iom_close(tl_bathy0)
-
-   !8- clean
+   ! clean
+   CALL att_clean(tl_att)
    CALL file_clean(tl_fileout)
-   CALL file_clean(tl_bathy1)
-   CALL file_clean(tl_bathy0)
+   CALL mpp_clean(tl_bathy1)
+   CALL mpp_clean(tl_bathy0)
    DEALLOCATE(dl_weight)
 
@@ -437,19 +530,20 @@
    CALL logger_close()
 
-!> @endcode
 CONTAINS
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine compute refined bathymetry on boundary from coarse grid.
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] 
-   !> @todo 
+   !> @param[in] td_bathy0       coarse grid bathymetry file structure 
+   !> @param[in] td_bathy1       fine grid bathymetry file structure
+   !> @param[in] td_bdy          boundary structure
+   !> @param[in] id_rho          array of refinement factor
+   !> @param[inout] dd_refined   array of refined bathymetry 
+   !> @param[inout] dd_weight    array of weight
+   !> @param[in] dd_fill         fillValue
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE merge_bathy_get_boundary( td_bathy0, td_bathy1, td_bdy, &
    &                                    id_rho,                       &
@@ -459,6 +553,6 @@
 
       ! Argument
-      TYPE(TFILE)                    , INTENT(IN   ) :: td_bathy0
-      TYPE(TFILE)                    , INTENT(IN   ) :: td_bathy1
+      TYPE(TMPP)                     , INTENT(IN   ) :: td_bathy0
+      TYPE(TMPP)                     , INTENT(IN   ) :: td_bathy1
       TYPE(TBDY)                     , INTENT(IN   ) :: td_bdy
       INTEGER(i4), DIMENSION(:)      , INTENT(IN   ) :: id_rho
@@ -478,11 +572,6 @@
       INTEGER(i4) :: il_jmax0
 
-      INTEGER(i4) :: il_imin
-      INTEGER(i4) :: il_imax
-      INTEGER(i4) :: il_jmin
-      INTEGER(i4) :: il_jmax
-
       INTEGER(i4), DIMENSION(2,2)         :: il_offset
-      INTEGER(i4), DIMENSION(2,2,2)       :: il_ind
+      INTEGER(i4), DIMENSION(2,2)         :: il_ind
 
       REAL(dp)   , DIMENSION(:)      , ALLOCATABLE :: dl_tmp1d
@@ -494,9 +583,6 @@
       TYPE(TVAR) :: tl_lat1
 
-      TYPE(TFILE) :: tl_bathy1
-      TYPE(TFILE) :: tl_bathy0
-
-      TYPE(TMPP)  :: tl_mppbathy1
-      TYPE(TMPP)  :: tl_mppbathy0
+      TYPE(TMPP)  :: tl_bathy1
+      TYPE(TMPP)  :: tl_bathy0
 
       TYPE(TDOM)  :: tl_dom1
@@ -510,6 +596,5 @@
       IF( td_bdy%l_use )THEN
          DO jl=1,td_bdy%i_nseg
-            
-            !1- get boundary definition
+            ! get boundary definition
             SELECT CASE(TRIM(td_bdy%c_card))
             CASE('north')
@@ -520,9 +605,4 @@
                il_jmax1=td_bdy%t_seg(jl)%i_index
 
-               il_imin=1
-               il_imax=il_imax1-il_imin1+1
-               il_jmin=td_bdy%t_seg(jl)%i_width
-               il_jmax=1
-
             CASE('south')
 
@@ -532,9 +612,4 @@
                il_jmax1=td_bdy%t_seg(jl)%i_index+(td_bdy%t_seg(jl)%i_width-1)
 
-               il_imin=1
-               il_imax=il_imax1-il_imin1+1
-               il_jmin=1
-               il_jmax=td_bdy%t_seg(jl)%i_width
-               
             CASE('east')
 
@@ -544,9 +619,4 @@
                il_jmax1=td_bdy%t_seg(jl)%i_last 
 
-               il_imin=td_bdy%t_seg(jl)%i_width
-               il_imax=1
-               il_jmin=1
-               il_jmax=il_jmax1-il_jmin1+1
-
             CASE('west')
 
@@ -556,117 +626,102 @@
                il_jmax1=td_bdy%t_seg(jl)%i_last 
 
-               il_imin=1
-               il_imax=td_bdy%t_seg(jl)%i_width
-               il_jmin=1
-               il_jmax=il_jmax1-il_jmin1+1
-
             END SELECT
 
-            !2 -read fine grid domain
-            tl_bathy1=td_bathy1
-            CALL iom_open(tl_bathy1)
-
-            !2-1 compute domain
+            ! -read fine grid domain
+            tl_bathy1=mpp_copy(td_bathy1)
+
+            ! compute domain
             tl_dom1=dom_init( tl_bathy1,         &
             &                 il_imin1, il_imax1,&
-            &                 il_jmin1, il_jmax1 )
-
-            !2-2 close file
-            CALL iom_close(tl_bathy1)
-
-            !2-3 read variables on domain (ugly way to do it, have to work on it)
-            !2-3-1 init mpp structure
-            tl_mppbathy1=mpp_init(tl_bathy1)
- 
-            CALL file_clean(tl_bathy1)
-
-            !2-3-2 get processor to be used
-            CALL mpp_get_use( tl_mppbathy1, tl_dom1 )
-
-            !2-3-3 open mpp files
-            CALL iom_mpp_open(tl_mppbathy1)
-
-            !2-3-4 read variable value on domain
-            tl_lon1=iom_mpp_read_var(tl_mppbathy1,'longitude',td_dom=tl_dom1)
-            tl_lat1=iom_mpp_read_var(tl_mppbathy1,'latitude' ,td_dom=tl_dom1)
-
-            !2-3-5 close mpp files
-            CALL iom_mpp_close(tl_mppbathy1)
-
-            !2-3-6 clean structure
-            CALL mpp_clean(tl_mppbathy1)
-
-            !3- get coarse grid indices
-            il_ind(:,:,:)=grid_get_coarse_index(td_bathy0, tl_lon1, tl_lat1, &
-            &                                   id_rho=id_rho(:))
-
-            il_imin0=il_ind(1,1,1)
-            il_imax0=il_ind(1,2,1)
-
-            il_jmin0=il_ind(2,1,1)
-            il_jmax0=il_ind(2,2,1)
-
-            il_offset(:,:)=il_ind(:,:,2)
-
-            !4- read coarse grid bathymetry on domain
-            tl_bathy0=td_bathy0
-            CALL iom_open(tl_bathy0)
-
-            !4-1 compute domain
+            &                 il_jmin1, il_jmax1,&
+            &                 TRIM(td_bdy%c_card))
+
+            ! add extra band to fine grid domain (if possible)
+            ! to avoid dimension of one and so be able to compute offset
+            CALL dom_add_extra(tl_dom1, id_rho(jp_I), id_rho(jp_J))
+
+            ! open mpp files over domain
+            CALL iom_dom_open(tl_bathy1, tl_dom1)
+
+            ! read variable value on domain
+            tl_lon1=iom_dom_read_var(tl_bathy1,'longitude',tl_dom1)
+            tl_lat1=iom_dom_read_var(tl_bathy1,'latitude' ,tl_dom1)
+
+            ! close mpp files
+            CALL iom_dom_close(tl_bathy1)
+
+            ! clean structure
+            CALL mpp_clean(tl_bathy1)
+
+            ! get coarse grid indices
+            il_ind(:,:)=grid_get_coarse_index(td_bathy0, tl_lon1, tl_lat1, &
+            &                                 id_rho=id_rho(:))
+
+            il_imin0=il_ind(1,1)
+            il_imax0=il_ind(1,2)
+
+            il_jmin0=il_ind(2,1)
+            il_jmax0=il_ind(2,2)
+
+            ! read coarse grid bathymetry on domain
+            tl_bathy0=mpp_copy(td_bathy0)
+
+            ! compute domain
             tl_dom0=dom_init( tl_bathy0,         &
             &                 il_imin0, il_imax0,&
             &                 il_jmin0, il_jmax0 )
 
-            !4-2 close file
-            CALL iom_close(tl_bathy0)
-
-            !4-3 add extra band (if possible) to compute interpolation
+            il_offset(:,:)= grid_get_fine_offset(tl_bathy0,         &
+            &                                    il_imin0, il_jmin0,&
+            &                                    il_imax0, il_jmax0,&
+            &                                    tl_lon1%d_value(:,:,1,1), &
+            &                                    tl_lat1%d_value(:,:,1,1), &
+            &                                    id_rho=id_rho(:))
+
+            ! clean
+            CALL var_clean(tl_lon1)
+            CALL var_clean(tl_lat1)
+
+            ! add extra band (if possible) to compute interpolation
             CALL dom_add_extra(tl_dom0)
 
-            !4-4 read variables on domain (ugly way to do it, have to work on it)
-            !4-4-1 init mpp structure
-            tl_mppbathy0=mpp_init(tl_bathy0)
-            
-            CALL file_clean(tl_bathy0)
-
-            !4-4-2 get processor to be used
-            CALL mpp_get_use( tl_mppbathy0, tl_dom0 )
-
-            !4-4-3 open mpp files
-            CALL iom_mpp_open(tl_mppbathy0)
-
-            !4-4-4 read variable value on domain
-            tl_var0=iom_mpp_read_var(tl_mppbathy0,'Bathymetry',td_dom=tl_dom0)
-
-            !4-4-5 close mpp files
-            CALL iom_mpp_close(tl_mppbathy0)
-
-            !4-4-6 clean structure
-            CALL mpp_clean(tl_mppbathy0)
-
-            !5- interpolate variable
+            ! open mpp files over domain
+            CALL iom_dom_open(tl_bathy0, tl_dom0)
+
+            ! read variable value on domain
+            tl_var0=iom_dom_read_var(tl_bathy0,'Bathymetry',tl_dom0)
+
+            ! close mpp files
+            CALL iom_dom_close(tl_bathy0)
+
+            ! clean structure
+            CALL mpp_clean(tl_bathy0)
+
+            ! interpolate variable
             CALL merge_bathy_interp( tl_var0,         &
             &                        id_rho(:),       &
             &                        il_offset(:,:) )
 
-            !6- remove extraband added to domain
+            ! remove extraband added to domain
             CALL dom_del_extra( tl_var0, tl_dom0, id_rho(:) )
 
-            !6-1 remove extraband added to domain
+            ! remove extraband added to domain
             CALL dom_clean_extra( tl_dom0 )
 
-            !7- fill refined table  
-            !7-1 keep only useful point
-            ! interpolation could create more point than necessary
-            CALL boundary_clean_interp(tl_var0, td_bdy )
-
-            ! use add request ????
-
-            !7-2 fill refined table
+            ! remove extraband added to fine grid domain
+            CALL dom_del_extra( tl_var0, tl_dom1 )
+
+            ! remove extraband added to fine grid domain
+            CALL dom_clean_extra( tl_dom1 )
+
+            ! fill refined array
             dd_refined( il_imin1:il_imax1, &
             &           il_jmin1:il_jmax1, &
             &           :,: )= tl_var0%d_value(:,:,:,:)
 
-            !8- compute weight function
+            ! clean
+            CALL var_clean(tl_var0)
+
+            ! compute weight function
             ALLOCATE( dl_tmp1d(td_bdy%t_seg(jl)%i_width) )
 
@@ -678,5 +733,5 @@
 
                ! compute weight on segment
-               dl_tmp1d(:)= 0.5 + 0.5*COS( (dg_pi*dl_tmp1d(:)) / &
+               dl_tmp1d(:)= 0.5 + 0.5*COS( (dp_pi*dl_tmp1d(:)) / &
                &                           (td_bdy%t_seg(jl)%i_width) )
 
@@ -694,5 +749,5 @@
 
                ! compute weight on segment
-               dl_tmp1d(:)= 0.5 + 0.5*COS( (dg_pi*dl_tmp1d(:)) / &
+               dl_tmp1d(:)= 0.5 + 0.5*COS( (dp_pi*dl_tmp1d(:)) / &
                &                           (td_bdy%t_seg(jl)%i_width) )
 
@@ -710,5 +765,5 @@
 
                ! compute weight on segment
-               dl_tmp1d(:)= 0.5 + 0.5*COS( (dg_pi*dl_tmp1d(:)) / &
+               dl_tmp1d(:)= 0.5 + 0.5*COS( (dp_pi*dl_tmp1d(:)) / &
                &                           (td_bdy%t_seg(jl)%i_width) )
 
@@ -726,5 +781,5 @@
 
                ! compute weight on segment
-               dl_tmp1d(:)= 0.5 + 0.5*COS( (dg_pi*dl_tmp1d(:)) / &
+               dl_tmp1d(:)= 0.5 + 0.5*COS( (dp_pi*dl_tmp1d(:)) / &
                &                           (td_bdy%t_seg(jl)%i_width) )
 
@@ -740,5 +795,5 @@
             DEALLOCATE( dl_tmp1d )
 
-            !8-1 fill weight table
+            ! fill weight array
             ALLOCATE( dl_tmp2d( tl_dom1%t_dim(1)%i_len, &
             &                   tl_dom1%t_dim(2)%i_len) )
@@ -764,18 +819,17 @@
       ENDIF
    END SUBROUTINE merge_bathy_get_boundary
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine
+   !> This subroutine interpolate variable.
    !> 
-   !> @details 
+   !> @author J.Paul
+   !> @date November, 2013 - Initial Version
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !>
-   !> @param[in] 
-   !> @todo 
+   !> @param[inout] td_var variable structure
+   !> @param[in] id_rho    array of refinment factor
+   !> @param[in] id_offset array of offset between fine and coarse grid
+   !> @param[in] id_iext   i-direction size of extra bands (default=im_minext) 
+   !> @param[in] id_jext   j-direction size of extra bands (default=im_minext)
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE merge_bathy_interp( td_var,          &
    &                              id_rho,          &
@@ -793,5 +847,4 @@
 
       ! local variable
-      TYPE(TVAR)  :: tl_var
       TYPE(TVAR)  :: tl_mask
 
@@ -803,7 +856,4 @@
       ! loop indices
       !----------------------------------------------------------------
-
-      ! copy variable
-      tl_var=td_var
 
       !WARNING: two extrabands are required for cubic interpolation
@@ -815,5 +865,5 @@
 
       IF( il_iext < 2 .AND. td_var%c_interp(1) == 'cubic' )THEN
-         CALL logger_warn("CREATE BATHY INTERP: at least extrapolation "//&
+         CALL logger_warn("MERGE BATHY INTERP: at least extrapolation "//&
          &  "on two points are required with cubic interpolation ")
          il_iext=2
@@ -821,64 +871,57 @@
 
       IF( il_jext < 2 .AND. td_var%c_interp(1) == 'cubic' )THEN
-         CALL logger_warn("CREATE BATHY INTERP: at least extrapolation "//&
+         CALL logger_warn("MERGE BATHY INTERP: at least extrapolation "//&
          &  "on two points are required with cubic interpolation ")
          il_jext=2
       ENDIF
 
-      !1- work on mask
-      !1-1 create mask
-      ALLOCATE(bl_mask(tl_var%t_dim(1)%i_len, &
-      &                tl_var%t_dim(2)%i_len, &
-      &                tl_var%t_dim(3)%i_len, &
-      &                tl_var%t_dim(4)%i_len) )
+      ! work on mask
+      ! create mask
+      ALLOCATE(bl_mask(td_var%t_dim(1)%i_len, &
+      &                td_var%t_dim(2)%i_len, &
+      &                td_var%t_dim(3)%i_len, &
+      &                td_var%t_dim(4)%i_len) )
 
       bl_mask(:,:,:,:)=1
-      WHERE(tl_var%d_value(:,:,:,:)==tl_var%d_fill) bl_mask(:,:,:,:)=0      
-
-      SELECT CASE(TRIM(tl_var%c_point))
+      WHERE(td_var%d_value(:,:,:,:)==td_var%d_fill) bl_mask(:,:,:,:)=0      
+
+      SELECT CASE(TRIM(td_var%c_point))
       CASE DEFAULT ! 'T'
-         tl_mask=var_init('tmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('U')
-         tl_mask=var_init('umask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('V')
-         tl_mask=var_init('vmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
-      CASE('F')
-         tl_mask=var_init('fmask', bl_mask(:,:,:,:), td_dim=tl_var%t_dim(:))
+         tl_mask=var_init('tmask',bl_mask(:,:,:,:),td_dim=td_var%t_dim(:),&
+         &                id_ew=td_var%i_ew )
+      CASE('U','V','F')
+         CALL logger_fatal("MERGE BATHY INTERP: can not computed "//&
+         &                 "interpolation on "//TRIM(td_var%c_point)//&
+         &                 " grid point (variable "//TRIM(td_var%c_name)//&
+         &                 "). check namelist.")
       END SELECT
 
       DEALLOCATE(bl_mask)
 
-      !1-2 interpolate mask
+      ! interpolate mask
       CALL interp_fill_value( tl_mask, id_rho(:),  &
       &                       id_offset=id_offset(:,:) )
 
-      !2- work on variable
-      !2-0 add extraband
-      CALL extrap_add_extrabands(tl_var, il_iext, il_iext)
-
-      !2-1 extrapolate variable
-      CALL extrap_fill_value( tl_var, id_offset=id_offset(:,:), &
+      ! work on variable
+      ! add extraband
+      CALL extrap_add_extrabands(td_var, il_iext, il_iext)
+
+      ! extrapolate variable
+      CALL extrap_fill_value( td_var, id_offset=id_offset(:,:), &
       &                               id_rho=id_rho(:),         &
       &                               id_iext=il_iext, id_jext=il_jext )
 
-      !2-2 interpolate Bathymetry
-      CALL interp_fill_value( tl_var, id_rho(:), &
+      ! interpolate Bathymetry
+      CALL interp_fill_value( td_var, id_rho(:), &
       &                       id_offset=id_offset(:,:) )
 
-      !2-3 remove extraband
-      CALL extrap_del_extrabands(tl_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
-
-      !2-4 keep original mask 
+      ! remove extraband
+      CALL extrap_del_extrabands(td_var, il_iext*id_rho(jp_I), il_jext*id_rho(jp_J))
+
+      ! keep original mask 
       WHERE( tl_mask%d_value(:,:,:,:) == 0 )
-         tl_var%d_value(:,:,:,:)=tl_var%d_fill
+         td_var%d_value(:,:,:,:)=td_var%d_fill
       END WHERE
 
-      !3- save result
-      td_var=tl_var
-
-      ! clean variable structure
-      CALL var_clean(tl_var)
-
    END SUBROUTINE merge_bathy_interp
-   !> @endcode
 END PROGRAM merge_bathy
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/mpp.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/mpp.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/mpp.f90	(revision 5075)
@@ -5,32 +5,47 @@
 ! MODULE: mpp
 !
-!
 ! DESCRIPTION:
-!> This module manage massively parallel processing
+!> @brief
+!> This module manage massively parallel processing.
 !
 !> @details
 !> define type TMPP:<br/>
-!> TYPE(TMPP) :: tl_mpp<br/>
+!> @code
+!> TYPE(TMPP) :: tl_mpp
+!> @endcode
 !>
 !>    to initialise a mpp structure:<br/>
-!>    - tl_mpp=mpp_init( cd_file, id_mask, [id_niproc,] [id_njproc,] 
-!>         [id_nproc] [id_preci,] [id_precj,] [cd_type])
-!>    - tl_mpp=mpp_init( cd_file, td_var, [id_niproc,] [id_njproc,] 
-!>         [id_nproc] [id_preci,] [id_precj,] [cd_type])
-!>    - tl_mpp=mpp_init( td_file )
+!> @code
+!>    tl_mpp=mpp_init( cd_file, id_mask, 
+!>                       [id_niproc,] [id_njproc,] [id_nproc,]
+!>                       [id_preci,] [id_precj,] 
+!>                       [cd_type,] [id_ew])
+!> @endcode
+!> or
+!> @code
+!>    tl_mpp=mpp_init( cd_file, td_var, 
+!>                      [id_niproc,] [id_njproc,] [id_nproc,]
+!>                      [id_preci,] [id_precj,]
+!>                      [cd_type] )
+!> @endcode
+!> or
+!> @code
+!>    tl_mpp=mpp_init( td_file [,id_ew] )
+!> @endcode
 !>       - cd_file is the filename of the global domain file, in which 
 !>         MPP will be done (example: Bathymetry) 
 !>       - td_file is the file structure of one processor file composing an MPP
-!>       - id_mask is the 2D mask of global domain 
+!>       - id_mask is the 2D mask of global domain [optional]
 !>       - td_var is a variable structure (on T-point) from global domain file.
-!>         mask of the domain will be computed using FillValue
+!>         mask of the domain will be computed using FillValue [optional]
 !>       - id_niproc is the number of processor following I-direction to be used
-!>         (optional)
+!>         [optional]
 !>       - id_njproc is the number of processor following J-direction to be used 
-!>         (optional)
-!>       - id_nproc is the total number of processor to be used (optional)
-!>       - id_preci is the size of the overlap region following I-direction
-!>       - id_precj is the size of the overlap region following J-direction
-!>       - cd_type is the type of files composing MPP<br/>
+!>         [optional]
+!>       - id_nproc is the total number of processor to be used [optional]
+!>       - id_preci is the size of the overlap region following I-direction [optional]
+!>       - id_precj is the size of the overlap region following J-direction [optional]
+!>       - cd_type is the type of files composing MPP [optional]
+!>       - id_ew is east-west overlap [optional]<br/> 
 !>  
 !>    to get mpp name:<br/>
@@ -62,5 +77,5 @@
 !>    - tl_mpp\%i_ndim
 !>
-!>    to get the table of dimension structure (4 elts) associated to the
+!>    to get the array of dimension structure (4 elts) associated to the
 !>    mpp structure:<br/>
 !>    - tl_mpp\%t_dim(:)
@@ -70,50 +85,110 @@
 !>
 !>    to clean a mpp structure:<br/>
-!>    - CALL mpp_clean(tl_mpp)
+!> @code
+!>    CALL mpp_clean(tl_mpp)
+!> @endcode
 !>
 !>    to print information about mpp:<br/>
+!> @code
 !>    CALL mpp_print(tl_mpp)
+!> @endcode
 !>
 !>    to add variable to mpp:<br/>
+!> @code
 !>    CALL mpp_add_var(td_mpp, td_var)
+!> @endcode
 !>       - td_var is a variable structure
 !>
 !>    to add dimension to mpp:<br/>
+!> @code
 !>    CALL mpp_add_dim(td_mpp, td_dim)
+!> @endcode
 !>       - td_dim is a dimension structure
 !>
-!>    to delete variable to mpp:<br/>
+!>    to add attribute to mpp:<br/>
+!> @code
+!>    CALL mpp_add_att(td_mpp, td_att)
+!> @endcode
+!>       - td_att is a attribute structure
+!>
+!>    to delete variable from mpp:<br/>
+!> @code
 !>    CALL mpp_del_var(td_mpp, td_var)
+!> @endcode
+!>    or
+!> @code
+!>    CALL mpp_del_var(td_mpp, cd_name)
+!> @endcode
 !>       - td_var is a variable structure
+!>       - cd_name is variable name or standard name
 !>
-!>    to delete dimension to mpp:<br/>
+!>    to delete dimension from mpp:<br/>
+!> @code
 !>    CALL mpp_del_dim(td_mpp, td_dim)
+!> @endcode
 !>       - td_dim is a dimension structure
 !>
+!>    to delete attribute from mpp:<br/>
+!> @code
+!>    CALL mpp_del_att(td_mpp, td_att)
+!> @endcode
+!>    or
+!> @code
+!>    CALL mpp_del_att(td_mpp, cd_name)
+!> @endcode
+!>       - td_att is a attribute structure
+!>       - cd_name is attribute name
+!>
 !>    to overwrite variable to mpp:<br/>
+!> @code
 !>    CALL mpp_move_var(td_mpp, td_var)
+!> @endcode
 !>       - td_var is a variable structure
 !>
 !>    to overwrite dimension to mpp:<br/>
+!> @code
 !>    CALL mpp_move_dim(td_mpp, td_dim)
+!> @endcode
 !>       - td_dim is a dimension structure
 !>
+!>    to overwrite attribute to mpp:<br/>
+!> @code
+!>    CALL mpp_move_att(td_mpp, td_att)
+!> @endcode
+!>       - td_att is a attribute structure
+!>
 !>    to determine domain decomposition type:<br/>
+!> @code
 !>    CALL mpp_get_dom(td_mpp)
+!> @endcode
 !>
 !>    to get processors to be used:<br/>
-!>    CALL mpp_get_use( td_mpp, td_dom )
-!>       - td_dom is a domain structure
+!> @code
+!>    CALL mpp_get_use( td_mpp, id_imin, id_imax, id_idim, & 
+!>    &                         id_jmin, id_jmax, id_jdim )
+!> @endcode
+!>       - id_imin 
+!>       - id_imax 
+!>       - id_idim 
+!>       - id_jmin 
+!>       - id_jmax 
+!>       - id_jdim 
 !>
 !>    to get sub domains which form global domain contour:<br/>
+!> @code
 !>    CALL mpp_get_contour( td_mpp ) 
+!> @endcode
 !>
 !>    to get global domain indices of one processor:<br/>
+!> @code
 !>    il_ind(1:4)=mpp_get_proc_index( td_mpp, id_procid )
+!> @endcode
 !>       - il_ind(1:4) are global domain indices (i1,i2,j1,j2)
 !>       - id_procid is the processor id
 !>
 !>    to get the processor domain size:<br/>
+!> @code
 !>    il_size(1:2)=mpp_get_proc_size( td_mpp, id_procid )
+!> @endcode
 !>       - il_size(1:2) are the size of domain following I and J
 !>       - id_procid is the processor id
@@ -122,16 +197,13 @@
 !>  J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!> @todo
-!>  - add description generique de l'objet mpp
-!>  - mpp_print
-!>  - voir pour mettre cd_file systematiquement pour mpp_init
-!>  + modifier utilisation la haut
+!> @date November, 2013 - Initial Version
+!> @date November, 2014 - Fix memory leaks bug
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
 !----------------------------------------------------------------------
 MODULE mpp
+   USE global                          ! global parameter
    USE kind                            ! F90 kind parameter
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE fct                             ! basic useful function
    USE dim                             ! dimension manager
@@ -140,15 +212,12 @@
    USE file                            ! file manager
    USE iom                             ! I/O manager
-!   USE proc                            ! proc manager
-   USE dom                             ! domain manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
-   PUBLIC :: TMPP       ! mpp structure
+   PUBLIC :: TMPP       !< mpp structure
 
    ! function and subroutine
-   PUBLIC :: ASSIGNMENT(=)      !< copy mpp structure
+   PUBLIC :: mpp_copy           !< copy mpp structure
    PUBLIC :: mpp_init           !< initialise mpp structure
    PUBLIC :: mpp_clean          !< clean mpp strcuture
@@ -163,4 +232,6 @@
    PUBLIC :: mpp_move_dim       !< overwrite one dimension strucutre in mpp structure
    PUBLIC :: mpp_move_att       !< overwrite one attribute strucutre in mpp structure
+   PUBLIC :: mpp_recombine_var  !< recombine variable from mpp structure
+   PUBLIC :: mpp_get_index      !< return index of mpp 
 
    PUBLIC :: mpp_get_dom        !< determine domain decomposition type (full, overlap, noverlap)
@@ -170,40 +241,66 @@
    PUBLIC :: mpp_get_proc_size  !< get processor domain size
 
-   PRIVATE :: mpp__add_proc     !< add one proc strucutre in mpp structure
-   PRIVATE :: mpp__del_proc     !< delete one proc strucutre in mpp structure
-   PRIVATE :: mpp__move_proc    !< overwrite proc strucutre in mpp structure
-   PRIVATE :: mpp__compute      !< compute domain decomposition
-   PRIVATE :: mpp__del_land     !< remove land sub domain from domain decomposition
-   PRIVATE :: mpp__optimiz      !< compute optimum domain decomposition
-   PRIVATE :: mpp__land_proc    !< check if processor is a land processor
-   PRIVATE :: mpp__check_dim    !< check mpp structure dimension with proc or variable dimension
-   PRIVATE :: mpp__del_var_name !< delete variable in mpp structure, given variable name
-   PRIVATE :: mpp__del_var_str  !< delete variable in mpp structure, given variable structure
-   PRIVATE :: mpp__del_att_name !< delete variable in mpp structure, given variable name
-   PRIVATE :: mpp__del_att_str  !< delete variable in mpp structure, given variable structure
-   PRIVATE :: mpp__split_var    !< extract variable part that will be written in processor 
-   PRIVATE :: mpp__copy         !< copy mpp structure
-
-   !> @struct TMPP
-   TYPE TMPP
+   PRIVATE :: mpp__add_proc            ! add one proc strucutre in mpp structure
+   PRIVATE :: mpp__del_proc            ! delete one proc strucutre in mpp structure
+   PRIVATE :: mpp__del_proc_id         ! delete one proc strucutre in mpp structure, given procesor id
+   PRIVATE :: mpp__del_proc_str        ! delete one proc strucutre in mpp structure, given procesor file structure 
+   PRIVATE :: mpp__move_proc           ! overwrite proc strucutre in mpp structure
+   PRIVATE :: mpp__compute             ! compute domain decomposition
+   PRIVATE :: mpp__del_land            ! remove land sub domain from domain decomposition
+   PRIVATE :: mpp__optimiz             ! compute optimum domain decomposition
+   PRIVATE :: mpp__land_proc           ! check if processor is a land processor
+   PRIVATE :: mpp__check_dim           ! check mpp structure dimension with proc or variable dimension
+   PRIVATE :: mpp__check_proc_dim      ! check if processor and mpp structure use same dimension
+   PRIVATE :: mpp__check_var_dim       ! check if variable  and mpp structure use same dimension
+   PRIVATE :: mpp__del_var_name        ! delete variable in mpp structure, given variable name
+   PRIVATE :: mpp__del_var_mpp         ! delete all variable in mpp structure
+   PRIVATE :: mpp__del_var_str         ! delete variable in mpp structure, given variable structure
+   PRIVATE :: mpp__del_att_name        ! delete variable in mpp structure, given variable name
+   PRIVATE :: mpp__del_att_str         ! delete variable in mpp structure, given variable structure
+   PRIVATE :: mpp__split_var           ! extract variable part that will be written in processor 
+   PRIVATE :: mpp__copy_unit           ! copy mpp structure
+   PRIVATE :: mpp__copy_arr            ! copy array of mpp structure
+   PRIVATE :: mpp__get_use_unit        ! get sub domains to be used (which cover "zoom domain")
+   PRIVATE :: mpp__init_mask           ! initialise mpp structure, given file name
+   PRIVATE :: mpp__init_var            ! initialise mpp structure, given variable strcuture
+   PRIVATE :: mpp__init_file           ! initialise a mpp structure, given file structure 
+   PRIVATE :: mpp__init_file_cdf       ! initialise a mpp structure with cdf file
+   PRIVATE :: mpp__init_file_rstdimg   ! initialise a mpp structure with rstdimg file
+   PRIVATE :: mpp__clean_unit          ! clean mpp strcuture
+   PRIVATE :: mpp__clean_arr           ! clean array of mpp strcuture
+
+   TYPE TMPP !< mpp structure
 
       ! general 
-      CHARACTER(LEN=lc)                   :: c_name = ''   !< base name ???
-
-      INTEGER(i4)                         :: i_niproc = 0         !< number of processors following i
-      INTEGER(i4)                         :: i_njproc = 0         !< number of processors following j
-      INTEGER(i4)                         :: i_nproc  = 0         !< total number of proccessors used
-      INTEGER(i4)                         :: i_preci = 1          !< i-direction overlap region length
-      INTEGER(i4)                         :: i_precj = 1          !< j-direction overlap region length
-
-      CHARACTER(LEN=lc)                   :: c_type = ''   !< type of the files (cdf, cdf4, dimg)
-      CHARACTER(LEN=lc)                   :: c_dom  = ''   !< type of domain (full, overlap, nooverlap)
-
-      INTEGER(i4)                         :: i_ndim = 0           !< number of dimensions used in mpp
-      TYPE(TDIM),  DIMENSION(ip_maxdim)   :: t_dim                !< global domain dimension
-
-      TYPE(TFILE), DIMENSION(:), POINTER  :: t_proc => NULL()     !< files/processors composing mpp
+      CHARACTER(LEN=lc)                  :: c_name = ''   !< base name 
+      INTEGER(i4)                        :: i_id   = 0    !< mpp id
+
+      INTEGER(i4)                        :: i_niproc = 0  !< number of processors following i
+      INTEGER(i4)                        :: i_njproc = 0  !< number of processors following j
+      INTEGER(i4)                        :: i_nproc  = 0  !< total number of proccessors used
+      INTEGER(i4)                        :: i_preci = 1   !< i-direction overlap region length
+      INTEGER(i4)                        :: i_precj = 1   !< j-direction overlap region length
+      INTEGER(i4)                        :: i_ew    = -1  !< east-west overlap
+      INTEGER(i4)                        :: i_perio = -1  !< NEMO periodicity index
+      INTEGER(i4)                        :: i_pivot = -1  !< NEMO pivot point index F(0),T(1)
+
+      CHARACTER(LEN=lc)                  :: c_type = ''   !< type of the files (cdf, cdf4, dimg)
+      CHARACTER(LEN=lc)                  :: c_dom  = ''   !< type of domain (full, overlap, nooverlap)
+
+      INTEGER(i4)                        :: i_ndim = 0    !< number of dimensions used in mpp
+      TYPE(TDIM),  DIMENSION(ip_maxdim)  :: t_dim         !< global domain dimension
+
+      TYPE(TFILE), DIMENSION(:), POINTER :: t_proc => NULL()     !< files/processors composing mpp
 
    END TYPE
+
+   INTERFACE mpp_get_use
+      MODULE PROCEDURE mpp__get_use_unit 
+   END INTERFACE mpp_get_use
+
+   INTERFACE mpp_clean
+      MODULE PROCEDURE mpp__clean_unit 
+      MODULE PROCEDURE mpp__clean_arr   
+   END INTERFACE mpp_clean
 
    INTERFACE mpp__check_dim
@@ -220,4 +317,5 @@
       MODULE PROCEDURE mpp__del_var_name
       MODULE PROCEDURE mpp__del_var_str
+      MODULE PROCEDURE mpp__del_var_mpp
    END INTERFACE mpp_del_var
 
@@ -230,9 +328,10 @@
       MODULE PROCEDURE mpp__init_mask
       MODULE PROCEDURE mpp__init_var
-      MODULE PROCEDURE mpp__init_read
+      MODULE PROCEDURE mpp__init_file
    END INTERFACE mpp_init
 
-   INTERFACE ASSIGNMENT(=)
-      MODULE PROCEDURE mpp__copy   ! copy mpp structure
+   INTERFACE mpp_copy
+      MODULE PROCEDURE mpp__copy_unit  ! copy mpp structure
+      MODULE PROCEDURE mpp__copy_arr   ! copy array of mpp structure
    END INTERFACE
 
@@ -240,23 +339,34 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine copy mpp structure in another mpp
-   !> structure
+   !> This subroutine copy mpp structure in another one
    !> @details 
-   !> mpp file are copied in a temporary table, 
+   !> mpp file are copied in a temporary array, 
    !> so input and output mpp structure do not point on the same 
    !> "memory cell", and so on are independant. 
    !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[out] td_mpp1  : mpp structure
-   !> @param[in] td_mpp2  : mpp structure
-   !-------------------------------------------------------------------
-   ! @code
-   SUBROUTINE mpp__copy( td_mpp1, td_mpp2 )
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_file=file_copy(file_init()) is forbidden).
+   !> This will create memory leaks.
+   !> @warning to avoid infinite loop, do not use any function inside 
+   !> this subroutine
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
+   !
+   !> @param[in] td_mpp   mpp structure
+   !> @return copy of input mpp structure
+   !-------------------------------------------------------------------
+   FUNCTION mpp__copy_unit( td_mpp )
       IMPLICIT NONE
       ! Argument
-      TYPE(TMPP), INTENT(OUT) :: td_mpp1
-      TYPE(TMPP), INTENT(IN)  :: td_mpp2
+      TYPE(TMPP), INTENT(IN)  :: td_mpp
+      ! function
+      TYPE(TMPP) :: mpp__copy_unit
+
+      ! local variable
+      TYPE(TFILE) :: tl_file
 
       ! loop indices
@@ -264,31 +374,80 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace("COPY: mpp "//TRIM(td_mpp2%c_name)//" in "//&
-      &  TRIM(td_mpp1%c_name))
+      CALL logger_trace("MPP COPY: "//TRIM(td_mpp%c_name)//" in "//&
+      &  TRIM(mpp__copy_unit%c_name))
+
       ! copy mpp variable
-      td_mpp1%c_name     = TRIM(td_mpp2%c_name)
-      td_mpp1%i_niproc   = td_mpp2%i_niproc
-      td_mpp1%i_njproc   = td_mpp2%i_njproc
-      td_mpp1%i_nproc    = td_mpp2%i_nproc
-      td_mpp1%i_preci    = td_mpp2%i_preci
-      td_mpp1%i_precj    = td_mpp2%i_precj
-      td_mpp1%c_type     = TRIM(td_mpp2%c_type)
-      td_mpp1%c_dom      = TRIM(td_mpp2%c_dom)
-      td_mpp1%i_ndim     = td_mpp2%i_ndim
+      mpp__copy_unit%c_name     = TRIM(td_mpp%c_name)
+      mpp__copy_unit%i_niproc   = td_mpp%i_niproc
+      mpp__copy_unit%i_njproc   = td_mpp%i_njproc
+      mpp__copy_unit%i_nproc    = td_mpp%i_nproc
+      mpp__copy_unit%i_preci    = td_mpp%i_preci
+      mpp__copy_unit%i_precj    = td_mpp%i_precj
+      mpp__copy_unit%c_type     = TRIM(td_mpp%c_type)
+      mpp__copy_unit%c_dom      = TRIM(td_mpp%c_dom)
+      mpp__copy_unit%i_ndim     = td_mpp%i_ndim
+      mpp__copy_unit%i_ew       = td_mpp%i_ew
+      mpp__copy_unit%i_perio    = td_mpp%i_perio
+      mpp__copy_unit%i_pivot    = td_mpp%i_pivot
 
       ! copy dimension
-      td_mpp1%t_dim(:) = td_mpp2%t_dim(:)
+      mpp__copy_unit%t_dim(:) = dim_copy(td_mpp%t_dim(:))
       
       ! copy file structure
-      IF( ASSOCIATED(td_mpp1%t_proc) ) DEALLOCATE(td_mpp1%t_proc)
-      IF( ASSOCIATED(td_mpp2%t_proc) )THEN
-         ALLOCATE( td_mpp1%t_proc(td_mpp1%i_nproc) )
-         DO ji=1,td_mpp1%i_nproc
-            td_mpp1%t_proc(ji) = td_mpp2%t_proc(ji)
+      IF( ASSOCIATED(mpp__copy_unit%t_proc) )THEN
+         CALL file_clean(mpp__copy_unit%t_proc(:))
+         DEALLOCATE(mpp__copy_unit%t_proc)
+      ENDIF
+      IF( ASSOCIATED(td_mpp%t_proc) .AND. mpp__copy_unit%i_nproc > 0 )THEN
+         ALLOCATE( mpp__copy_unit%t_proc(mpp__copy_unit%i_nproc) )
+         DO ji=1,mpp__copy_unit%i_nproc
+            tl_file = file_copy(td_mpp%t_proc(ji))
+            mpp__copy_unit%t_proc(ji) = file_copy(tl_file)
          ENDDO
-      ENDIF
-
-   END SUBROUTINE mpp__copy
-   ! @endcode
+         ! clean
+         CALL file_clean(tl_file)
+      ENDIF
+
+   END FUNCTION mpp__copy_unit
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine copy an array of mpp structure in another one
+   !> @details 
+   !> mpp file are copied in a temporary array, 
+   !> so input and output mpp structure do not point on the same 
+   !> "memory cell", and so on are independant. 
+   !>
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_file=file_copy(file_init()) is forbidden).
+   !> This will create memory leaks.
+   !> @warning to avoid infinite loop, do not use any function inside 
+   !> this subroutine
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
+   !>
+   !> @param[in] td_mpp   mpp structure
+   !> @return copy of input array of mpp structure
+   !-------------------------------------------------------------------
+   FUNCTION mpp__copy_arr( td_mpp )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TMPP), DIMENSION(:), INTENT(IN)  :: td_mpp
+      ! function
+      TYPE(TMPP), DIMENSION(SIZE(td_mpp(:))) :: mpp__copy_arr
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      DO ji=1,SIZE(td_mpp(:))
+         mpp__copy_arr(ji)=mpp_copy(td_mpp(ji))
+      ENDDO
+
+   END FUNCTION mpp__copy_arr
    !-------------------------------------------------------------------
    !> @brief This subroutine print some information about mpp strucutre.
@@ -297,7 +456,6 @@
    !> - Nov, 2013- Initial Version
    !
-   !> @param[in] td_mpp : mpp structure
-   !-------------------------------------------------------------------
-   ! @code
+   !> @param[in] td_mpp mpp structure
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_print(td_mpp)
       IMPLICIT NONE
@@ -307,5 +465,5 @@
 
       ! local variable
-      INTEGER(i4), PARAMETER :: ip_freq = 4
+      INTEGER(i4), PARAMETER :: il_freq = 4
 
       INTEGER(i4), DIMENSION(:,:), ALLOCATABLE :: il_proc
@@ -321,5 +479,5 @@
       !----------------------------------------------------------------
 
-      WRITE(*,'((a,a),2(/3x,a,a),6(/3x,a,i0))')&
+      WRITE(*,'((a,a),2(/3x,a,a),9(/3x,a,i0))')&
       &  "MPP : ",TRIM(td_mpp%c_name), &
       &  " type   : ",TRIM(td_mpp%c_type), &
@@ -330,5 +488,8 @@
       &  " preci  : ",td_mpp%i_preci, &
       &  " precj  : ",td_mpp%i_precj, &
-      &  " ndim   : ",td_mpp%i_ndim
+      &  " ndim   : ",td_mpp%i_ndim,  &
+      &  " overlap: ",td_mpp%i_ew, &
+      &  " perio  : ",td_mpp%i_perio, &
+      &  " pivot  : ",td_mpp%i_pivot
 
       ! print dimension
@@ -363,11 +524,12 @@
                &  td_mpp%t_proc(ji)%i_lej
 
-               !! attribute
-               !DO jj=1, td_mpp%t_proc(ji)%i_natt
-               !   CALL att_print(td_mpp%t_proc(ji)%t_att(jj))
-               !ENDDO
-
-
             ENDDO
+
+            IF( td_mpp%t_proc(1)%i_nvar > 0 )THEN
+               WRITE(*,'(/a)') " Variable(s) used : "
+               DO ji=1,td_mpp%t_proc(1)%i_nvar
+                  WRITE(*,'(3x,a)') TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name) 
+               ENDDO
+            ENDIF
 
          ELSE
@@ -387,11 +549,13 @@
                &  td_mpp%t_proc(ji)%i_lej
 
-               !! attribute
-               !DO jj=1, td_mpp%t_proc(ji)%i_natt
-               !   CALL att_print(td_mpp%t_proc(ji)%t_att(jj))
-               !ENDDO
-
             ENDDO
             
+            IF( td_mpp%t_proc(1)%i_nvar > 0 )THEN
+               WRITE(*,'(/a)') " Variable(s) used : "
+               DO ji=1,td_mpp%t_proc(1)%i_nvar
+                  WRITE(*,'(3x,a)') TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name) 
+               ENDDO
+            ENDIF
+
             ALLOCATE( il_proc(td_mpp%i_niproc,td_mpp%i_njproc) )
             ALLOCATE( il_lci(td_mpp%i_niproc,td_mpp%i_njproc) )
@@ -407,6 +571,6 @@
 
             jl = 1
-            DO jk = 1,(td_mpp%i_niproc-1)/ip_freq+1
-               jm = MIN(td_mpp%i_niproc, jl+ip_freq-1)
+            DO jk = 1,(td_mpp%i_niproc-1)/il_freq+1
+               jm = MIN(td_mpp%i_niproc, jl+il_freq-1)
                WRITE(*,*)
                WRITE(*,9401) (ji, ji = jl,jm)
@@ -419,5 +583,5 @@
                   WRITE(*,9400) ('***', ji = jl,jm-1)
                ENDDO
-               jl = jl+ip_freq
+               jl = jl+il_freq
             ENDDO
          
@@ -439,9 +603,8 @@
 
    END SUBROUTINE mpp_print
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function initialised mpp structure, given file name, mask and number of
-   !> processor following I and J
+   !> This function initialise mpp structure, given file name, 
+   !> and optionaly mask and number of processor following I and J
    !> @detail
    !> - If no total number of processor is defined (id_nproc), optimize 
@@ -452,25 +615,27 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[in] cd_file : file name of one file composing mpp domain
-   !> @param[in] id_mask : domain mask
-   !> @param[in] id_niproc : number of processors following i
-   !> @param[in] id_njproc : number of processors following j
-   !> @param[in] id_nproc  : total number of processors
-   !> @param[in] id_preci  : i-direction overlap region
-   !> @param[in] id_precj  : j-direction overlap region
-   !> @param[in] cd_type   : type of the files (cdf, cdf4, dimg)
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[in] cd_file   file name of one file composing mpp domain
+   !> @param[in] id_mask   domain mask
+   !> @param[in] id_niproc number of processors following i
+   !> @param[in] id_njproc number of processors following j
+   !> @param[in] id_nproc  total number of processors
+   !> @param[in] id_preci  i-direction overlap region
+   !> @param[in] id_precj  j-direction overlap region
+   !> @param[in] cd_type   type of the files (cdf, cdf4, dimg)
+   !> @param[in] id_ew     east-west overlap
+   !> @param[in] id_perio  NEMO periodicity index
+   !> @param[in] id_pivot  NEMO pivot point index F(0),T(1)
    !> @return mpp structure
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TMPP) FUNCTION mpp__init_mask(cd_file, id_mask,              &
    &                                  id_niproc, id_njproc, id_nproc,&
    &                                  id_preci, id_precj,            &
-                                      cd_type)
+                                      cd_type, id_ew, id_perio, id_pivot)
       IMPLICIT NONE
       ! Argument
       CHARACTER(LEN=*),            INTENT(IN) :: cd_file
-      INTEGER(i4), DIMENSION(:,:), INTENT(IN), OPTIONAL :: id_mask
+      INTEGER(i4), DIMENSION(:,:), INTENT(IN) :: id_mask
       INTEGER(i4),                 INTENT(IN), OPTIONAL :: id_niproc
       INTEGER(i4),                 INTENT(IN), OPTIONAL :: id_njproc
@@ -479,4 +644,7 @@
       INTEGER(i4),                 INTENT(IN), OPTIONAL :: id_precj
       CHARACTER(LEN=*),            INTENT(IN), OPTIONAL :: cd_type
+      INTEGER(i4),                 INTENT(IN), OPTIONAL :: id_ew
+      INTEGER(i4),                 INTENT(IN), OPTIONAL :: id_perio
+      INTEGER(i4),                 INTENT(IN), OPTIONAL :: id_pivot
 
       ! local variable
@@ -494,7 +662,4 @@
       ! clean mpp
       CALL mpp_clean(mpp__init_mask)
-
-      ! get mpp name
-      mpp__init_mask%c_name=TRIM(file_rename(cd_file))
 
       ! check type
@@ -518,14 +683,18 @@
       ENDIF
 
-      IF( PRESENT(id_mask) )THEN
-         ! get global domain dimension
-         il_shape(:)=SHAPE(id_mask)
-
-         tl_dim=dim_init('X',il_shape(1))
-         CALL mpp_add_dim(mpp__init_mask, tl_dim)
-
-         tl_dim=dim_init('Y',il_shape(2))
-         CALL mpp_add_dim(mpp__init_mask,tl_dim)
-      ENDIF
+      ! get mpp name
+      mpp__init_mask%c_name=TRIM(file_rename(cd_file))
+
+      ! get global domain dimension
+      il_shape(:)=SHAPE(id_mask)
+
+      tl_dim=dim_init('X',il_shape(1))
+      CALL mpp_add_dim(mpp__init_mask, tl_dim)
+
+      tl_dim=dim_init('Y',il_shape(2))
+      CALL mpp_add_dim(mpp__init_mask, tl_dim)
+
+      ! clean
+      CALL dim_clean(tl_dim)
 
       IF( (       PRESENT(id_niproc)  .AND. (.NOT. PRESENT(id_niproc))) .OR. &
@@ -546,4 +715,10 @@
       IF( PRESENT(id_precj) ) mpp__init_mask%i_precj= id_precj
 
+      ! east-west overlap
+      IF( PRESENT(id_ew) ) mpp__init_mask%i_ew= id_ew
+      ! NEMO periodicity
+      IF( PRESENT(id_perio) ) mpp__init_mask%i_perio= id_perio
+      IF( PRESENT(id_pivot) ) mpp__init_mask%i_pivot= id_pivot
+
       IF( mpp__init_mask%i_nproc  /= 0 .AND. &
       &   mpp__init_mask%i_niproc /= 0 .AND. &
@@ -560,5 +735,6 @@
       ELSE
 
-         IF( mpp__init_mask%i_niproc /= 0 .AND. mpp__init_mask%i_njproc /= 0 )THEN
+         IF( mpp__init_mask%i_niproc /= 0 .AND. &
+         &   mpp__init_mask%i_njproc /= 0 )THEN
             ! compute domain decomposition
             CALL mpp__compute( mpp__init_mask )
@@ -570,9 +746,14 @@
 
          ELSE
-            CALL logger_error("MPP INIT: can't define domain decomposition")
-            CALL logger_debug ("MPP INIT: maximum number of processor to be used "//&
-            &  "or number of processor following I and J direction must "//&
-            &  "be specified.")
+            CALL logger_warn("MPP INIT: number of processor to be used "//&
+            &                "not specify. force to one.")
+            mpp__init_mask%i_nproc  = 1
+            ! optimiz
+            CALL mpp__optimiz( mpp__init_mask, id_mask )
          ENDIF
+         CALL logger_info("MPP INIT: domain decoposition : "//&
+         &  'niproc('//TRIM(fct_str(mpp__init_mask%i_niproc))//') * '//&
+         &  'njproc('//TRIM(fct_str(mpp__init_mask%i_njproc))//') = '//&
+         &  'nproc('//TRIM(fct_str(mpp__init_mask%i_nproc))//')' )
 
          ! get domain type
@@ -593,4 +774,6 @@
             mpp__init_mask%t_proc(ji)%c_type=TRIM(mpp__init_mask%c_type)
 
+            ! clean
+            CALL dim_clean(tl_dim)
          ENDDO
 
@@ -640,12 +823,13 @@
          CALL mpp_add_att(mpp__init_mask, tl_att)         
 
+         ! clean
+         CALL att_clean(tl_att)
       ENDIF
 
    END FUNCTION mpp__init_mask
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function initialised mpp structure, given variable strcuture 
-   !> and number of processor following I and J
+   !> This function initialise mpp structure, given variable strcuture 
+   !> and optionaly number of processor following I and J
    !> @detail
    !> - If no total number of processor is defined (id_nproc), optimize 
@@ -656,20 +840,22 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[in] cd_file : file name of one file composing mpp domain
-   !> @param[in] td_var : variable structure
-   !> @param[in] id_niproc : number of processors following i
-   !> @param[in] id_njproc : number of processors following j
-   !> @param[in] id_nproc  : total number of processors
-   !> @param[in] id_preci  : i-direction overlap region
-   !> @param[in] id_precj  : j-direction overlap region
-   !> @param[in] cd_type   : type of the files (cdf, cdf4, dimg)
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[in] cd_file   file name of one file composing mpp domain
+   !> @param[in] td_var    variable structure
+   !> @param[in] id_niproc number of processors following i
+   !> @param[in] id_njproc number of processors following j
+   !> @param[in] id_nproc  total number of processors
+   !> @param[in] id_preci  i-direction overlap region
+   !> @param[in] id_precj  j-direction overlap region
+   !> @param[in] cd_type   type of the files (cdf, cdf4, dimg)
+   !> @param[in] id_perio  NEMO periodicity index
+   !> @param[in] id_pivot  NEMO pivot point index F(0),T(1)
    !> @return mpp structure
    !-------------------------------------------------------------------
-   !> @code
    TYPE(TMPP) FUNCTION mpp__init_var( cd_file, td_var,               &
    &                                  id_niproc, id_njproc, id_nproc,&
-   &                                  id_preci, id_precj, cd_type )
+   &                                  id_preci, id_precj, cd_type,   &
+   &                                  id_perio, id_pivot )
       IMPLICIT NONE
       ! Argument
@@ -682,16 +868,22 @@
       INTEGER(i4),      INTENT(IN), OPTIONAL :: id_precj
       CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: cd_type
+      INTEGER(i4),      INTENT(IN), OPTIONAL :: id_perio
+      INTEGER(i4),      INTENT(IN), OPTIONAL :: id_pivot
 
       ! local variable
-      INTEGER(i4), DIMENSION(:,:), ALLOCATABLE :: il_mask
+      INTEGER(i4), DIMENSION(:,:,:), ALLOCATABLE :: il_mask
       !----------------------------------------------------------------
 
       IF( ASSOCIATED(td_var%d_value) )THEN
-         ALLOCATE( il_mask(td_var%t_dim(1)%i_len, td_var%t_dim(2)%i_len) )
-         il_mask(:,:)=var_get_mask(td_var)
+         ALLOCATE( il_mask(td_var%t_dim(1)%i_len, &
+         &                 td_var%t_dim(2)%i_len, &
+         &                 td_var%t_dim(3)%i_len) )
+         il_mask(:,:,:)=var_get_mask(td_var)
          
-         mpp__init_var=mpp_init( cd_file, il_mask(:,:),         &
+         mpp__init_var=mpp_init( cd_file, il_mask(:,:,1),       &
          &                       id_niproc, id_njproc, id_nproc,&
-         &                       id_preci, id_precj, cd_type )
+         &                       id_preci, id_precj, cd_type,   &
+         &                       id_ew=td_var%i_ew, &
+         &                       id_perio=id_perio, id_pivot=id_pivot)
 
          DEALLOCATE(il_mask)
@@ -701,31 +893,49 @@
 
    END FUNCTION mpp__init_var
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a mpp structure, 
-   !> reading one restart dimg file, or some netcdf files.
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initalise a mpp structure given file structure. 
    !> @details 
-   !>
-   !> @warning td_file should be not opened
-   !>
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file strcuture
+   !> It reads restart dimg files, or some netcdf files.
+   !>
+   !> @warning 
+   !>  netcdf file must contains some attributes:
+   !>    - DOMAIN_number_total 
+   !>    - DOMAIN_size_global
+   !>    - DOMAIN_number
+   !>    - DOMAIN_position_first
+   !>    - DOMAIN_position_last
+   !>    - DOMAIN_halo_size_start
+   !>    - DOMAIN_halo_size_end
+   !>  or the file is assume to be no mpp file.
+   !>  
+   !> 
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file strcuture
+   !> @param[in] id_ew     east-west overlap
+   !> @param[in] id_perio  NEMO periodicity index
+   !> @param[in] id_pivot  NEMO pivot point index F(0),T(1)
    !> @return mpp structure
    !-------------------------------------------------------------------
-   ! @code
-   TYPE(TMPP) FUNCTION mpp__init_read( td_file )
+   TYPE(TMPP) FUNCTION mpp__init_file( td_file, id_ew, id_perio, id_pivot )
       IMPLICIT NONE
 
       ! Argument
       TYPE(TFILE), INTENT(IN) :: td_file
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_ew
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_perio
+      INTEGER(i4), INTENT(IN), OPTIONAL :: id_pivot
 
       ! local variable
       TYPE(TMPP)  :: tl_mpp
+      
       TYPE(TFILE) :: tl_file
+      
       TYPE(TDIM)  :: tl_dim
+
       TYPE(TATT)  :: tl_att
+
       INTEGER(i4) :: il_nproc
       INTEGER(i4) :: il_attid
@@ -737,5 +947,5 @@
 
       ! clean mpp
-      CALL mpp_clean(mpp__init_read)
+      CALL mpp_clean(mpp__init_file)
 
       ! check file type
@@ -743,6 +953,5 @@
          CASE('cdf')
             ! need to read all file to get domain decomposition
-
-            tl_file=td_file
+            tl_file=file_copy(td_file)
 
             ! open file
@@ -750,5 +959,5 @@
 
             ! read first file domain decomposition
-            tl_mpp=mpp__init_read_cdf(tl_file)
+            tl_mpp=mpp__init_file_cdf(tl_file)
 
             ! get number of processor/file to be read
@@ -779,19 +988,19 @@
 
                   ! read domain decomposition
-                  tl_mpp = mpp__init_read_cdf(tl_file)
+                  tl_mpp = mpp__init_file_cdf(tl_file)
                   IF( ji == 1 )THEN
-                     mpp__init_read=tl_mpp
+                     mpp__init_file=mpp_copy(tl_mpp)
                   ELSE
-                     IF( ANY( mpp__init_read%t_dim(1:2)%i_len /= &
+                     IF( ANY( mpp__init_file%t_dim(1:2)%i_len /= &
                                       tl_mpp%t_dim(1:2)%i_len) )THEN
 
-                        CALL logger_error("INIT READ: dimension from file "//&
+                        CALL logger_error("MPP INIT READ: dimension from file "//&
                         &     TRIM(tl_file%c_name)//" and mpp strcuture "//&
-                        &     TRIM(mpp__init_read%c_name)//"differ ")
+                        &     TRIM(mpp__init_file%c_name)//"differ ")
 
                      ELSE
 
                         ! add processor to mpp strcuture
-                        CALL mpp__add_proc(mpp__init_read, tl_mpp%t_proc(1))
+                        CALL mpp__add_proc(mpp__init_file, tl_mpp%t_proc(1))
 
                      ENDIF
@@ -802,74 +1011,84 @@
 
                ENDDO
-               IF( mpp__init_read%i_nproc /= il_nproc )THEN
-                  CALL logger_error("INIT READ: some processors can't be added &
+               IF( mpp__init_file%i_nproc /= il_nproc )THEN
+                  CALL logger_error("MPP INIT READ: some processors can't be added &
                   &               to mpp structure")
                ENDIF
 
             ELSE
-               mpp__init_read=tl_mpp
+               mpp__init_file=mpp_copy(tl_mpp)
             ENDIF
 
             ! mpp type
-            mpp__init_read%c_type=TRIM(td_file%c_type)
+            mpp__init_file%c_type=TRIM(td_file%c_type)
 
             ! mpp domain type
-            CALL mpp_get_dom(mpp__init_read)
+            CALL mpp_get_dom(mpp__init_file)
 
             ! create some attributes for domain decomposition (use with dimg file)
-            tl_att=att_init( "DOMAIN_number_total", mpp__init_read%i_nproc )
-            CALL mpp_add_att(mpp__init_read, tl_att)
-
-            tl_att=att_init( "DOMAIN_I_position_first", mpp__init_read%t_proc(:)%i_impp )
-            CALL mpp_add_att(mpp__init_read, tl_att)
-
-            tl_att=att_init( "DOMAIN_J_position_first", mpp__init_read%t_proc(:)%i_jmpp )
-            CALL mpp_add_att(mpp__init_read, tl_att)
-
-            tl_att=att_init( "DOMAIN_I_position_last", mpp__init_read%t_proc(:)%i_lci )
-            CALL mpp_add_att(mpp__init_read, tl_att)
-
-            tl_att=att_init( "DOMAIN_J_position_last", mpp__init_read%t_proc(:)%i_lcj )
-            CALL mpp_add_att(mpp__init_read, tl_att)
-
-            tl_att=att_init( "DOMAIN_I_halo_size_start", mpp__init_read%t_proc(:)%i_ldi )
-            CALL mpp_add_att(mpp__init_read, tl_att)
-
-            tl_att=att_init( "DOMAIN_J_halo_size_start", mpp__init_read%t_proc(:)%i_ldj )
-            CALL mpp_add_att(mpp__init_read, tl_att)
-
-            tl_att=att_init( "DOMAIN_I_halo_size_end", mpp__init_read%t_proc(:)%i_lei )
-            CALL mpp_add_att(mpp__init_read, tl_att)
-
-            tl_att=att_init( "DOMAIN_J_halo_size_end", mpp__init_read%t_proc(:)%i_lej )
-            CALL mpp_add_att(mpp__init_read, tl_att)
+            tl_att=att_init( "DOMAIN_number_total", mpp__init_file%i_nproc )
+            CALL mpp_add_att(mpp__init_file, tl_att)
+
+            tl_att=att_init( "DOMAIN_I_position_first", mpp__init_file%t_proc(:)%i_impp )
+            CALL mpp_add_att(mpp__init_file, tl_att)
+
+            tl_att=att_init( "DOMAIN_J_position_first", mpp__init_file%t_proc(:)%i_jmpp )
+            CALL mpp_add_att(mpp__init_file, tl_att)
+
+            tl_att=att_init( "DOMAIN_I_position_last", mpp__init_file%t_proc(:)%i_lci )
+            CALL mpp_add_att(mpp__init_file, tl_att)
+
+            tl_att=att_init( "DOMAIN_J_position_last", mpp__init_file%t_proc(:)%i_lcj )
+            CALL mpp_add_att(mpp__init_file, tl_att)
+
+            tl_att=att_init( "DOMAIN_I_halo_size_start", mpp__init_file%t_proc(:)%i_ldi )
+            CALL mpp_add_att(mpp__init_file, tl_att)
+
+            tl_att=att_init( "DOMAIN_J_halo_size_start", mpp__init_file%t_proc(:)%i_ldj )
+            CALL mpp_add_att(mpp__init_file, tl_att)
+
+            tl_att=att_init( "DOMAIN_I_halo_size_end", mpp__init_file%t_proc(:)%i_lei )
+            CALL mpp_add_att(mpp__init_file, tl_att)
+
+            tl_att=att_init( "DOMAIN_J_halo_size_end", mpp__init_file%t_proc(:)%i_lej )
+            CALL mpp_add_att(mpp__init_file, tl_att)
             
+            ! clean
+            CALL mpp_clean(tl_mpp)
+            CALL att_clean(tl_att)
 
          CASE('dimg')
             ! domain decomposition could be read in one file
 
-            tl_file=td_file
+            tl_file=file_copy(td_file)
             ! open file
+            CALL logger_debug("MPP INIT READ: open file "//TRIM(tl_file%c_name))
             CALL iom_open(tl_file)
 
+            CALL logger_debug("MPP INIT READ: read mpp structure ")
             ! read mpp structure
-            mpp__init_read=mpp__init_read_rstdimg(tl_file)
+            mpp__init_file=mpp__init_file_rstdimg(tl_file)
 
             ! mpp type
-            mpp__init_read%c_type=TRIM(td_file%c_type)
+            mpp__init_file%c_type=TRIM(td_file%c_type)
 
             ! mpp domain type
-            CALL mpp_get_dom(mpp__init_read)
+            CALL logger_debug("MPP INIT READ: mpp_get_dom ")
+            CALL mpp_get_dom(mpp__init_file)
 
             ! get processor size
-            DO ji=1,mpp__init_read%i_nproc
-
-               il_shape(:)=mpp_get_proc_size( mpp__init_read, ji )
+            CALL logger_debug("MPP INIT READ: get processor size ")
+            DO ji=1,mpp__init_file%i_nproc
+
+               il_shape(:)=mpp_get_proc_size( mpp__init_file, ji )
 
                tl_dim=dim_init('X',il_shape(1))
-               CALL file_add_dim(mpp__init_read%t_proc(ji), tl_dim)
+               CALL file_add_dim(mpp__init_file%t_proc(ji), tl_dim)
 
                tl_dim=dim_init('Y',il_shape(2))
-               CALL file_add_dim(mpp__init_read%t_proc(ji), tl_dim)            
+               CALL file_add_dim(mpp__init_file%t_proc(ji), tl_dim)            
+
+               ! clean
+               CALL dim_clean(tl_dim)
 
             ENDDO
@@ -879,10 +1098,30 @@
 
          CASE DEFAULT
-            CALL logger_error("INIT READ: invalid type for file "//&
+            CALL logger_error("MPP INIT READ: invalid type for file "//&
             &              TRIM(tl_file%c_name))
       END SELECT
 
-   END FUNCTION mpp__init_read
-   ! @endcode
+      ! east west overlap
+      IF( PRESENT(id_ew) ) mpp__init_file%i_ew=id_ew
+      ! NEMO periodicity
+      IF( PRESENT(id_perio) )THEN
+         mpp__init_file%i_perio= id_perio
+         SELECT CASE(id_perio)
+         CASE(3,4)
+            mpp__init_file%i_pivot=1
+         CASE(5,6)
+            mpp__init_file%i_pivot=0
+         CASE DEFAULT
+            mpp__init_file%i_pivot=1
+         END SELECT
+      ENDIF
+
+      IF( PRESENT(id_pivot) ) mpp__init_file%i_pivot= id_pivot
+
+      ! clean 
+      CALL file_clean(tl_file)
+
+      CALL logger_debug("MPP INIT READ: fin init_read ")
+   END FUNCTION mpp__init_file
    !-------------------------------------------------------------------
    !> @brief This function initalise a mpp structure, 
@@ -892,11 +1131,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file strcuture
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] td_file   file strcuture
    !> @return mpp structure
    !-------------------------------------------------------------------
-   ! @code
-   TYPE(TMPP) FUNCTION mpp__init_read_cdf( td_file )
+   TYPE(TMPP) FUNCTION mpp__init_file_cdf( td_file )
       IMPLICIT NONE
 
@@ -906,12 +1144,16 @@
       ! local variable
       INTEGER(i4) :: il_attid  ! attribute id
+      
       LOGICAL     :: ll_exist
       LOGICAL     :: ll_open
 
       TYPE(TATT)  :: tl_att
+
+      TYPE(TDIM)  :: tl_dim
+      
       TYPE(TFILE) :: tl_proc
       !----------------------------------------------------------------
 
-      CALL logger_trace(" INIT READ: netcdf file "//TRIM(td_file%c_name))
+      CALL logger_trace("MPP INIT READ: netcdf file "//TRIM(td_file%c_name))
 
       INQUIRE( FILE=TRIM(td_file%c_name), EXIST=ll_exist, OPENED=ll_open )
@@ -921,13 +1163,13 @@
          IF( td_file%i_id == 0 )THEN
             CALL logger_info(" id "//TRIM(fct_str(td_file%i_id))) 
-            CALL logger_error("INIT READ: netcdf file "//TRIM(td_file%c_name)//&
+            CALL logger_error("MPP INIT READ: netcdf file "//TRIM(td_file%c_name)//&
             &  " not opened")
          ELSE
 
             ! get mpp name
-            mpp__init_read_cdf%c_name=TRIM( file_rename(td_file%c_name) )
+            mpp__init_file_cdf%c_name=TRIM( file_rename(td_file%c_name) )
 
             ! add type
-            mpp__init_read_cdf%c_type="cdf"
+            mpp__init_file_cdf%c_type="cdf"
 
             ! global domain size
@@ -937,22 +1179,24 @@
             ENDIF
             IF( il_attid /= 0 )THEN
-               mpp__init_read_cdf%t_dim(1)= &
-               &  dim_init('X',INT(td_file%t_att(il_attid)%d_value(1)))
-               mpp__init_read_cdf%t_dim(2)= &
-               &  dim_init('Y',INT(td_file%t_att(il_attid)%d_value(2)))
-            ELSE
-               mpp__init_read_cdf%t_dim(1)= &
-               &  dim_init( td_file%t_dim(1)%c_name, td_file%t_dim(1)%i_len)
-               mpp__init_read_cdf%t_dim(2)= &
-               &  dim_init( td_file%t_dim(2)%c_name, td_file%t_dim(2)%i_len)
-
-            ENDIF
-            mpp__init_read_cdf%t_dim(3)= &
-            &  dim_init( td_file%t_dim(3)%c_name, td_file%t_dim(1)%i_len)
-            mpp__init_read_cdf%t_dim(4)= &
-            &  dim_init( td_file%t_dim(4)%c_name, td_file%t_dim(2)%i_len)
+               tl_dim=dim_init('X',INT(td_file%t_att(il_attid)%d_value(1)))
+               CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
+
+               tl_dim=dim_init('Y',INT(td_file%t_att(il_attid)%d_value(2)))
+               CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
+            ELSE ! assume only one file (not mpp)
+               tl_dim=dim_init( td_file%t_dim(1)%c_name, td_file%t_dim(1)%i_len)
+               CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
+
+               tl_dim=dim_init( td_file%t_dim(2)%c_name, td_file%t_dim(2)%i_len)
+               CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
+            ENDIF
+            tl_dim=dim_init( td_file%t_dim(3)%c_name, td_file%t_dim(3)%i_len)
+            CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
+
+            tl_dim=dim_init( td_file%t_dim(4)%c_name, td_file%t_dim(4)%i_len)
+            CALL mpp_add_dim(mpp__init_file_cdf,tl_dim)
 
             ! initialise file/processor
-            tl_proc=td_file
+            tl_proc=file_copy(td_file)
 
             ! processor id
@@ -968,5 +1212,5 @@
 
             ! processor dimension
-            tl_proc%t_dim(:)=td_file%t_dim(:)
+            tl_proc%t_dim(:)=dim_copy(td_file%t_dim(:))
 
             ! DOMAIN_position_first
@@ -992,6 +1236,6 @@
                tl_proc%i_lcj = INT(td_file%t_att(il_attid)%d_value(2)) + tl_proc%i_jmpp
             ELSE
-               tl_proc%i_lci = mpp__init_read_cdf%t_dim(1)%i_len
-               tl_proc%i_lcj = mpp__init_read_cdf%t_dim(2)%i_len
+               tl_proc%i_lci = mpp__init_file_cdf%t_dim(1)%i_len
+               tl_proc%i_lcj = mpp__init_file_cdf%t_dim(2)%i_len
             ENDIF
 
@@ -1018,11 +1262,11 @@
                tl_proc%i_lej = INT(td_file%t_att(il_attid)%d_value(2))
             ELSE
-               tl_proc%i_lei = mpp__init_read_cdf%t_dim(1)%i_len
-               tl_proc%i_lej = mpp__init_read_cdf%t_dim(2)%i_len
+               tl_proc%i_lei = mpp__init_file_cdf%t_dim(1)%i_len
+               tl_proc%i_lej = mpp__init_file_cdf%t_dim(2)%i_len
             ENDIF
 
             ! add attributes
             tl_att=att_init( "DOMAIN_size_global", &
-            &                mpp__init_read_cdf%t_dim(:)%i_len)
+            &                mpp__init_file_cdf%t_dim(:)%i_len)
             CALL file_move_att(tl_proc, tl_att)
 
@@ -1047,16 +1291,18 @@
 
             ! add processor to mpp structure
-            CALL mpp__add_proc(mpp__init_read_cdf, tl_proc)
-
+            CALL mpp__add_proc(mpp__init_file_cdf, tl_proc)
+
+            ! clean 
+            CALL file_clean(tl_proc)
+            CALL att_clean(tl_att)
          ENDIF
 
       ELSE
 
-         CALL logger_error("INIT READ: netcdf file "//TRIM(td_file%c_name)//&
+         CALL logger_error("MPP INIT READ: netcdf file "//TRIM(td_file%c_name)//&
          &  " do not exist")
 
       ENDIF      
-   END FUNCTION mpp__init_read_cdf
-   ! @endcode
+   END FUNCTION mpp__init_file_cdf
    !-------------------------------------------------------------------
    !> @brief This function initalise a mpp structure, 
@@ -1066,11 +1312,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_file : file strcuture
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   file strcuture
    !> @return mpp structure
    !-------------------------------------------------------------------
-   ! @code
-   TYPE(TMPP) FUNCTION mpp__init_read_rstdimg( td_file )
+   TYPE(TMPP) FUNCTION mpp__init_file_rstdimg( td_file )
       IMPLICIT NONE
 
@@ -1079,20 +1324,21 @@
 
       ! local variable
-      INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_recl                          ! record length 
-      INTEGER(i4) :: il_nx, il_ny, il_nz              ! x,y,z dimension 
-      INTEGER(i4) :: il_n0d, il_n1d, il_n2d, il_n3d   ! number of 0/1/2/3D variables 
-      INTEGER(i4) :: il_iglo, il_jglo                 ! domain global size
-      INTEGER(i4) :: il_rhd                           ! record of the header infos
-      INTEGER(i4) :: il_pni, il_pnj, il_pnij          ! domain decomposition
-      INTEGER(i4) :: il_area                          ! domain index
-
-      LOGICAL     ::  ll_exist
-      LOGICAL     ::  ll_open
+      INTEGER(i4)       :: il_status
+      INTEGER(i4)       :: il_recl                          ! record length 
+      INTEGER(i4)       :: il_nx, il_ny, il_nz              ! x,y,z dimension 
+      INTEGER(i4)       :: il_n0d, il_n1d, il_n2d, il_n3d   ! number of 0/1/2/3D variables 
+      INTEGER(i4)       :: il_iglo, il_jglo                 ! domain global size
+      INTEGER(i4)       :: il_rhd                           ! record of the header infos
+      INTEGER(i4)       :: il_pni, il_pnj, il_pnij          ! domain decomposition
+      INTEGER(i4)       :: il_area                          ! domain index
+
+      LOGICAL           ::  ll_exist
+      LOGICAL           ::  ll_open
 
       CHARACTER(LEN=lc) :: cl_file
 
-      TYPE(TDIM)  :: tl_dim ! dimension structure
-      TYPE(TATT)  :: tl_att
+      TYPE(TDIM)        :: tl_dim ! dimension structure
+      TYPE(TATT)        :: tl_att
+      TYPE(TFILE)       :: tl_proc
 
       ! loop indices
@@ -1104,5 +1350,5 @@
 
          IF( .NOT. ll_open )THEN
-            CALL logger_error("INIT READ: dimg file "//TRIM(td_file%c_name)//&
+            CALL logger_error("MPP INIT READ: dimg file "//TRIM(td_file%c_name)//&
             &  " not opened")
          ELSE
@@ -1118,22 +1364,35 @@
             CALL fct_err(il_status)
             IF( il_status /= 0 )THEN
-               CALL logger_error("INIT READ: read first line header of "//&
+               CALL logger_error("MPP INIT READ: read first line header of "//&
                &              TRIM(td_file%c_name))
             ENDIF
 
             ! get mpp name
-            mpp__init_read_rstdimg%c_name=TRIM( file_rename(td_file%c_name) )
+            mpp__init_file_rstdimg%c_name=TRIM( file_rename(td_file%c_name) )
+
+            ! add type
+            mpp__init_file_rstdimg%c_type="dimg"
 
             ! number of processors to be read
-            mpp__init_read_rstdimg%i_nproc  = il_pnij
-            mpp__init_read_rstdimg%i_niproc = il_pni
-            mpp__init_read_rstdimg%i_njproc = il_pnj
-
-            IF( ASSOCIATED(mpp__init_read_rstdimg%t_proc) )THEN
-               DEALLOCATE(mpp__init_read_rstdimg%t_proc)
-            ENDIF
-            ALLOCATE( mpp__init_read_rstdimg%t_proc(il_pnij) , stat=il_status )
+            mpp__init_file_rstdimg%i_nproc  = il_pnij
+            mpp__init_file_rstdimg%i_niproc = il_pni
+            mpp__init_file_rstdimg%i_njproc = il_pnj
+
+            IF( ASSOCIATED(mpp__init_file_rstdimg%t_proc) )THEN
+               CALL file_clean(mpp__init_file_rstdimg%t_proc(:))
+               DEALLOCATE(mpp__init_file_rstdimg%t_proc)
+            ENDIF
+            ALLOCATE( mpp__init_file_rstdimg%t_proc(il_pnij) , stat=il_status )
+
+            tl_proc=file_copy(td_file)
+            ! remove dimension from file
+            CALL dim_clean(tl_proc%t_dim(:))
+            ! initialise file/processors
+            DO ji=1,mpp__init_file_rstdimg%i_nproc
+               mpp__init_file_rstdimg%t_proc(ji)=file_copy(tl_proc)
+            ENDDO
+
             IF( il_status /= 0 )THEN
-               CALL logger_error("INIT READ: not enough space to read domain &
+               CALL logger_error("MPP INIT READ: not enough space to read domain &
                &              decomposition in file "//TRIM(td_file%c_name))
             ENDIF
@@ -1148,132 +1407,135 @@
             &     il_area,                         &
             &     il_iglo, il_jglo,                &
-            &     mpp__init_read_rstdimg%t_proc(:)%i_lci,    &
-            &     mpp__init_read_rstdimg%t_proc(:)%i_lcj,    &
-            &     mpp__init_read_rstdimg%t_proc(:)%i_ldi,    &
-            &     mpp__init_read_rstdimg%t_proc(:)%i_ldj,    &
-            &     mpp__init_read_rstdimg%t_proc(:)%i_lei,    &
-            &     mpp__init_read_rstdimg%t_proc(:)%i_lej,    &
-            &     mpp__init_read_rstdimg%t_proc(:)%i_impp,   &
-            &     mpp__init_read_rstdimg%t_proc(:)%i_jmpp
+            &     mpp__init_file_rstdimg%t_proc(:)%i_lci,    &
+            &     mpp__init_file_rstdimg%t_proc(:)%i_lcj,    &
+            &     mpp__init_file_rstdimg%t_proc(:)%i_ldi,    &
+            &     mpp__init_file_rstdimg%t_proc(:)%i_ldj,    &
+            &     mpp__init_file_rstdimg%t_proc(:)%i_lei,    &
+            &     mpp__init_file_rstdimg%t_proc(:)%i_lej,    &
+            &     mpp__init_file_rstdimg%t_proc(:)%i_impp,   &
+            &     mpp__init_file_rstdimg%t_proc(:)%i_jmpp
             CALL fct_err(il_status)
             IF( il_status /= 0 )THEN
-               CALL logger_error("INIT READ: read first line of "//&
+               CALL logger_error("MPP INIT READ: read first line of "//&
                &              TRIM(td_file%c_name))
             ENDIF
 
-            ! mpp dimension
+            ! global domain size
             tl_dim=dim_init('X',il_iglo)
-            CALL mpp_add_dim(mpp__init_read_rstdimg,tl_dim)
+            CALL mpp_add_dim(mpp__init_file_rstdimg,tl_dim)
             tl_dim=dim_init('Y',il_jglo)
-            CALL mpp_add_dim(mpp__init_read_rstdimg,tl_dim)
-
-            DO ji=1,mpp__init_read_rstdimg%i_nproc
+            CALL mpp_add_dim(mpp__init_file_rstdimg,tl_dim)
+
+            tl_dim=dim_init('Z',il_nz)
+            CALL mpp_add_dim(mpp__init_file_rstdimg,tl_dim)
+
+            DO ji=1,mpp__init_file_rstdimg%i_nproc
                ! get file name
                cl_file =  file_rename(td_file%c_name,ji)
-               mpp__init_read_rstdimg%t_proc(ji)%c_name = TRIM(cl_file)
+               mpp__init_file_rstdimg%t_proc(ji)%c_name = TRIM(cl_file)
                ! update processor id
-               mpp__init_read_rstdimg%t_proc(ji)%i_pid=ji
+               mpp__init_file_rstdimg%t_proc(ji)%i_pid=ji
 
                ! add attributes
                tl_att=att_init( "DOMAIN_number", ji )
-               CALL file_move_att(mpp__init_read_rstdimg%t_proc(ji), tl_att) 
+               CALL file_move_att(mpp__init_file_rstdimg%t_proc(ji), tl_att) 
 
                tl_att=att_init( "DOMAIN_position_first", &
-               &                (/mpp__init_read_rstdimg%t_proc(ji)%i_impp, &
-               &                  mpp__init_read_rstdimg%t_proc(ji)%i_jmpp /) )
-               CALL file_move_att(mpp__init_read_rstdimg%t_proc(ji), tl_att)
+               &                (/mpp__init_file_rstdimg%t_proc(ji)%i_impp, &
+               &                  mpp__init_file_rstdimg%t_proc(ji)%i_jmpp /) )
+               CALL file_move_att(mpp__init_file_rstdimg%t_proc(ji), tl_att)
 
                tl_att=att_init( "DOMAIN_position_last", &
-               &                (/mpp__init_read_rstdimg%t_proc(ji)%i_lci, &
-               &                  mpp__init_read_rstdimg%t_proc(ji)%i_lcj /) )
-               CALL file_move_att(mpp__init_read_rstdimg%t_proc(ji), tl_att)
+               &                (/mpp__init_file_rstdimg%t_proc(ji)%i_lci, &
+               &                  mpp__init_file_rstdimg%t_proc(ji)%i_lcj /) )
+               CALL file_move_att(mpp__init_file_rstdimg%t_proc(ji), tl_att)
 
                tl_att=att_init( "DOMAIN_halo_size_start", &
-               &                (/mpp__init_read_rstdimg%t_proc(ji)%i_ldi, &
-               &                  mpp__init_read_rstdimg%t_proc(ji)%i_ldj /) )
-               CALL file_move_att(mpp__init_read_rstdimg%t_proc(ji), tl_att)               
+               &                (/mpp__init_file_rstdimg%t_proc(ji)%i_ldi, &
+               &                  mpp__init_file_rstdimg%t_proc(ji)%i_ldj /) )
+               CALL file_move_att(mpp__init_file_rstdimg%t_proc(ji), tl_att)               
 
                tl_att=att_init( "DOMAIN_halo_size_end", &
-               &                (/mpp__init_read_rstdimg%t_proc(ji)%i_lei, &
-               &                  mpp__init_read_rstdimg%t_proc(ji)%i_lej /) )
-               CALL file_move_att(mpp__init_read_rstdimg%t_proc(ji), tl_att)
+               &                (/mpp__init_file_rstdimg%t_proc(ji)%i_lei, &
+               &                  mpp__init_file_rstdimg%t_proc(ji)%i_lej /) )
+               CALL file_move_att(mpp__init_file_rstdimg%t_proc(ji), tl_att)
             ENDDO
-      
+ 
             ! add type
-            mpp__init_read_rstdimg%t_proc(:)%c_type="dimg"
+            mpp__init_file_rstdimg%t_proc(:)%c_type="dimg"
 
             ! add attributes
             tl_att=att_init( "DOMAIN_size_global", &
-            &                mpp__init_read_rstdimg%t_dim(:)%i_len)
-            CALL mpp_move_att(mpp__init_read_rstdimg, tl_att)
+            &                mpp__init_file_rstdimg%t_dim(:)%i_len)
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_number_total", &
-            &                 mpp__init_read_rstdimg%i_nproc )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%i_nproc )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_I_number_total", &
-            &                 mpp__init_read_rstdimg%i_niproc )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%i_niproc )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_J_number_total", &
-            &                 mpp__init_read_rstdimg%i_njproc )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%i_njproc )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_I_position_first", &
-            &                 mpp__init_read_rstdimg%t_proc(:)%i_impp )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%t_proc(:)%i_impp )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_J_position_first", &
-            &                 mpp__init_read_rstdimg%t_proc(:)%i_jmpp )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%t_proc(:)%i_jmpp )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_I_position_last", &
-            &                 mpp__init_read_rstdimg%t_proc(:)%i_lci )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%t_proc(:)%i_lci )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_J_position_last", &
-            &                 mpp__init_read_rstdimg%t_proc(:)%i_lcj )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%t_proc(:)%i_lcj )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_I_halo_size_start", &
-            &                 mpp__init_read_rstdimg%t_proc(:)%i_ldi )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%t_proc(:)%i_ldi )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_J_halo_size_start", &
-            &                 mpp__init_read_rstdimg%t_proc(:)%i_ldj )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%t_proc(:)%i_ldj )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_I_halo_size_end", &
-            &                 mpp__init_read_rstdimg%t_proc(:)%i_lei )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%t_proc(:)%i_lei )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
 
             tl_att=att_init( "DOMAIN_J_halo_size_end", &
-            &                 mpp__init_read_rstdimg%t_proc(:)%i_lej )
-            CALL mpp_add_att(mpp__init_read_rstdimg, tl_att)
+            &                 mpp__init_file_rstdimg%t_proc(:)%i_lej )
+            CALL mpp_move_att(mpp__init_file_rstdimg, tl_att)
+
+            ! clean
+            CALL dim_clean(tl_dim)
+            CALL att_clean(tl_att)
          ENDIF
 
       ELSE
 
-         CALL logger_error("INIT READ: dimg file "//TRIM(td_file%c_name)//&
+         CALL logger_error("MPP INIT READ: dimg file "//TRIM(td_file%c_name)//&
          &  " do not exist")
 
       ENDIF
 
-   END FUNCTION mpp__init_read_rstdimg
-   ! @endcode
+   END FUNCTION mpp__init_file_rstdimg
    !-------------------------------------------------------------------
    !> @brief This function check if variable and mpp structure use same
    !> dimension.
    !
-   !> @details
-   !
    !> @author J.Paul
    !> - Nov, 2013- Initial Version
    !
-   !> @param[in] td_mpp : mpp structure
-   !> @param[in] td_proc : processor structure
+   !> @param[in] td_mpp    mpp structure
+   !> @param[in] td_proc   processor structure
    !> @return dimension of processor and mpp structure agree (or not)
    !-------------------------------------------------------------------
-   ! @code
    LOGICAL FUNCTION mpp__check_proc_dim(td_mpp, td_proc)
       IMPLICIT NONE
@@ -1301,5 +1563,5 @@
             mpp__check_proc_dim=.FALSE.
 
-            CALL logger_error( " CHECK DIM: processor and mpp dimension differ" )
+            CALL logger_error( "MPP CHECK DIM: processor and mpp dimension differ" )
 
          ENDIF
@@ -1312,5 +1574,5 @@
             mpp__check_proc_dim=.FALSE.
 
-            CALL logger_error( " CHECK DIM: processor and mpp dimension differ" )
+            CALL logger_error( "MPP CHECK DIM: processor and mpp dimension differ" )
 
          ENDIF
@@ -1318,20 +1580,14 @@
 
    END FUNCTION mpp__check_proc_dim
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !>    This subroutine add variable to mpp structure.
-   !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    td_var : variable strcuture
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !>    This subroutine add variable in all files of mpp structure.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in]    td_var variable strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_add_var( td_mpp, td_var )
       IMPLICIT NONE
@@ -1350,11 +1606,6 @@
       IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
 
-         CALL logger_error( "MPP ADD VAR: domain decomposition not define "//&
-         &               "for mpp "//TRIM(td_mpp%c_name))
-
-      ELSEIF( td_mpp%i_ndim == 0 )THEN
-
-         CALL logger_error( " MPP ADD VAR: no dimension define for "//&
-         &               " mpp strcuture "//TRIM(td_mpp%c_name))
+         CALL logger_error( "MPP ADD VAR: processor decomposition not "//&
+         &  "define for mpp "//TRIM(td_mpp%c_name))
 
       ELSE
@@ -1367,6 +1618,6 @@
             il_varid=0
             IF( ASSOCIATED(td_mpp%t_proc(1)%t_var) )THEN
-               il_varid=var_get_id( td_mpp%t_proc(1)%t_var(:), &
-               &                    td_var%c_name, td_var%c_stdname )
+               il_varid=var_get_index( td_mpp%t_proc(1)%t_var(:), &
+               &                       td_var%c_name, td_var%c_stdname )
             ENDIF
 
@@ -1393,4 +1644,12 @@
                IF( mpp__check_dim(td_mpp, td_var) )THEN
 
+                  ! update dimension if need be
+                  DO ji=1,ip_maxdim
+                     IF( td_var%t_dim(ji)%l_use .AND. &
+                     &   .NOT. td_mpp%t_dim(ji)%l_use )THEN
+                        CALL mpp_add_dim(td_mpp,td_var%t_dim(ji))
+                     ENDIF
+                  ENDDO
+
                   ! add variable in each processor
                   DO ji=1,td_mpp%i_nproc
@@ -1401,4 +1660,6 @@
                      CALL file_add_var(td_mpp%t_proc(ji), tl_var)
 
+                     ! clean
+                     CALL var_clean(tl_var)
                   ENDDO
 
@@ -1409,20 +1670,16 @@
 
    END SUBROUTINE mpp_add_var
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function extract from variable structure, part that will 
+   !-------------------------------------------------------------------
+   !> @brief This function extract, from variable structure, part that will 
    !> be written in processor id_procid.<br/>
    !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp : mpp structure
-   !> @param[in] td_var : variable structure
-   !> @param[in] id_procid : processor id
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_mpp    mpp structure
+   !> @param[in] td_var    variable structure
+   !> @param[in] id_procid processor id
    !> @return variable structure
    !-------------------------------------------------------------------
-   ! @code   
    TYPE(TVAR) FUNCTION mpp__split_var(td_mpp, td_var, id_procid)
       IMPLICIT NONE
@@ -1444,45 +1701,76 @@
 
       ! copy mpp
-      mpp__split_var=td_var
-
-      ! remove value over global domain from pointer
-      CALL var_del_value( mpp__split_var )
-
-      ! get processor dimension
-      il_size(:)=mpp_get_proc_size( td_mpp, id_procid )
-
-      ! define new dimension in variable structure 
-      IF( td_var%t_dim(1)%l_use )THEN
-         tl_dim=dim_init( TRIM(td_var%t_dim(1)%c_name), il_size(1) )
-         CALL var_move_dim( mpp__split_var, tl_dim )
-      ENDIF
-      IF( td_var%t_dim(2)%l_use )THEN
-         tl_dim=dim_init( TRIM(td_var%t_dim(2)%c_name), il_size(2) )
-         CALL var_move_dim( mpp__split_var, tl_dim )      
-      ENDIF
-
-      ! get processor indices
-      il_ind(:)=mpp_get_proc_index( td_mpp, id_procid )
-      il_i1 = il_ind(1)
-      il_i2 = il_ind(2)
-      il_j1 = il_ind(3)
-      il_j2 = il_ind(4)
-
-      IF( .NOT. td_var%t_dim(1)%l_use )THEN
-         il_i1=1 
-         il_i2=1 
-      ENDIF
-
-      IF( .NOT. td_var%t_dim(2)%l_use )THEN
-         il_j1=1 
-         il_j2=1 
-      ENDIF      
-
-      ! add variable value on processor
-      CALL var_add_value( mpp__split_var, &
-      &                   td_var%d_value(il_i1:il_i2, il_j1:il_j2, :, :) )
+      mpp__split_var=var_copy(td_var)
+
+      IF( ASSOCIATED(td_var%d_value) )THEN
+         ! remove value over global domain from pointer
+         CALL var_del_value( mpp__split_var )
+
+         ! get processor dimension
+         il_size(:)=mpp_get_proc_size( td_mpp, id_procid )
+
+         ! define new dimension in variable structure 
+         IF( td_var%t_dim(1)%l_use )THEN
+            tl_dim=dim_init( TRIM(td_var%t_dim(1)%c_name), il_size(1) )
+            CALL var_move_dim( mpp__split_var, tl_dim )
+         ENDIF
+         IF( td_var%t_dim(2)%l_use )THEN
+            tl_dim=dim_init( TRIM(td_var%t_dim(2)%c_name), il_size(2) )
+            CALL var_move_dim( mpp__split_var, tl_dim )      
+         ENDIF
+
+         ! get processor indices
+         il_ind(:)=mpp_get_proc_index( td_mpp, id_procid )
+         il_i1 = il_ind(1)
+         il_i2 = il_ind(2)
+         il_j1 = il_ind(3)
+         il_j2 = il_ind(4)
+
+         IF( .NOT. td_var%t_dim(1)%l_use )THEN
+            il_i1=1 
+            il_i2=1 
+         ENDIF
+
+         IF( .NOT. td_var%t_dim(2)%l_use )THEN
+            il_j1=1 
+            il_j2=1 
+         ENDIF      
+
+         ! add variable value on processor
+         CALL var_add_value( mpp__split_var, &
+         &                   td_var%d_value(il_i1:il_i2, il_j1:il_j2, :, :) )
+      ENDIF
 
    END FUNCTION mpp__split_var
-   !> @endcode
+   !-------------------------------------------------------------------
+   !> @brief 
+   !>  This subroutine delete all variable in mpp strcuture.
+   !>
+   !> @author J.Paul
+   !> @date October, 2014 - Initial version
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !-------------------------------------------------------------------
+   SUBROUTINE mpp__del_var_mpp( td_mpp )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TMPP), INTENT(INOUT) :: td_mpp
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      CALL logger_info( &
+      &  "MPP CLEAN VAR: reset all variable "//&
+      &  "in mpp strcuture "//TRIM(td_mpp%c_name) )
+
+      IF( ASSOCIATED(td_mpp%t_proc) )THEN
+         DO ji=td_mpp%t_proc(1)%i_nvar,1,-1
+            CALL mpp_del_var(td_mpp, td_mpp%t_proc(1)%t_var(ji))
+         ENDDO
+      ENDIF
+
+   END SUBROUTINE mpp__del_var_mpp
    !-------------------------------------------------------------------
    !> @brief
@@ -1490,15 +1778,10 @@
    !> structure.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    td_var : variable strcuture
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in]    td_var variable strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__del_var_str( td_mpp, td_var )
       IMPLICIT NONE
@@ -1517,5 +1800,5 @@
       IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
 
-         CALL logger_error( " DEL VAR: domain decomposition not define "//&
+         CALL logger_error( "MPP DEL VAR: domain decomposition not define "//&
          &               " in mpp strcuture "//TRIM(td_mpp%c_name))
 
@@ -1525,14 +1808,14 @@
          il_varid = 0
          IF( ASSOCIATED(td_mpp%t_proc(1)%t_var) )THEN
-            il_varid=var_get_id( td_mpp%t_proc(1)%t_var(:), &
-            &                    td_var%c_name, td_var%c_stdname )
+            il_varid=var_get_index( td_mpp%t_proc(1)%t_var(:), &
+            &                       td_var%c_name, td_var%c_stdname )
          ENDIF
          IF( il_varid == 0 )THEN
             CALL logger_error( &
-            &  " DEL VAR: no variable "//TRIM(td_var%c_name)//&
+            &  "MPP DEL VAR: no variable "//TRIM(td_var%c_name)//&
             &  ", in mpp structure "//TRIM(td_mpp%c_name) )
 
             DO ji=1,td_mpp%t_proc(1)%i_nvar
-               CALL logger_debug( " DEL VAR: in mpp structure : &
+               CALL logger_debug( "MPP DEL VAR: in mpp structure : &
                &  variable : "//TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name)//&
                &  ", standard name "//&
@@ -1551,20 +1834,14 @@
       ENDIF
    END SUBROUTINE mpp__del_var_str
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !>    This subroutine delete variable in mpp structure, given variable name.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    cd_name: variable name
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp    mpp strcuture
+   !> @param[in]    cd_name   variable name
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__del_var_name( td_mpp, cd_name )
       IMPLICIT NONE
@@ -1579,5 +1856,5 @@
       IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
 
-         CALL logger_error( " DEL VAR: domain decomposition not define "//&
+         CALL logger_error( "MPP DEL VAR: domain decomposition not define "//&
          &               " in mpp strcuture "//TRIM(td_mpp%c_name))
 
@@ -1585,5 +1862,5 @@
 
          IF( td_mpp%t_proc(1)%i_nvar == 0 )THEN
-            CALL logger_debug( " DEL VAR NAME: no variable associated to mpp &
+            CALL logger_debug( "MPP DEL VAR NAME: no variable associated to mpp &
             &                 structure "//TRIM(td_mpp%c_name) )
          ELSE
@@ -1592,11 +1869,12 @@
             il_varid=0
             IF( ASSOCIATED(td_mpp%t_proc(1)%t_var) )THEN
-               il_varid=var_get_id( td_mpp%t_proc(1)%t_var(:), &
-               &                    cd_name )
-            ENDIF
+               il_varid=var_get_index( td_mpp%t_proc(1)%t_var(:), &
+               &                       cd_name )
+            ENDIF
+
             IF( il_varid == 0 )THEN
 
                CALL logger_warn( &
-               &  "DEL VAR : there is no variable with name "//&
+               &  "MPP DEL VAR : there is no variable with name "//&
                &  "or standard name "//TRIM(ADJUSTL(cd_name))//&
                &  " in mpp structure "//TRIM(td_mpp%c_name))
@@ -1611,22 +1889,14 @@
       ENDIF
    END SUBROUTINE mpp__del_var_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !>    This subroutine overwrite variable in mpp structure.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    td_var : variable structure
-   !> @todo
-   !> - voir si il ne faut pas redefinir (__copy) variable si elle vient de mpp
-   !> exemple CALL  mpp_move_var( td_mpp, td_mpp%t_proc()%t_var )
-   !> remarque cas probabelement impossible puisque td_var doit avoir dim de td_mpp
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in]    td_var variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_move_var( td_mpp, td_var )
       IMPLICIT NONE
@@ -1639,5 +1909,5 @@
       !----------------------------------------------------------------
       ! copy variable
-      tl_var=td_var
+      tl_var=var_copy(td_var)
 
       ! remove processor
@@ -1647,4 +1917,7 @@
       CALL mpp_add_var(td_mpp, tl_var)
 
+      ! clean 
+      CALL var_clean(tl_var)
+
    END SUBROUTINE mpp_move_var
    !> @endcode
@@ -1653,16 +1926,13 @@
    !>    This subroutine add processor to mpp structure.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    td_proc : processor strcuture
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp    mpp strcuture
+   !> @param[in]    td_proc   processor strcuture
    !
    !> @todo 
    !> - check proc type
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE mpp__add_proc( td_mpp, td_proc )
       IMPLICIT NONE
@@ -1698,10 +1968,10 @@
 
             CALL logger_error( &
-            &  " ADD PROC: processor "//TRIM(fct_str(td_proc%i_pid))//&
+            &  "MPP ADD PROC: processor "//TRIM(fct_str(td_proc%i_pid))//&
             &  ", already in mpp structure " )
 
       ELSE
-         
-         CALL logger_trace("ADD PROC: add processor "//&
+ 
+         CALL logger_trace("MPP ADD PROC: add processor "//&
          &               TRIM(fct_str(td_mpp%i_nproc+1))//" in mpp structure")
 
@@ -1716,16 +1986,17 @@
             IF(il_status /= 0 )THEN
 
-               CALL logger_error( " ADD PROC: not enough space to put processor &
+               CALL logger_error( "MPP ADD PROC: not enough space to put processor &
                &               in mpp structure")
 
             ELSE
                ! save temporary mpp structure
-               tl_proc(:)=td_mpp%t_proc(:)
-
-               DEALLOCATE( td_mpp%t_proc )
+               tl_proc(:)=file_copy(td_mpp%t_proc(:))
+
+               CALL file_clean( td_mpp%t_proc(:) )
+               DEALLOCATE(td_mpp%t_proc)
                ALLOCATE( td_mpp%t_proc(td_mpp%i_nproc+1), stat=il_status)
                IF(il_status /= 0 )THEN
 
-                  CALL logger_error( " ADD PROC: not enough space to put "//&
+                  CALL logger_error( "MPP ADD PROC: not enough space to put "//&
                   &  "processor in mpp structure ")
 
@@ -1733,11 +2004,13 @@
 
                ! copy processor in mpp before
-               ! processor with lesser id than new processor
-               td_mpp%t_proc( 1:il_procid ) = tl_proc( 1:il_procid )
+               ! processor with lower id than new processor
+               td_mpp%t_proc( 1:il_procid ) = file_copy(tl_proc( 1:il_procid ))
 
                ! processor with greater id than new processor
                td_mpp%t_proc( il_procid+1 : td_mpp%i_nproc+1 ) = &
-               &                 tl_proc( il_procid : td_mpp%i_nproc )
-
+               &              file_copy(tl_proc( il_procid : td_mpp%i_nproc ))
+
+               ! clean
+               CALL file_clean(tl_proc(:))
                DEALLOCATE(tl_proc)
             ENDIF
@@ -1746,4 +2019,5 @@
             ! no processor in mpp structure
             IF( ASSOCIATED(td_mpp%t_proc) )THEN
+               CALL file_clean(td_mpp%t_proc(:))
                DEALLOCATE(td_mpp%t_proc)
             ENDIF
@@ -1751,5 +2025,5 @@
             IF(il_status /= 0 )THEN
 
-               CALL logger_error( " ADD PROC: not enough space to put "//&
+               CALL logger_error( "MPP ADD PROC: not enough space to put "//&
                &  "processor in mpp structure " )
 
@@ -1759,10 +2033,10 @@
          ! check dimension
          IF( ANY(td_mpp%t_dim(1:2)%i_len < td_proc%t_dim(1:2)%i_len) )THEN
-            CALL logger_error( "ADD PROC: mpp structure and new processor "//&
+            CALL logger_error( "MPP ADD PROC: mpp structure and new processor "//&
             &  " dimension differ. ")
-            CALL logger_debug("ADD PROC: mpp dimension ("//&
+            CALL logger_debug("MPP ADD PROC: mpp dimension ("//&
             &  TRIM(fct_str(td_mpp%t_dim(1)%i_len))//","//&
             &  TRIM(fct_str(td_mpp%t_dim(2)%i_len))//")" )
-            CALL logger_debug("ADD PROC: processor dimension ("//&
+            CALL logger_debug("MPP ADD PROC: processor dimension ("//&
             &  TRIM(fct_str(td_proc%t_dim(1)%i_len))//","//&
             &  TRIM(fct_str(td_proc%t_dim(2)%i_len))//")" )
@@ -1771,25 +2045,19 @@
 
             ! add new processor
-            td_mpp%t_proc(td_mpp%i_nproc)=td_proc
+            td_mpp%t_proc(td_mpp%i_nproc)=file_copy(td_proc)
          ENDIF
 
       ENDIF
    END SUBROUTINE mpp__add_proc
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !>    This subroutine delete processor in mpp structure, given processor id.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    id_procid : processor id
-   !
-   !> @todo check proc id exist
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !>
+   !> @param[inout] td_mpp    mpp strcuture
+   !> @param[in]    id_procid processor id
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__del_proc_id( td_mpp, id_procid )
       IMPLICIT NONE
@@ -1803,4 +2071,6 @@
       INTEGER(i4), DIMENSION(1) :: il_ind
       TYPE(TFILE), DIMENSION(:), ALLOCATABLE :: tl_proc
+
+      ! loop indices
       !----------------------------------------------------------------
 
@@ -1808,14 +2078,16 @@
       il_procid=il_ind(1)
       IF( il_procid == 0 )THEN
-         CALL logger_error("DEL PROC: no processor "//TRIM(fct_str(id_procid))//&
-         &              " associated to mpp structure")
+         CALL logger_error("MPP DEL PROC: no processor "//&
+         &                 TRIM(fct_str(id_procid))//&
+         &                 " associated to mpp structure")
       ELSE
-         CALL logger_trace("DEL PROC: remove processor "//TRIM(fct_str(id_procid)))
+         CALL logger_trace("DEL PROC: remove processor "//&
+         &                 TRIM(fct_str(id_procid)))
 
          IF( td_mpp%i_nproc > 1 )THEN
             ALLOCATE( tl_proc(td_mpp%i_nproc-1), stat=il_status )
             IF(il_status /= 0 )THEN
-               CALL logger_error( " DEL PROC: not enough space to put processor &
-               &                 in temporary mpp structure")
+               CALL logger_error( "MPP DEL PROC: not enough space to put &
+               &  processor in temporary mpp structure")
 
             ELSE
@@ -1823,22 +2095,26 @@
                ! save temporary processor's mpp structure
                IF( il_procid > 1 )THEN
-                  tl_proc(1:il_procid-1)=td_mpp%t_proc(1:il_procid-1)
+                  tl_proc(1:il_procid-1)=file_copy(td_mpp%t_proc(1:il_procid-1))
                ENDIF
-               tl_proc(il_procid:)=td_mpp%t_proc(il_procid+1:)
+
+               IF( il_procid < td_mpp%i_nproc )THEN
+                  tl_proc(il_procid:)=file_copy(td_mpp%t_proc(il_procid+1:))
+               ENDIF
 
                ! new number of processor in mpp
                td_mpp%i_nproc=td_mpp%i_nproc-1
 
-               DEALLOCATE( td_mpp%t_proc )
+               CALL file_clean( td_mpp%t_proc(:) )
+               DEALLOCATE(td_mpp%t_proc)
                ALLOCATE( td_mpp%t_proc(td_mpp%i_nproc), stat=il_status )
                IF(il_status /= 0 )THEN
 
-                  CALL logger_error( " DEL PROC: not enough space to put processors &
-                  &               in mpp structure " )
+                  CALL logger_error( "MPP DEL PROC: not enough space &
+                  &  to put processors in mpp structure " )
 
                ELSE
 
                   ! copy processor in mpp before
-                  td_mpp%t_proc(:)=tl_proc(:)
+                  td_mpp%t_proc(:)=file_copy(tl_proc(:))
 
                   ! update processor id
@@ -1848,6 +2124,10 @@
                ENDIF
             ENDIF
+            ! clean
+            CALL file_clean( tl_proc(:) )
+            DEALLOCATE(tl_proc)
          ELSE
-            DEALLOCATE( td_mpp%t_proc )
+            CALL file_clean( td_mpp%t_proc(:) )
+            DEALLOCATE(td_mpp%t_proc)
 
             ! new number of processor in mpp
@@ -1856,5 +2136,4 @@
       ENDIF
    END SUBROUTINE mpp__del_proc_id
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -1862,15 +2141,10 @@
    !>    structure.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
    !
    !> @param[inout] td_mpp : mpp strcuture
    !> @param[in]    td_proc : file/processor structure
-   !
-   !> @todo check proc id exist
-   !-------------------------------------------------------------------
-   !> @code
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__del_proc_str( td_mpp, td_proc )
       IMPLICIT NONE
@@ -1883,9 +2157,8 @@
          CALL mpp__del_proc( td_mpp, td_proc%i_pid )
       ELSE
-         CALL logger_error("DEL PROC: processor not defined")
+         CALL logger_error("MPP DEL PROC: processor not defined")
       ENDIF
 
    END SUBROUTINE mpp__del_proc_str
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -1895,13 +2168,9 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    id_procid : processor id
-   !> @todo
-   !> - voir si il ne faut pas redefinir (__copy) proc si il vient de mpp
-   !> exemple CALL  mpp_move_proc( td_mpp, td_mpp%t_proc )   
-   !-------------------------------------------------------------------
-   !> @code
+   !> @date Nov, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp    mpp strcuture
+   !> @param[in]    id_procid processor id
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__move_proc( td_mpp, td_proc )
       IMPLICIT NONE
@@ -1918,21 +2187,15 @@
 
    END SUBROUTINE mpp__move_proc
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine add a dimension structure in a mpp 
    !> structure.
    !> Do not overwrite, if dimension already in mpp structure.
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_mpp : mpp structure
-   !> @param[in] td_dim : dimension structure
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   ! @code
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_mpp mpp structure
+   !> @param[in] td_dim    dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_add_dim(td_mpp, td_dim)
       IMPLICIT NONE
@@ -1942,47 +2205,52 @@
 
       ! local variable
-      INTEGER(i4) :: il_dimid
+      INTEGER(i4) :: il_ind
 
       ! loop indices
-      !----------------------------------------------------------------
-      IF( td_mpp%i_ndim <= 4 )THEN
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      IF( td_mpp%i_ndim <= ip_maxdim )THEN
 
          ! check if dimension already in mpp structure
-         il_dimid=dim_get_id(td_mpp%t_dim(:), td_dim%c_name, td_dim%c_sname)
-         IF( il_dimid /= 0 )THEN
-
-            CALL logger_error( &
-            &  " ADD DIM: dimension "//TRIM(td_dim%c_name)//&
-            &  ", short name "//TRIM(td_dim%c_sname)//&
-            &  ", already in mpp "//TRIM(td_mpp%c_name) )
+         il_ind=dim_get_index(td_mpp%t_dim(:), td_dim%c_name, td_dim%c_sname)
+         IF( il_ind /= 0 )THEN
+
+            IF( td_mpp%t_dim(il_ind)%l_use )THEN
+               CALL logger_error( &
+               &  "MPP ADD DIM: dimension "//TRIM(td_dim%c_name)//&
+               &  ", short name "//TRIM(td_dim%c_sname)//&
+               &  ", already used in mpp "//TRIM(td_mpp%c_name) )
+            ELSE
+               ! replace dimension
+               td_mpp%t_dim(il_ind)=dim_copy(td_dim)
+               td_mpp%t_dim(il_ind)%i_id=il_ind
+               td_mpp%t_dim(il_ind)%l_use=.TRUE.
+            ENDIF
 
          ELSE
 
-            CALL logger_debug( &
-            &  " ADD DIM: add dimension "//TRIM(td_dim%c_name)//&
-            &  ", short name "//TRIM(td_dim%c_sname)//&
-            &  ", in mpp "//TRIM(td_mpp%c_name) )
-
-            IF( td_mpp%i_ndim == 4 )THEN
+            IF( td_mpp%i_ndim == ip_maxdim )THEN
+               CALL logger_error( &
+               &  "MPP ADD DIM: can not add dimension "//TRIM(td_dim%c_name)//&
+               &  ", short name "//TRIM(td_dim%c_sname)//&
+               &  ", in mpp "//TRIM(td_mpp%c_name)//". Already "//&
+               &  TRIM(fct_str(ip_maxdim))//" dimensions." )
+            ELSE
                ! search empty dimension
-               il_dimid=dim_get_void_id(td_mpp%t_dim(:),TRIM(td_dim%c_name), &
-               &                                        TRIM(td_dim%c_sname))
-               ! replace empty dimension
-               td_mpp%t_dim(il_dimid)=td_dim
-               td_mpp%t_dim(il_dimid)%i_id=il_dimid
-               td_mpp%t_dim(il_dimid)%l_use=.TRUE.
-            ELSE
-               il_dimid=dim_get_void_id(td_mpp%t_dim(:),TRIM(td_dim%c_name), &
-               &                                        TRIM(td_dim%c_sname))
-               ! add new dimension
-               td_mpp%t_dim(il_dimid)=td_dim
-               td_mpp%t_dim(il_dimid)%i_id=td_mpp%i_ndim+1
-               td_mpp%t_dim(il_dimid)%l_use=.TRUE.
+               DO ji=1,ip_maxdim
+                  IF( td_mpp%t_dim(ji)%i_id == 0 )THEN
+                     il_ind=ji 
+                     EXIT
+                  ENDIF
+               ENDDO
+ 
+               ! add new dimension    
+               td_mpp%t_dim(il_ind)=dim_copy(td_dim)
                ! update number of attribute
                td_mpp%i_ndim=COUNT(td_mpp%t_dim(:)%l_use)
-            ENDIF
-
-            ! reorder dimension to ('x','y','z','t')
-            CALL dim_reorder(td_mpp%t_dim)
+
+               td_mpp%t_dim(il_ind)%l_use=.TRUE.
+               td_mpp%t_dim(il_ind)%i_id=td_mpp%i_ndim
+            ENDIF
 
          ENDIF
@@ -1990,25 +2258,19 @@
       ELSE
          CALL logger_error( &
-         &  " ADD DIM: too much dimension in mpp "//&
+         &  "MPP ADD DIM: too much dimension in mpp "//&
          &  TRIM(td_mpp%c_name)//" ("//TRIM(fct_str(td_mpp%i_ndim))//")")
       ENDIF
 
    END SUBROUTINE mpp_add_dim
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine delete a dimension structure in a mpp 
    !> structure.<br/>
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_mpp : mpp structure
-   !> @param[in] td_dim : dimension structure
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   ! @code
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_mpp mpp structure
+   !> @param[in] td_dim    dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_del_dim(td_mpp, td_dim)
       IMPLICIT NONE
@@ -2019,97 +2281,68 @@
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_dimid
+      INTEGER(i4) :: il_ind
       TYPE(TDIM), DIMENSION(:), ALLOCATABLE  :: tl_dim
 
       ! loop indices
-      !----------------------------------------------------------------
-      IF( td_mpp%i_ndim <= 4 )THEN
-
-         ! check if dimension already in mpp structure
-         il_dimid=dim_get_id(td_mpp%t_dim(:), td_dim%c_name, td_dim%c_sname)
-         IF( il_dimid == 0 )THEN
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      ! check if dimension already in mpp structure
+      il_ind=dim_get_index(td_mpp%t_dim(:), td_dim%c_name, td_dim%c_sname)
+      IF( il_ind == 0 )THEN
+
+         CALL logger_error( &
+         &  "MPP DEL DIM: no dimension "//TRIM(td_dim%c_name)//&
+         &  ", short name "//TRIM(td_dim%c_sname)//&
+         &  ", in mpp "//TRIM(td_mpp%c_name) )
+
+      ELSE
+
+         ALLOCATE( tl_dim(td_mpp%i_ndim-1), stat=il_status )
+         IF(il_status /= 0 )THEN
 
             CALL logger_error( &
-            &  " DEL DIM: no dimension "//TRIM(td_dim%c_name)//&
-            &  ", short name "//TRIM(td_dim%c_sname)//&
-            &  ", in mpp "//TRIM(td_mpp%c_name) )
+            &  "MPP DEL DIM: not enough space to put dimensions from "//&
+            &  TRIM(td_mpp%c_name)//" in temporary dimension structure")
 
          ELSE
 
-            CALL logger_debug( &
-            &  " DEL DIM: delete dimension "//TRIM(td_dim%c_name)//&
-            &  ", short name "//TRIM(td_dim%c_sname)//&
-            &  ", in mpp "//TRIM(td_mpp%c_name) )
-
-            IF( td_mpp%i_ndim == 4 )THEN
-               ALLOCATE( tl_dim(1), stat=il_status )
-               IF(il_status /= 0 )THEN
-                  CALL logger_error( &
-                  &  " DEL DIM: not enough space to put dimensions from "//&
-                  &  TRIM(td_mpp%c_name)//" in temporary dimension structure")
-               ELSE
-                  ! replace dimension by empty one
-                  td_mpp%t_dim(il_dimid)=tl_dim(1)
-               ENDIF
-               DEALLOCATE(tl_dim)
-            ELSE
-               ! 
-               ALLOCATE( tl_dim(td_mpp%i_ndim), stat=il_status )
-               IF(il_status /= 0 )THEN
-
-                  CALL logger_error( &
-                  &  " DEL DIM: not enough space to put dimensions from "//&
-                  &  TRIM(td_mpp%c_name)//" in temporary dimension structure")
-
-               ELSE
-
-                  ! save temporary dimension's mpp structure
-                  tl_dim( 1 : il_dimid-1 ) = td_mpp%t_dim( 1 : il_dimid-1 )
-                  tl_dim( il_dimid : td_mpp%i_ndim-1 ) = &
-                  &           td_mpp%t_dim( il_dimid+1 : td_mpp%i_ndim )
-
-                  ! copy dimension in file, except one
-                  td_mpp%t_dim(1:td_mpp%i_ndim)=tl_dim(:)
-
-                  ! update number of dimension
-                  td_mpp%i_ndim=td_mpp%i_ndim-1
-
-               ENDIF
-            ENDIF
-
-            ! reorder dimension to ('x','y','z','t')
-            CALL dim_reorder(td_mpp%t_dim)
-
-            !IF( ASSOCIATED(td_mpp%t_proc) )THEN
-            !   ! del dimension of processor
-            !   DO ji=1,td_mpp%i_nproc
-            !      CALL file_del_dim(td_mpp%t_proc(ji), td_dim)
-            !   ENDDO
-            !ENDIF
+            ! save temporary dimension's mpp structure
+            tl_dim( 1 : il_ind-1 ) = dim_copy(td_mpp%t_dim( 1 : il_ind-1 ))
+            tl_dim( il_ind : td_mpp%i_ndim-1 ) = &
+            &           dim_copy(td_mpp%t_dim( il_ind+1 : td_mpp%i_ndim ))
+
+            ! remove dimension from file
+            CALL dim_clean(td_mpp%t_dim(:))
+            ! copy dimension in file, except one
+            td_mpp%t_dim(1:td_mpp%i_ndim)=dim_copy(tl_dim(:))
+
+            ! update number of dimension
+            td_mpp%i_ndim=td_mpp%i_ndim-1
+
+            ! update dimension id
+            DO ji=1,td_mpp%i_ndim
+               td_mpp%t_dim(ji)%i_id=ji
+            ENDDO
+
+            ! clean
+            CALL dim_clean(tl_dim(:))
+            DEALLOCATE(tl_dim)
 
          ENDIF
-      ELSE
-         CALL logger_error( &
-         &  " DEL DIM: too much dimension in mpp "//&
-         &  TRIM(td_mpp%c_name)//" ("//TRIM(fct_str(td_mpp%i_ndim))//")")
+
       ENDIF
 
    END SUBROUTINE mpp_del_dim
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine move a dimension structure 
    !> in mpp structure.
    !> @warning dimension order may have changed
-   !
-   !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_mpp : mpp structure
-   !> @param[in] td_dim : dimension structure
-   !> @todo
-   !-------------------------------------------------------------------
-   ! @code
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_mpp mpp structure
+   !> @param[in] td_dim    dimension structure
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_move_dim(td_mpp, td_dim)
       IMPLICIT NONE
@@ -2119,35 +2352,39 @@
 
       ! local variable
+      INTEGER(i4) :: il_ind
       INTEGER(i4) :: il_dimid
-
-      !----------------------------------------------------------------
-
-      il_dimid=dim_get_id(td_mpp%t_dim(:), TRIM(td_dim%c_name), &
-      &                                    TRIM(td_dim%c_sname))
-      IF( il_dimid /= 0 )THEN
-         ! remove dimension with same name
-         CALL mpp_del_dim(td_mpp, td_dim)
-      ENDIF
-
-      ! add new dimension
-      CALL mpp_add_dim(td_mpp, td_dim)
-
+      !----------------------------------------------------------------
+      IF( td_mpp%i_ndim <= ip_maxdim )THEN
+
+         ! check if dimension already in mpp structure
+         il_ind=dim_get_index(td_mpp%t_dim(:), td_dim%c_name, td_dim%c_sname)
+         IF( il_ind /= 0 )THEN
+
+            il_dimid=td_mpp%t_dim(il_ind)%i_id
+            ! replace dimension
+            td_mpp%t_dim(il_ind)=dim_copy(td_dim)
+            td_mpp%t_dim(il_ind)%i_id=il_dimid
+            td_mpp%t_dim(il_ind)%l_use=.TRUE.
+
+         ELSE
+            CALL mpp_add_dim(td_mpp, td_dim)
+         ENDIF
+
+      ELSE
+         CALL logger_error( &
+         &  "MPP MOVE DIM: too much dimension in mpp "//&
+         &  TRIM(td_mpp%c_name)//" ("//TRIM(fct_str(td_mpp%i_ndim))//")")
+      ENDIF
    END SUBROUTINE mpp_move_dim
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief
    !>    This subroutine add global attribute to mpp structure.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    td_att : attribute strcuture
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in]    td_att attribute strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_add_att( td_mpp, td_att )
       IMPLICIT NONE
@@ -2176,11 +2413,12 @@
             il_attid=0
             IF( ASSOCIATED(td_mpp%t_proc(1)%t_att) )THEN
-               il_attid=att_get_id( td_mpp%t_proc(1)%t_att(:), &
+               il_attid=att_get_index( td_mpp%t_proc(1)%t_att(:), &
                &                    td_att%c_name )
             ENDIF
             IF( il_attid /= 0 )THEN
 
-               CALL logger_error( " MPP ADD ATT: attribute "//TRIM(td_att%c_name)//&
-               &  ", already in mpp "//TRIM(td_mpp%c_name) )
+               CALL logger_error( " MPP ADD ATT: attribute "//&
+               &                 TRIM(td_att%c_name)//&
+               &                 ", already in mpp "//TRIM(td_mpp%c_name) )
 
                DO ji=1,td_mpp%t_proc(1)%i_natt
@@ -2192,5 +2430,5 @@
             
                CALL logger_info( &
-               &  " MPP ADD VAR: add attribute "//TRIM(td_att%c_name)//&
+               &  " MPP ADD ATT: add attribute "//TRIM(td_att%c_name)//&
                &  ", in mpp "//TRIM(td_mpp%c_name) )
 
@@ -2207,5 +2445,4 @@
 
    END SUBROUTINE mpp_add_att
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -2213,19 +2450,10 @@
    !> structure.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    td_att : attribute strcuture
-   !
-   !> @todo 
-   !> - check proc id exist
-   !> - check proc dimension
-   !> - check proc file name
-   !> - check proc type
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in]    td_att attribute strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__del_att_str( td_mpp, td_att )
       IMPLICIT NONE
@@ -2244,5 +2472,5 @@
       IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
 
-         CALL logger_error( " DEL VAR: domain decomposition not define "//&
+         CALL logger_warn( "MPP DEL VAR: domain decomposition not define "//&
          &               " in mpp strcuture "//TRIM(td_mpp%c_name))
 
@@ -2252,20 +2480,24 @@
          il_attid=0
          IF( ASSOCIATED(td_mpp%t_proc(1)%t_att) )THEN
-            il_attid=att_get_id( td_mpp%t_proc(1)%t_att(:), &
+            il_attid=att_get_index( td_mpp%t_proc(1)%t_att(:), &
             &                    td_att%c_name )
          ENDIF
          IF( il_attid == 0 )THEN
-            CALL logger_error( &
-            &  " DEL VAR: no attribute "//TRIM(td_att%c_name)//&
+            CALL logger_warn( &
+            &  "MPP DEL VAR: no attribute "//TRIM(td_att%c_name)//&
             &  ", in mpp structure "//TRIM(td_mpp%c_name) )
 
-            DO ji=1,td_mpp%t_proc(1)%i_natt
-               CALL logger_debug( " DEL ATT: in mpp structure : &
-               &  attribute : "//TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name) )
-            ENDDO
+            IF( ASSOCIATED(td_mpp%t_proc(1)%t_var) )THEN
+               DO ji=1,td_mpp%t_proc(1)%i_natt
+                  CALL logger_debug( "MPP DEL ATT: in mpp structure : &
+                  &  attribute : "//TRIM(td_mpp%t_proc(1)%t_var(ji)%c_name) )
+               ENDDO
+            ENDIF
 
          ELSE
 
             cl_name=TRIM(td_att%c_name)
+            CALL logger_debug( "MPP DEL ATT: delete in mpp structure : &
+            &  attribute : "//TRIM(cl_name) )
             DO ji=1,td_mpp%i_nproc
                CALL file_del_att(td_mpp%t_proc(ji), TRIM(cl_name)) 
@@ -2276,5 +2508,4 @@
       ENDIF
    END SUBROUTINE mpp__del_att_str
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -2284,16 +2515,9 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    cd_name: attribute name
-   !
-   !> @todo 
-   !> - check proc id exist
-   !> - check proc dimension
-   !> - check proc file name
-   !> - check proc type
-   !-------------------------------------------------------------------
-   !> @code
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp    mpp strcuture
+   !> @param[in]    cd_name   attribute name
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__del_att_name( td_mpp, cd_name )
       IMPLICIT NONE
@@ -2308,5 +2532,5 @@
       IF( .NOT. ASSOCIATED(td_mpp%t_proc) )THEN
 
-         CALL logger_error( " DEL ATT: domain decomposition not define "//&
+         CALL logger_warn( "MPP DEL ATT: domain decomposition not define "//&
          &               " in mpp strcuture "//TRIM(td_mpp%c_name))
 
@@ -2314,5 +2538,5 @@
 
          IF( td_mpp%t_proc(1)%i_natt == 0 )THEN
-            CALL logger_debug( " DEL ATT NAME: no attribute associated to mpp &
+            CALL logger_debug( "MPP DEL ATT NAME: no attribute associated to mpp &
             &                 structure "//TRIM(td_mpp%c_name) )
          ELSE
@@ -2328,5 +2552,5 @@
 
                CALL logger_warn( &
-               &  " DEL ATT : there is no attribute with "//&
+               &  "MPP DEL ATT : there is no attribute with "//&
                &  "name "//TRIM(cd_name)//" in mpp structure "//&
                &  TRIM(td_mpp%c_name))
@@ -2341,19 +2565,14 @@
       ENDIF
    END SUBROUTINE mpp__del_att_name
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !>    This subroutine overwrite attribute in mpp structure.
    !>
-   !> @detail
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in]    td_att : attribute structure
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in]    td_att attribute structure
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_move_att( td_mpp, td_att )
       IMPLICIT NONE
@@ -2363,8 +2582,8 @@
 
       !local variable
-      TYPE(TATT) :: tl_att
+      TYPE(TATT)  :: tl_att
       !----------------------------------------------------------------
       ! copy variable
-      tl_att=td_att
+      tl_att=att_copy(td_att)
 
       ! remove processor
@@ -2374,6 +2593,8 @@
       CALL mpp_add_att(td_mpp, tl_att)
 
+      ! clean
+      CALL att_clean(tl_att)
+
    END SUBROUTINE mpp_move_att
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -2388,9 +2609,8 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp mpp strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__compute( td_mpp )
       IMPLICIT NONE
@@ -2410,5 +2630,5 @@
       CHARACTER(LEN=lc)                        :: cl_file
       TYPE(TFILE)                              :: tl_proc
-      TYPE(TATT)                               ::tl_att
+      TYPE(TATT)                               :: tl_att
 
       ! loop indices
@@ -2421,5 +2641,5 @@
       td_mpp%i_nproc=0
 
-      CALL logger_trace( "COMPUTE: compute domain decomposition with "//&
+      CALL logger_trace( "MPP COMPUTE: compute domain decomposition with "//&
       &               TRIM(fct_str(td_mpp%i_niproc))//" x "//&
       &               TRIM(fct_str(td_mpp%i_njproc))//" processors")
@@ -2498,5 +2718,4 @@
             &                (/tl_proc%i_lci, tl_proc%i_lcj/) )
             CALL file_add_att(tl_proc, tl_att)
-
 
             ! compute first and last indoor indices
@@ -2544,4 +2763,8 @@
             CALL mpp__add_proc(td_mpp, tl_proc)
 
+            ! clean
+            CALL att_clean(tl_att)
+            CALL file_clean(tl_proc)
+
          ENDDO
       ENDDO
@@ -2551,16 +2774,14 @@
 
    END SUBROUTINE mpp__compute
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
    !>  This subroutine remove land processor from domain decomposition.
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in] id_mask : sub domain mask (sea=1, land=0)
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in] id_mask   sub domain mask (sea=1, land=0)
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__del_land( td_mpp, id_mask )
       IMPLICIT NONE
@@ -2583,9 +2804,8 @@
          ENDDO
       ELSE
-         CALL logger_error("DEL LAND: domain decomposition not define.")
+         CALL logger_error("MPP DEL LAND: domain decomposition not define.")
       ENDIF
 
    END SUBROUTINE mpp__del_land
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
@@ -2596,9 +2816,9 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !> @date November, 2013 - Initial version
+   !
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in] id_mask   sub domain mask (sea=1, land=0) 
+   !-------------------------------------------------------------------
    SUBROUTINE mpp__optimiz( td_mpp, id_mask )
       IMPLICIT NONE
@@ -2617,6 +2837,6 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace("OPTIMIZ: look for best domain decomposition")
-      tl_mpp=td_mpp
+      CALL logger_trace("MPP OPTIMIZ: look for best domain decomposition")
+      tl_mpp=mpp_copy(td_mpp)
 
       ! save maximum number of processor to be used
@@ -2629,4 +2849,5 @@
             ! clean mpp processor
             IF( ASSOCIATED(tl_mpp%t_proc) )THEN
+               CALL file_clean(tl_mpp%t_proc(:))
                DEALLOCATE(tl_mpp%t_proc)
             ENDIF
@@ -2641,5 +2862,5 @@
             CALL mpp__del_land( tl_mpp, id_mask )
 
-            CALL logger_info("OPTIMIZ: number of processor "//&
+            CALL logger_info("MPP OPTIMIZ: number of processor "//&
             &  TRIM(fct_str(tl_mpp%i_nproc)) )
             IF( tl_mpp%i_nproc > td_mpp%i_nproc .AND. &
@@ -2650,18 +2871,22 @@
                CALL mpp_clean(td_mpp)
 
-               ! save processor table
+               ! save processor array
                ALLOCATE( tl_proc(tl_mpp%i_nproc) )
-               tl_proc(:)=tl_mpp%t_proc(:)
-
-               ! remove pointer on processor table
+               tl_proc(:)=file_copy(tl_mpp%t_proc(:))
+
+               ! remove pointer on processor array
+               CALL file_clean(tl_mpp%t_proc(:))
                DEALLOCATE(tl_mpp%t_proc)
  
-               ! save data except processor table
-               td_mpp=tl_mpp
-               ! save processor table
+               ! save data except processor array
+               td_mpp=mpp_copy(tl_mpp)
+
+               ! save processor array
                ALLOCATE( td_mpp%t_proc(td_mpp%i_nproc) )
-               td_mpp%t_proc(:)=tl_proc(:)
-
-               DEALLOCATE( tl_proc )
+               td_mpp%t_proc(:)=file_copy(tl_proc(:))
+
+               ! clean
+               CALL file_clean( tl_proc(:) )
+               DEALLOCATE(tl_proc)
 
             ENDIF
@@ -2670,18 +2895,19 @@
       ENDDO
 
+      ! clean
+      CALL mpp_clean(tl_mpp)
+
    END SUBROUTINE mpp__optimiz
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !>    This function check if processor is a land processor.
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[in] td_mpp : mpp strcuture
-   !> @param[in] id_proc : processor id
-   !> @param[in] id_mask : sub domain mask (sea=1, land=0)
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !>
+   !> @param[in] td_mpp    mpp strcuture
+   !> @param[in] id_proc   processor id
+   !> @param[in] id_mask   sub domain mask (sea=1, land=0)
+   !-------------------------------------------------------------------
    LOGICAL FUNCTION mpp__land_proc( td_mpp , id_proc, id_mask )
       IMPLICIT NONE
@@ -2695,5 +2921,5 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace("LAND PROC: check processor "//TRIM(fct_str(id_proc))//&
+      CALL logger_trace("MPP LAND PROC: check processor "//TRIM(fct_str(id_proc))//&
       &  " of mpp "//TRIM(td_mpp%c_name) )
       mpp__land_proc=.FALSE.
@@ -2703,5 +2929,11 @@
          IF( il_shape(1) /= td_mpp%t_dim(1)%i_len .OR. &
          &   il_shape(2) /= td_mpp%t_dim(2)%i_len )THEN
-             CALL logger_error("LAND PROC: mask and domain size differ")
+             CALL logger_debug("MPP LAND PROC: mask size ("//&
+             &                  TRIM(fct_str(il_shape(1)))//","//&
+             &                  TRIM(fct_str(il_shape(2)))//")")
+             CALL logger_debug("MPP LAND PROC: domain size ("//&
+             &                  TRIM(fct_str(td_mpp%t_dim(1)%i_len))//","//&
+             &                  TRIM(fct_str(td_mpp%t_dim(2)%i_len))//")")
+             CALL logger_error("MPP LAND PROC: mask and domain size differ")
          ELSE
             IF( ALL(id_mask( td_mpp%t_proc(id_proc)%i_impp +            &
@@ -2715,5 +2947,5 @@
             &      /= 1 ) )THEN
                ! land domain
-               CALL logger_info(" LAND PROC: processor "//TRIM(fct_str(id_proc))//&
+               CALL logger_info("MPP LAND PROC: processor "//TRIM(fct_str(id_proc))//&
                &             " is land processor")
                mpp__land_proc=.TRUE.
@@ -2722,20 +2954,18 @@
 
       ELSE
-         CALL logger_error("LAND PROC: domain decomposition not define.")
+         CALL logger_error("MPP LAND PROC: domain decomposition not define.")
       ENDIF
 
    END FUNCTION mpp__land_proc
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
    !>  This subroutine clean mpp strcuture.
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE mpp_clean( td_mpp )
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !-------------------------------------------------------------------
+   SUBROUTINE mpp__clean_unit( td_mpp )
       IMPLICIT NONE
       ! Argument
@@ -2746,52 +2976,80 @@
 
       ! loop indices
-      INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
       CALL logger_info( &
-      &  " CLEAN: reset mpp "//TRIM(td_mpp%c_name) )
+      &  "MPP CLEAN: reset mpp "//TRIM(td_mpp%c_name) )
 
       ! del dimension
       IF( td_mpp%i_ndim /= 0 )THEN
-         DO ji=td_mpp%i_ndim,1,-1
-            CALL dim_clean( td_mpp%t_dim(ji) )
-         ENDDO
+         CALL dim_clean( td_mpp%t_dim(:) )
       ENDIF
 
       IF( ASSOCIATED(td_mpp%t_proc) )THEN
-         ! clean each proc
-         DO ji=1,td_mpp%i_nproc
-            CALL file_clean( td_mpp%t_proc(ji) )
-         ENDDO
+         ! clean array of file processor
+         CALL file_clean( td_mpp%t_proc(:) )
          DEALLOCATE(td_mpp%t_proc)
       ENDIF
 
       ! replace by empty structure
-      td_mpp=tl_mpp
-
-   END SUBROUTINE mpp_clean
-   !> @endcode
+      td_mpp=mpp_copy(tl_mpp)
+
+   END SUBROUTINE mpp__clean_unit
+   !-------------------------------------------------------------------
+   !> @brief 
+   !>  This subroutine clean mpp strcuture.
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !-------------------------------------------------------------------
+   SUBROUTINE mpp__clean_arr( td_mpp )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TMPP),  DIMENSION(:), INTENT(INOUT) :: td_mpp
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      DO ji=SIZE(td_mpp(:)),1,-1
+         CALL mpp_clean(td_mpp(ji))
+      ENDDO
+
+   END SUBROUTINE mpp__clean_arr
    !-------------------------------------------------------------------
    !> @brief 
    !>  This subroutine get sub domains which cover "zoom domain".
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @param[in] td_dom : domain strcuture
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE mpp_get_use( td_mpp, td_dom )
+   !>
+   !> @author J.Paul
+   !> @date November, 2013 - Initial version
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !> @param[in] id_imin   i-direction lower indice
+   !> @param[in] id_imax   i-direction upper indice
+   !> @param[in] id_jmin   j-direction lower indice
+   !> @param[in] id_jmax   j-direction upper indice
+   !-------------------------------------------------------------------
+   SUBROUTINE mpp__get_use_unit( td_mpp, id_imin, id_imax, &
+   &                                     id_jmin, id_jmax )
       IMPLICIT NONE
       ! Argument
-      TYPE(TMPP),  INTENT(INOUT) :: td_mpp
-      TYPE(TDOM),  INTENT(IN)    :: td_dom
+      TYPE(TMPP) ,  INTENT(INOUT) :: td_mpp
+      INTEGER(i4),  INTENT(IN), OPTIONAL :: id_imin
+      INTEGER(i4),  INTENT(IN), OPTIONAL :: id_imax
+      INTEGER(i4),  INTENT(IN), OPTIONAL :: id_jmin
+      INTEGER(i4),  INTENT(IN), OPTIONAL :: id_jmax
 
       ! local variable
-      INTEGER(i4) :: il_jmin
       LOGICAL     :: ll_iuse
       LOGICAL     :: ll_juse
 
+      INTEGER(i4) :: il_imin
+      INTEGER(i4) :: il_imax
+      INTEGER(i4) :: il_jmin
+      INTEGER(i4) :: il_jmax
+
       ! loop indices
       INTEGER(i4) :: jk
@@ -2799,8 +3057,27 @@
       IF( ASSOCIATED(td_mpp%t_proc) )THEN
    
+         il_imin=1
+         il_imax=td_mpp%t_dim(1)%i_len
+         IF( PRESENT(id_imin) ) il_imin=id_imin
+         IF( PRESENT(id_imax) ) il_imax=id_imax
+         il_jmin=1
+         il_jmax=td_mpp%t_dim(2)%i_len
+         IF( PRESENT(id_jmin) ) il_jmin=id_jmin
+         IF( PRESENT(id_jmax) ) il_jmax=id_jmax
+
          ! check domain
-         IF( td_mpp%t_dim(1)%i_len == td_dom%t_dim0(1)%i_len .AND. &
-         &   td_mpp%t_dim(2)%i_len == td_dom%t_dim0(2)%i_len )THEN
-
+         IF( il_imin < 1 .OR. il_imin > td_mpp%t_dim(1)%i_len .OR. &
+         &   il_imax < 1 .OR. il_imax > td_mpp%t_dim(1)%i_len .OR. &
+         &   il_jmin < 1 .OR. il_jmin > td_mpp%t_dim(2)%i_len .OR. &
+         &   il_jmax < 1 .OR. il_jmax > td_mpp%t_dim(2)%i_len )THEN
+            CALL logger_debug("MPP GET USE: mpp gloabl size "//&
+            &        TRIM(fct_str(td_mpp%t_dim(1)%i_len))//","//&
+            &        TRIM(fct_str(td_mpp%t_dim(2)%i_len)))
+            CALL logger_debug("MPP GET USE: i-indices "//&
+            &        TRIM(fct_str(il_imin))//","//TRIM(fct_str(il_imax)))
+            CALL logger_debug("MPP GET USE: j-indices "//&
+            &        TRIM(fct_str(il_jmin))//","//TRIM(fct_str(il_jmax)))
+            CALL logger_error("MPP GET USE: invalid indices ")
+         ELSE
             td_mpp%t_proc(:)%l_use=.FALSE.
             DO jk=1,td_mpp%i_nproc
@@ -2808,28 +3085,25 @@
                ! check i-direction
                ll_iuse=.FALSE.
-               IF( td_dom%i_imin < td_dom%i_imax )THEN
+               IF( il_imin < il_imax )THEN
 
                   ! not overlap east west boundary
                   IF( td_mpp%t_proc(jk)%i_impp + td_mpp%t_proc(jk)%i_lci > &
-                  &   td_dom%i_imin .AND.                                  &
-                  &   td_mpp%t_proc(jk)%i_impp < td_dom%i_imax )THEN
+                  &   il_imin .AND.                                  &
+                  &   td_mpp%t_proc(jk)%i_impp < il_imax )THEN
                       ll_iuse=.TRUE.
                   ENDIF
 
-               ELSEIF( td_dom%i_imin == td_dom%i_imax )THEN
+               ELSEIF( il_imin == il_imax )THEN
 
                   ! east west cyclic
                   ll_iuse=.TRUE.
 
-               ELSE ! td_dom%i_imin > td_dom%i_imax
+               ELSE ! il_imin > id_imax
 
                   ! overlap east west boundary
                   IF( ( td_mpp%t_proc(jk)%i_impp + td_mpp%t_proc(jk)%i_lci >  &
-                  &     td_dom%i_imin .AND.                                   &
-                  &     td_mpp%t_proc(jk)%i_impp < td_dom%t_dim0(1)%i_len )    &
+                  &     il_imin )                                             &
                   &   .OR.                                                    &
-                  &   ( td_mpp%t_proc(jk)%i_impp + td_mpp%t_proc(jk)%i_lci >  &
-                  &     1 .AND.                                               &
-                  &     td_mpp%t_proc(jk)%i_impp < td_dom%i_imax) )THEN
+                  &   ( td_mpp%t_proc(jk)%i_impp < il_imax) )THEN
                      ll_iuse=.TRUE.
                   ENDIF
@@ -2839,16 +3113,15 @@
                ! check j-direction
                ll_juse=.FALSE.
-               IF( td_dom%i_jmin < td_dom%i_jmax )THEN
+               IF( il_jmin < il_jmax )THEN
 
                   ! not overlap north fold
                   IF( td_mpp%t_proc(jk)%i_jmpp + td_mpp%t_proc(jk)%i_lcj > &
-                  &   td_dom%i_jmin .AND.                                  &
-                  &   td_mpp%t_proc(jk)%i_jmpp < td_dom%i_jmax )THEN
+                  &   il_jmin .AND.                                  &
+                  &   td_mpp%t_proc(jk)%i_jmpp < il_jmax )THEN
                      ll_juse=.TRUE.
                   ENDIF
 
-               ELSE ! td_dom%i_jmin >= td_dom%i_jmax
-
-                  il_jmin=MIN(td_dom%i_jmin,td_dom%i_jmax)
+               ELSE ! id_jmin >= id_jmax
+
                   IF( td_mpp%t_proc(jk)%i_jmpp + td_mpp%t_proc(jk)%i_lcj > &
                   &  il_jmin )THEN
@@ -2861,24 +3134,20 @@
 
             ENDDO
-         ELSE
-            CALL logger_error("GET USE: domain differ")
          ENDIF
 
       ELSE
-         CALL logger_error("GET USE: domain decomposition not define.")
-      ENDIF
-
-   END SUBROUTINE mpp_get_use
-   !> @endcode
+         CALL logger_error("MPP GET USE: mpp decomposition not define.")
+      ENDIF
+
+   END SUBROUTINE mpp__get_use_unit
    !-------------------------------------------------------------------
    !> @brief 
    !>  This subroutine get sub domains which form global domain border.
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @author J.Paul
+   !> @date November, 2013
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_get_contour( td_mpp )
       IMPLICIT NONE
@@ -2892,5 +3161,5 @@
       IF( ASSOCIATED(td_mpp%t_proc) )THEN
 
-         td_mpp%t_proc(:)%l_ctr = .FALSE.
+         td_mpp%t_proc(:)%l_use = .FALSE.
          DO jk=1,td_mpp%i_nproc
             IF( td_mpp%t_proc(jk)%i_ldi == 1 .OR. &
@@ -2899,33 +3168,31 @@
             &   td_mpp%t_proc(jk)%i_lej == td_mpp%t_proc(jk)%i_lcj )THEN
 
-               td_mpp%t_proc(jk)%l_ctr = .TRUE.
-            
+               td_mpp%t_proc(jk)%l_use = .TRUE.
+ 
             ENDIF
          ENDDO
    
       ELSE
-         CALL logger_error("GET CONTOUR: domain decomposition not define.")
+         CALL logger_error("MPP GET CONTOUR: domain decomposition not define.")
       ENDIF
 
    END SUBROUTINE mpp_get_contour
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !> This function return processor indices, without overlap boundary,
-   !> given processor id. This depends of domain decompisition type. 
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[in] td_mpp : mpp strcuture
-   !> @param[in] id_procid : processor id
-   !> @return table of index (/ i1, i2, j1, j2 /)
-   !-------------------------------------------------------------------
-   !> @code
+   !> given processor id. 
+   !>
+   !> @author J.Paul
+   !> @date November, 2013
+   !>
+   !> @param[in] td_mpp    mpp strcuture
+   !> @param[in] id_procid processor id
+   !> @return array of index (/ i1, i2, j1, j2 /)
+   !-------------------------------------------------------------------
    FUNCTION mpp_get_proc_index( td_mpp, id_procid )
       IMPLICIT NONE
 
       ! Argument
-      TYPE(TMPP),  INTENT(IN) :: td_mpp
+      TYPE(TMPP) , INTENT(IN) :: td_mpp
       INTEGER(i4), INTENT(IN) :: id_procid
 
@@ -2936,18 +3203,14 @@
       INTEGER(i4) :: il_i1, il_i2
       INTEGER(i4) :: il_j1, il_j2
-      TYPE(TMPP)  :: tl_mpp
       !----------------------------------------------------------------
 
       IF( ASSOCIATED(td_mpp%t_proc) )THEN
 
-         tl_mpp=td_mpp
-         !IF( TRIM(td_mpp%c_dom) == "unknown" )THEN
          IF( TRIM(td_mpp%c_dom) == '' )THEN
-            CALL logger_warn("GET PROC INDEX: decomposition type unknown. "//&
-            &             "look for it")
-            CALL mpp_get_dom( tl_mpp )
+            CALL logger_fatal("MPP GET PROC INDEX: decomposition type unknown. "//&
+            &                 "you should ahve run mpp_get_dom before.")
          ENDIF
 
-         SELECT CASE(TRIM(tl_mpp%c_dom))
+         SELECT CASE(TRIM(td_mpp%c_dom))
             CASE('full')
                il_i1 = 1 ; il_i2 = td_mpp%t_dim(1)%i_len
@@ -2957,5 +3220,5 @@
                 il_j1 = td_mpp%t_proc(id_procid)%i_jmpp
 
-                il_i2 = il_i1 + td_mpp%t_proc(id_procid)%i_lci - 1 ! attention lei dans ioRestartDimg
+                il_i2 = il_i1 + td_mpp%t_proc(id_procid)%i_lci - 1 
                 il_j2 = il_j1 + td_mpp%t_proc(id_procid)%i_lcj - 1 
             CASE('nooverlap')
@@ -2970,5 +3233,5 @@
                &        td_mpp%t_proc(id_procid)%i_lej - 1
             CASE DEFAULT
-               CALL logger_error("GET PROC INDEX: invalid decomposition type.")
+               CALL logger_error("MPP GET PROC INDEX: invalid decomposition type.")
          END SELECT
 
@@ -2976,9 +3239,8 @@
 
       ELSE
-         CALL logger_error("GET PROC INDEX: domain decomposition not define.")
+         CALL logger_error("MPP GET PROC INDEX: domain decomposition not define.")
       ENDIF
 
    END FUNCTION mpp_get_proc_index
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -2987,11 +3249,10 @@
    !
    !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[in] td_mpp : mpp strcuture
-   !> @param[in] id_procid : sub domain id
-   !> @return table of index (/ isize, jsize /)
-   !-------------------------------------------------------------------
-   !> @code
+   !> @date November, 2013
+   !
+   !> @param[in] td_mpp    mpp strcuture
+   !> @param[in] id_procid sub domain id
+   !> @return array of index (/ isize, jsize /)
+   !-------------------------------------------------------------------
    FUNCTION mpp_get_proc_size( td_mpp, id_procid )
       IMPLICIT NONE
@@ -3007,18 +3268,14 @@
       INTEGER(i4) :: il_isize
       INTEGER(i4) :: il_jsize
-      TYPE(TMPP)  :: tl_mpp
       !----------------------------------------------------------------
 
       IF( ASSOCIATED(td_mpp%t_proc) )THEN
 
-         tl_mpp=td_mpp
-         !IF( TRIM(td_mpp%c_dom) == "unknown" )THEN
          IF( TRIM(td_mpp%c_dom) == '' )THEN
-            CALL logger_warn("GET PROC SIZE: decomposition type unknown. "//&
-            &              "look for it")
-            CALL mpp_get_dom( tl_mpp )
+            CALL logger_fatal("MPP GET PROC SIZE: decomposition type unknown. "//&
+            &                 "you should ahve run mpp_get_dom before.")
          ENDIF
 
-         SELECT CASE(TRIM(tl_mpp%c_dom))
+         SELECT CASE(TRIM(td_mpp%c_dom))
             CASE('full')
                
@@ -3037,6 +3294,6 @@
                &          td_mpp%t_proc(id_procid)%i_ldj + 1
             CASE DEFAULT
-               CALL logger_error("GET PROC SIZE: invalid decomposition type : "//&
-               &  TRIM(tl_mpp%c_dom) )
+               CALL logger_error("MPP GET PROC SIZE: invalid decomposition type : "//&
+               &  TRIM(td_mpp%c_dom) )
          END SELECT
 
@@ -3044,22 +3301,18 @@
 
       ELSE
-         CALL logger_error("GET PROC SIZE: domain decomposition not define.")
+         CALL logger_error("MPP GET PROC SIZE: domain decomposition not define.")
       ENDIF
 
    END FUNCTION mpp_get_proc_size
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
    !>  This subroutine determine domain decomposition type.
    !>  (full, overlap, noverlap)
-   !
-   !> @author J.Paul
-   !> @date Nov, 2013
-   !
-   !> @param[inout] td_mpp : mpp strcuture
-   !> @todo
-   !> - change name, confusing with domain.f90
-   !-------------------------------------------------------------------
-   !> @code
+   !>
+   !> @author J.Paul
+   !> @date November, 2013
+   !>
+   !> @param[inout] td_mpp mpp strcuture
+   !-------------------------------------------------------------------
    SUBROUTINE mpp_get_dom( td_mpp )
       IMPLICIT NONE
@@ -3075,5 +3328,5 @@
 
          IF( td_mpp%i_niproc == 0 .AND. td_mpp%i_niproc == 0 )THEN
-            CALL logger_info("GET DOM: use indoor indices to get domain "//&
+            CALL logger_info("MPP GET DOM: use indoor indices to get domain "//&
             &             "decomposition type.")
             IF((td_mpp%t_proc(1)%t_dim(1)%i_len ==                         &
@@ -3100,24 +3353,24 @@
             ELSE
 
-               CALL logger_error("GET DOM: should have been an impossible case")
+               CALL logger_error("MPP GET DOM: should have been an impossible case")
 
                il_isize=td_mpp%t_proc(1)%t_dim(1)%i_len
                il_jsize=td_mpp%t_proc(1)%t_dim(2)%i_len
-               CALL logger_debug("GET DOM: proc size "//&
+               CALL logger_debug("MPP GET DOM: proc size "//&
                &  TRIM(fct_str(il_isize))//" x "//TRIM(fct_str(il_jsize)) )
 
                il_isize=td_mpp%t_proc(1)%i_lei - td_mpp%t_proc(1)%i_ldi + 1
                il_jsize=td_mpp%t_proc(1)%i_lej - td_mpp%t_proc(1)%i_ldj + 1
-               CALL logger_debug("GET DOM: no overlap size "//&
+               CALL logger_debug("MPP GET DOM: no overlap size "//&
                &  TRIM(fct_str(il_isize))//" x "//TRIM(fct_str(il_jsize)) )
 
                il_isize=td_mpp%t_proc(1)%i_lci
                il_jsize=td_mpp%t_proc(1)%i_lcj
-               CALL logger_debug("GET DOM: overlap size "//&
+               CALL logger_debug("MPP GET DOM: overlap size "//&
                &  TRIM(fct_str(il_isize))//" x "//TRIM(fct_str(il_jsize)) )
 
                il_isize=td_mpp%t_dim(1)%i_len
                il_jsize=td_mpp%t_dim(2)%i_len
-               CALL logger_debug("GET DOM: full size "//&
+               CALL logger_debug("MPP GET DOM: full size "//&
                &  TRIM(fct_str(il_isize))//" x "//TRIM(fct_str(il_jsize)) )
 
@@ -3126,5 +3379,5 @@
          ELSE
 
-            CALL logger_info("GET DOM: use number of processors following "//&
+            CALL logger_info("MPP GET DOM: use number of processors following "//&
             &             "I and J to get domain decomposition type.")
             IF( td_mpp%i_niproc*td_mpp%i_njproc==td_mpp%i_nproc )THEN
@@ -3140,23 +3393,21 @@
 
       ELSE
-         CALL logger_error("GET DOM: domain decomposition not define.")
+         CALL logger_error("MPP GET DOM: domain decomposition not define.")
       ENDIF
 
    END SUBROUTINE mpp_get_dom
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This function check if variable  and mpp structure use same
    !> dimension.
-   !
+   !>
    !> @details
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp : mpp structure
-   !> @param[in] td_var : variable structure
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] td_mpp mpp structure
+   !> @param[in] td_var variable structure
    !> @return dimension of variable and mpp structure agree (or not)
    !-------------------------------------------------------------------
-   ! @code
    LOGICAL FUNCTION mpp__check_var_dim(td_mpp, td_var)
       IMPLICIT NONE
@@ -3179,5 +3430,5 @@
 
          CALL logger_error( &
-         &  " CHECK DIM: variable and mpp dimension differ"//&
+         &  "MPP CHECK DIM: variable and mpp dimension differ"//&
          &  " for variable "//TRIM(td_var%c_name)//&
          &  " and mpp "//TRIM(td_mpp%c_name))
@@ -3189,5 +3440,5 @@
          DO ji = 1, il_ndim
             CALL logger_debug( &
-            &  " CHECK DIM: for dimension "//&
+            &  "MPP CHECK DIM: for dimension "//&
             &  TRIM(td_mpp%t_dim(ji)%c_name)//&
             &  ", mpp length: "//&
@@ -3200,5 +3451,156 @@
 
    END FUNCTION mpp__check_var_dim
-   ! @endcode
+   !-------------------------------------------------------------------
+   !> @brief This function return the mpp id, in a array of mpp
+   !> structure,  given mpp base name. 
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_file   array of file structure
+   !> @param[in] cd_name   file name
+   !> @return file id in array of file structure (0 if not found)
+   !-------------------------------------------------------------------
+   INTEGER(i4) FUNCTION mpp_get_index(td_mpp, cd_name)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP)      , DIMENSION(:), INTENT(IN) :: td_mpp
+      CHARACTER(LEN=*),               INTENT(IN) :: cd_name
+
+      ! local variable
+      CHARACTER(LEN=lc) :: cl_name
+      INTEGER(i4)       :: il_size
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      mpp_get_index=0
+      il_size=SIZE(td_mpp(:))
+
+      cl_name=TRIM( file_rename(cd_name) )
+
+      ! check if mpp is in array of mpp structure
+      DO ji=1,il_size
+         ! look for file name
+         IF( TRIM(fct_lower(td_mpp(ji)%c_name)) == TRIM(fct_lower(cd_name)) )THEN
+ 
+            mpp_get_index=ji
+            EXIT
+
+         ENDIF
+      ENDDO
+
+   END FUNCTION mpp_get_index
+   !-------------------------------------------------------------------
+   !> @brief This function recombine variable splitted mpp structure. 
+   !
+   !> @author J.Paul
+   !> - Ocotber, 2014- Initial Version
+   !
+   !> @param[in] td_mpp   mpp file structure
+   !> @param[in] cd_name  variable name
+   !> @return variable strucutre
+   !-------------------------------------------------------------------
+   TYPE(TVAR) FUNCTION mpp_recombine_var(td_mpp, cd_name) 
+   IMPLICIT NONE
+      ! Argument      
+      TYPE(TMPP)      , INTENT(IN) :: td_mpp
+      CHARACTER(LEN=*), INTENT(IN) :: cd_name
+
+      ! local variable
+      INTEGER(i4)                       :: il_varid
+      INTEGER(i4)                       :: il_status
+      INTEGER(i4)                       :: il_i1p
+      INTEGER(i4)                       :: il_i2p
+      INTEGER(i4)                       :: il_j1p
+      INTEGER(i4)                       :: il_j2p
+      INTEGER(i4), DIMENSION(4)         :: il_ind
+
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_strt
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_cnt
+
+      TYPE(TVAR)                        :: tl_tmp
+      TYPE(TVAR)                        :: tl_var
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jk
+      !----------------------------------------------------------------
+
+      il_varid=var_get_index( td_mpp%t_proc(1)%t_var(:), cd_name)
+      IF( il_varid /= 0 )THEN
+      
+         tl_var=var_copy(td_mpp%t_proc(1)%t_var(il_varid))
+         ! Allocate space to hold variable value in structure 
+         IF( ASSOCIATED(tl_var%d_value) )THEN
+            DEALLOCATE(tl_var%d_value)   
+         ENDIF
+         ! 
+         DO ji=1,ip_maxdim
+            IF( tl_var%t_dim(ji)%l_use )THEN
+               tl_var%t_dim(ji)%i_len=td_mpp%t_dim(ji)%i_len
+            ENDIF
+         ENDDO
+
+         ALLOCATE(tl_var%d_value( tl_var%t_dim(1)%i_len, &
+         &                        tl_var%t_dim(2)%i_len, &
+         &                        tl_var%t_dim(3)%i_len, &
+         &                        tl_var%t_dim(4)%i_len),&
+         &        stat=il_status)
+         IF(il_status /= 0 )THEN
+
+           CALL logger_error( &
+            &  " MPP RECOMBINE VAR: not enough space to put variable "//&
+            &  TRIM(tl_var%c_name)//" in variable structure")
+
+         ENDIF
+
+         ! FillValue by default
+         tl_var%d_value(:,:,:,:)=tl_var%d_fill
+
+         ! read processor 
+         DO jk=1,td_mpp%i_nproc
+            IF( td_mpp%t_proc(jk)%l_use )THEN
+               ! get processor indices
+               il_ind(:)=mpp_get_proc_index( td_mpp, jk )
+               il_i1p = il_ind(1)
+               il_i2p = il_ind(2)
+               il_j1p = il_ind(3)
+               il_j2p = il_ind(4)
+ 
+               il_strt(:)=(/ 1,1,1,1 /)
+
+               il_cnt(:)=(/ il_i2p-il_i1p+1,         &
+               &            il_j2p-il_j1p+1,         &
+               &            tl_var%t_dim(3)%i_len, &
+               &            tl_var%t_dim(4)%i_len /)
+
+               tl_tmp=iom_read_var( td_mpp%t_proc(jk), tl_var%c_name,&
+               &                    il_strt(:), il_cnt(:) )
+               
+               ! replace value in output variable structure
+               tl_var%d_value( il_i1p : il_i2p,  &
+               &               il_j1p : il_j2p,  &
+               &               :,:) = tl_tmp%d_value(:,:,:,:)
+
+               ! clean
+               CALL var_clean(tl_tmp)
+
+            ENDIF
+         ENDDO
+
+         mpp_recombine_var=var_copy(tl_var)
+
+         ! clean
+         CALL var_clean(tl_var)
+
+      ELSE
+
+         CALL logger_error( &
+         &  " MPP RECOMBINE VAR: there is no variable with "//&
+         &  "name or standard name"//TRIM(cd_name)//&
+         &  " in mpp file "//TRIM(td_mpp%c_name))
+      ENDIF
+   END FUNCTION mpp_recombine_var
 END MODULE mpp
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/multi.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/multi.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/multi.f90	(revision 5075)
@@ -5,16 +5,61 @@
 ! MODULE: multi
 !
-!
 ! DESCRIPTION:
-!> This module manage multi file structure
+!> This module manage multi file structure.
 !
 !> @details
-!> define type TMULTI:<br/>
-!> TYPE(TMULTI) :: tl_multi<br/>
+!>    define type TMULTI:<br/>
+!> @code
+!>    TYPE(TMULTI) :: tl_multi
+!> @endcode
+!>
+!>    to initialize a multi-file structure:<br/>
+!> @code
+!>    tl_multi=multi_init(cd_varfile(:))
+!> @endcode
+!>       - cd_varfile : array of variable with file path 
+!>       ('var1:file1','var2:file2')<br/>
+!>          file path could be replaced by a matrix of value.<br/>
+!>          separators used to defined matrix are:
+!>             - ',' for line
+!>             - '/' for row
+!>             - '\' for level<br/>
+!>             Example:<br/>
+!>                - 'var1:3,2,3/1,4,5'
+!>                - 3,2,3/1,4,5  =>  
+!>                      @f$ \left( \begin{array}{ccc}
+!>                           3 & 2 & 3 \\
+!>                           1 & 4 & 5 \end{array} \right) @f$<br/>
+!> 
+!>    to get the number of mpp file in mutli file structure:<br/>
+!>    - tl_multi\%i_nmpp
+!>
+!>    to get the total number of variable in mutli file structure:<br/>
+!>    - tl_multi\%i_nvar
+!>
+!>    @note number of variable and number of file could differ cause several variable
+!>    could be in the same file.
+!>
+!>    to get array of mpp structure in mutli file structure:<br/>
+!>    - tl_multi\%t_mpp(:)
+!>
+!>    to print information about multi structure:<br/>
+!> @code
+!>    CALL multi_print(td_multi)
+!> @endcode
+!>
+!>    to clean multi file strucutre:<br/>
+!> @code
+!>    CALL multi_clean(td_multi)
+!> @endcode
+!>       - td_multi is multi file structure
 !>
 !> @author
 !>  J.Paul
 ! REVISION HISTORY:
-!> @date 2013 - Initial Version
+!> @date November, 2013 - Initial Version
+!> @date October, 2014
+!> - use mpp file structure instead of file
+!> @date November, 2014 - Fix memory leaks bug
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -22,37 +67,37 @@
 MODULE multi
    USE kind                            ! F90 kind parameter
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE fct                             ! basic useful function
    USE dim                             ! dimension manager
-   USE att                             ! attribute manager
    USE var                             ! variable manager
    USE file                            ! file manager
+   USE iom                             ! I/O manager
+   USE mpp                             ! MPP manager
+   USE iom_mpp                         ! MPP I/O manager
+
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
    ! type and variable
-   PUBLIC :: TMULTI       ! multi file structure
+   PUBLIC :: TMULTI       !< multi file structure
 
    ! function and subroutine
-   PUBLIC :: ASSIGNMENT(=)     !< copy multi structure
-   PUBLIC :: multi_init        !< initialise mpp structure
-   PUBLIC :: multi_clean       !< clean mpp strcuture
-   PUBLIC :: multi_print       !< print information about mpp structure
-
-   PUBLIC :: multi_add_file    !< add one proc strucutre in mpp structure
-!   PUBLIC :: multi_del_file    !< delete one proc strucutre in mpp structure
-!   PUBLIC :: multi_move_file   !< overwrite proc strucutre in mpp structure
-
-   !> @struct TMULTI
-   TYPE TMULTI
+   PUBLIC :: multi_copy        !< copy multi structure
+   PUBLIC :: multi_init        !< initialise multi structure
+   PUBLIC :: multi_clean       !< clean multi strcuture
+   PUBLIC :: multi_print       !< print information about milti structure
+
+   PUBLIC :: multi__add_mpp    !< add file strucutre to multi file structure
+   PRIVATE :: multi__copy_unit !< copy multi file structure
+
+   TYPE TMULTI !< multi file structure
       ! general 
-      INTEGER(i4)                         :: i_nfile = 0         !< number of files 
+      INTEGER(i4)                         :: i_nmpp  = 0         !< number of mpp files 
       INTEGER(i4)                         :: i_nvar  = 0         !< total number of variables
-      TYPE(TFILE), DIMENSION(:), POINTER  :: t_file => NULL()    !< files composing multi
+      TYPE(TMPP) , DIMENSION(:), POINTER  :: t_mpp => NULL()     !< mpp files composing multi
    END TYPE
 
-   INTERFACE ASSIGNMENT(=)
-      MODULE PROCEDURE multi__copy   ! copy multi file structure
+   INTERFACE multi_copy
+      MODULE PROCEDURE multi__copy_unit   ! copy multi file structure
    END INTERFACE   
 
@@ -60,26 +105,33 @@
    !-------------------------------------------------------------------
    !> @brief
-   !> This function copy multi file structure in another multi file
-   !> structure
+   !> This function copy multi mpp structure in another one
    !> @details 
-   !> file variable value are copied in a temporary table, 
+   !> file variable value are copied in a temporary array, 
    !> so input and output file structure value do not point on the same 
    !> "memory cell", and so on are independant. 
    !>
+   !> @warning do not use on the output of a function who create or read an
+   !> attribute (ex: tl_att=att_copy(att_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>   
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[out] td_multi1  : file structure
-   !> @param[in] td_multi2  : file structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE multi__copy( td_multi1, td_multi2 )
+   !> - November, 2013- Initial Version
+   !> @date November, 2014
+   !>    - use function instead of overload assignment operator (to avoid memory leak)
+   !>
+   !> @param[in] td_multi    mpp structure
+   !> @return copy of input multi structure
+   !-------------------------------------------------------------------
+   FUNCTION multi__copy_unit( td_multi )
       IMPLICIT NONE
       ! Argument
-      TYPE(TMULTI), INTENT(OUT) :: td_multi1
-      TYPE(TMULTI), INTENT(IN)  :: td_multi2
+      TYPE(TMULTI), INTENT(IN)  :: td_multi
+      ! function
+      TYPE(TMULTI) :: multi__copy_unit
+
+      ! local variable
+      TYPE(TMPP) :: tl_mpp
 
       ! loop indices
@@ -87,30 +139,39 @@
       !----------------------------------------------------------------
 
-      CALL logger_trace("COPY: mulit file ")
-
-      td_multi1%i_nfile = td_multi2%i_nfile
-      td_multi1%i_nvar  = td_multi2%i_nvar
+      multi__copy_unit%i_nmpp = td_multi%i_nmpp
+      multi__copy_unit%i_nvar = td_multi%i_nvar
 
       ! copy variable structure
-      IF( ASSOCIATED(td_multi1%t_file) ) DEALLOCATE(td_multi1%t_file)
-      IF( ASSOCIATED(td_multi2%t_file) .AND. td_multi1%i_nfile > 0 )THEN
-         ALLOCATE( td_multi1%t_file(td_multi1%i_nfile) )
-         DO ji=1,td_multi1%i_nfile
-            td_multi1%t_file(ji) = td_multi2%t_file(ji)
+      IF( ASSOCIATED(multi__copy_unit%t_mpp) )THEN
+         CALL mpp_clean(multi__copy_unit%t_mpp(:))
+         DEALLOCATE(multi__copy_unit%t_mpp)
+      ENDIF
+      IF( ASSOCIATED(td_multi%t_mpp) .AND. multi__copy_unit%i_nmpp > 0 )THEN
+         ALLOCATE( multi__copy_unit%t_mpp(multi__copy_unit%i_nmpp) )
+         DO ji=1,multi__copy_unit%i_nmpp
+            tl_mpp = mpp_copy(td_multi%t_mpp(ji))
+            multi__copy_unit%t_mpp(ji) = mpp_copy(tl_mpp)
          ENDDO
-      ENDIF
-
-   END SUBROUTINE multi__copy
-   !> @endcode
+         ! clean
+         CALL mpp_clean(tl_mpp)
+      ENDIF
+
+   END FUNCTION multi__copy_unit
    !-------------------------------------------------------------------
    !> @brief This subroutine initialize multi file structure.
-   !
+   !>
+   !> @details
+   !> if variable name is 'all', add all the variable of the file in mutli file
+   !> structure.
+   !> @note if first character of filename is numeric, assume matrix is given as
+   !> input.<br/>
+   !> create pseudo file named 'data-*', with matrix read as variable value.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_varfile : variable location information (from namelist) 
-   !> @return td_multi : multi structure
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] cd_varfile   variable location information (from namelist) 
+   !> @return multi file structure
+   !-------------------------------------------------------------------
    FUNCTION multi_init(cd_varfile)
       IMPLICIT NONE
@@ -124,17 +185,20 @@
       ! local variable
       CHARACTER(LEN=lc) :: cl_name
+      CHARACTER(LEN=lc) :: cl_lower
       CHARACTER(LEN=lc) :: cl_file
       CHARACTER(LEN=lc) :: cl_matrix
 
-      INTEGER(i4)       :: il_fileid
+      INTEGER(i4)       :: il_nvar
+
+      LOGICAL           :: ll_dim
 
       TYPE(TVAR)        :: tl_var
 
-      TYPE(TFILE)       :: tl_file
-
-      TYPE(TMULTI)      :: tl_multi
+      TYPE(TMPP)        :: tl_mpp
 
       ! loop indices
       INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      INTEGER(i4) :: jk
       !----------------------------------------------------------------
 
@@ -142,31 +206,97 @@
       DO WHILE( TRIM(cd_varfile(ji)) /= '' )
 
-         cl_name=fct_lower(fct_split(cd_varfile(ji),1,':'))
+         il_nvar=0
+         cl_name=fct_split(cd_varfile(ji),1,':')
+         cl_lower=fct_lower(cl_name)
          cl_file=fct_split(cd_varfile(ji),2,':')
 
-         IF( TRIM(cl_name) /= '' )THEN
+         IF( LEN(TRIM(cl_file)) == lc )THEN
+            CALL logger_fatal("MULTI INIT: file name too long (==256)."//&
+            &  " check namelist.")
+         ENDIF
+
+         IF( TRIM(cl_lower) /= '' )THEN
             IF( TRIM(cl_file) /= '' )THEN
                cl_matrix=''
                IF( fct_is_num(cl_file(1:1)) )THEN
                   cl_matrix=TRIM(cl_file)
-                  WRITE(cl_file,'(a,i2.2)')'data_',ji
+                  WRITE(cl_file,'(a,i2.2)')'data-',ji
+
+                  tl_var=var_init(TRIM(cl_name))
+                  CALL var_read_matrix(tl_var, cl_matrix)
+
+                  ! create mpp structure
+                  tl_mpp=mpp_init(TRIM(cl_file), tl_var)
+
+                  ! add variable
+                  CALL mpp_add_var(tl_mpp,tl_var)
+
+                  ! number of variable
+                  il_nvar=il_nvar+1
+
+               ELSE
+
+                  ! 
+                  tl_mpp=mpp_init( file_init(TRIM(cl_file)) )
+
+                  ! define variable
+                  IF( TRIM(fct_lower(cl_lower)) /= 'all' )THEN
+
+                     ! clean var
+                     CALL mpp_del_var(tl_mpp)
+
+                     tl_var=var_init(TRIM(cl_lower))
+
+                     ! add variable
+                     CALL mpp_add_var(tl_mpp,tl_var)
+
+                     ! number of variable
+                     il_nvar=il_nvar+1
+
+                     ! clean structure
+                     CALL var_clean(tl_var)
+
+                  ELSE ! cl_lower == 'all'
+
+                     DO jk=tl_mpp%t_proc(1)%i_nvar,1,-1
+                        
+                        ! check if variable is dimension
+                        ll_dim=.FALSE.
+                        DO jj=1,ip_maxdim
+                           IF( TRIM(tl_mpp%t_proc(1)%t_dim(jj)%c_name) == &
+                           &   TRIM(tl_mpp%t_proc(1)%t_var(jk)%c_name) )THEN
+                              ll_dim=.TRUE.
+                              CALL logger_trace("MULTI INIT: "//&
+                              &  TRIM(tl_mpp%t_proc(1)%t_var(jk)%c_name)//&
+                              &  ' is var dimension')
+                              EXIT
+                           ENDIF
+                        ENDDO
+                        ! do not use variable dimension
+                        IF( ll_dim )THEN
+                           tl_var=var_init( &
+                           &  TRIM(tl_mpp%t_proc(1)%t_var(jk)%c_name) )
+                           ! delete variable
+                           CALL mpp_del_var(tl_mpp,tl_var)
+                           ! clean structure
+                           CALL var_clean(tl_var)
+                        ELSE
+                           ! number of variable
+                           il_nvar=il_nvar+1
+                        ENDIF
+
+                     ENDDO
+
+                  ENDIF
+
                ENDIF
-               
-               ! get file id
-               tl_file=file_init(TRIM(cl_file))
-               il_fileid=multi_add_file(tl_multi,tl_file) 
- 
-               ! define variable
-               tl_var=var_init(TRIM(cl_name))
-               CALL var_read_matrix(tl_var, cl_matrix)
-
-               ! add variable
-               CALL file_add_var(tl_multi%t_file(il_fileid),tl_var)
+
+               CALL multi__add_mpp(multi_init, tl_mpp) 
 
                ! update total number of variable
-               tl_multi%i_nvar=tl_multi%i_nvar+1
-
-               ! clean structure
-               CALL var_clean(tl_var)
+               multi_init%i_nvar=multi_init%i_nvar+il_nvar
+
+               ! clean
+               CALL mpp_clean(tl_mpp)
 
             ELSE
@@ -182,18 +312,13 @@
       ENDDO
 
-      ! save result
-      multi_init=tl_multi
-
    END FUNCTION multi_init
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine clean multi file strucutre.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_multi : multi file structure
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_multi  multi file structure
+   !-------------------------------------------------------------------
    SUBROUTINE multi_clean(td_multi)
       IMPLICIT NONE
@@ -206,30 +331,25 @@
 
       ! loop indices
-      INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
       CALL logger_info( " CLEAN: reset multi file " )
 
-      IF( ASSOCIATED( td_multi%t_file ) )THEN
-         DO ji=td_multi%i_nfile,1,-1
-            CALL file_clean(td_multi%t_file(ji))
-         ENDDO
-         DEALLOCATE(td_multi%t_file)
+      IF( ASSOCIATED( td_multi%t_mpp ) )THEN
+         CALL mpp_clean(td_multi%t_mpp(:))
+         DEALLOCATE(td_multi%t_mpp)
       ENDIF
 
       ! replace by empty structure
-      td_multi=tl_multi
+      td_multi=multi_copy(tl_multi)
 
    END SUBROUTINE multi_clean
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine print some information about mpp strucutre.
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_mpp : mpp structure
-   !-------------------------------------------------------------------
-   ! @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_multi multi file structure
+   !-------------------------------------------------------------------
    SUBROUTINE multi_print(td_multi)
       IMPLICIT NONE
@@ -246,15 +366,16 @@
 
       ! print file
-      IF( td_multi%i_nfile /= 0 .AND. ASSOCIATED(td_multi%t_file) )THEN
-         WRITE(*,'(/a,i3)') 'MULTI: total number of file: ',&
-         &  td_multi%i_nfile
+      IF( td_multi%i_nmpp /= 0 .AND. ASSOCIATED(td_multi%t_mpp) )THEN
+         WRITE(*,'(/a,i3)') 'MULTI: total number of mpp: ',&
+         &  td_multi%i_nmpp
          WRITE(*,'(6x,a,i3)') ' total number of variable: ',&
          &  td_multi%i_nvar
-         DO ji=1,td_multi%i_nfile
-            WRITE(*,'(3x,3a)') 'FILE ',TRIM(td_multi%t_file(ji)%c_name),&
+         DO ji=1,td_multi%i_nmpp
+            WRITE(*,'(3x,3a)') 'MPP FILE ',TRIM(td_multi%t_mpp(ji)%c_name),&
             & ' CONTAINS'
-            DO jj=1,td_multi%t_file(ji)%i_nvar
-               IF( ASSOCIATED(td_multi%t_file(ji)%t_var) )THEN
-                  WRITE(*,'(6x,a/)') TRIM(td_multi%t_file(ji)%t_var(jj)%c_name)
+            DO jj=1,td_multi%t_mpp(ji)%t_proc(1)%i_nvar
+               IF( ASSOCIATED(td_multi%t_mpp(ji)%t_proc(1)%t_var) )THEN
+                  WRITE(*,'(6x,a)') &
+                  &  TRIM(td_multi%t_mpp(ji)%t_proc(1)%t_var(jj)%c_name)
                ENDIF
             ENDDO
@@ -263,5 +384,4 @@
 
    END SUBROUTINE multi_print
-   ! @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -271,92 +391,102 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_multi : multi file strcuture
-   !> @param[in]    td_file  : file strcuture
-   !> @return file id in multi structure
-   !-------------------------------------------------------------------
-   !> @code
-   FUNCTION multi_add_file( td_multi, td_file )
+   !> - November, 2013- Initial Version
+   !> @date October, 2014
+   !> - use mpp file structure instead of file
+   !
+   !> @param[inout] td_multi  multi mpp file strcuture
+   !> @param[in]    td_mpp    mpp file strcuture
+   !> @return mpp file id in multi mpp file structure
+   !-------------------------------------------------------------------
+   SUBROUTINE multi__add_mpp( td_multi, td_mpp )
       IMPLICIT NONE
       ! Argument
       TYPE(TMULTI), INTENT(INOUT) :: td_multi
-      TYPE(TFILE) , INTENT(IN)    :: td_file
-
-      ! function
-      INTEGER(i4) :: multi_add_file
+      TYPE(TMPP)  , INTENT(IN)    :: td_mpp
 
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_fileid
-      TYPE(TFILE), DIMENSION(:), ALLOCATABLE :: tl_file
+      INTEGER(i4) :: il_mppid
+      
+      TYPE(TMPP), DIMENSION(:), ALLOCATABLE :: tl_mpp
+
+      ! loop indices
+      INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
-      il_fileid=0
-      IF( ASSOCIATED(td_multi%t_file) )THEN
-         il_fileid=file_get_id(td_multi%t_file(:),TRIM(td_file%c_name))
-      ENDIF
-
-      IF( il_fileid /= 0 )THEN
-
-            multi_add_file=il_fileid
+      il_mppid=0
+      IF( ASSOCIATED(td_multi%t_mpp) )THEN
+         il_mppid=mpp_get_index(td_multi%t_mpp(:),TRIM(td_mpp%c_name))
+      ENDIF
+
+      IF( il_mppid /= 0 )THEN
+
+            CALL logger_debug( " MULTI ADD FILE: mpp file "//TRIM(td_mpp%c_name)//&
+            &               " already in multi mpp file structure")
+
+            ! add new variable
+            DO ji=1,td_mpp%t_proc(1)%i_nvar
+               CALL mpp_add_var(td_multi%t_mpp(il_mppid), td_mpp%t_proc(1)%t_var(ji))
+            ENDDO
 
       ELSE
-         
-         CALL logger_trace("MULTI ADD FILE: add file "//&
-         &               TRIM(td_file%c_name)//" in multi structure")
-
-         IF( td_multi%i_nfile > 0 )THEN
+ 
+         CALL logger_trace("MULTI ADD MPP: add mpp "//&
+         &               TRIM(td_mpp%c_name)//" in multi mpp file structure")
+
+         IF( td_multi%i_nmpp > 0 )THEN
             ! 
-            ! already other file in multi structure
-            ALLOCATE( tl_file(td_multi%i_nfile), stat=il_status )
+            ! already other mpp file in multi file structure
+            ALLOCATE( tl_mpp(td_multi%i_nmpp), stat=il_status )
             IF(il_status /= 0 )THEN
 
-               CALL logger_error( " MULTI ADD FILE: not enough space to put file &
-               &               in multi structure")
+               CALL logger_error( " MULTI ADD MPP FILE: not enough space to put &
+               &               mpp file in multi mpp file structure")
 
             ELSE
-               ! save temporary multi structure
-               tl_file(:)=td_multi%t_file(:)
-
-               DEALLOCATE( td_multi%t_file )
-               ALLOCATE( td_multi%t_file(td_multi%i_nfile+1), stat=il_status)
+               ! save temporary multi file structure
+               tl_mpp(:)=mpp_copy(td_multi%t_mpp(:))
+
+               CALL mpp_clean(td_multi%t_mpp(:))
+               DEALLOCATE( td_multi%t_mpp )
+               ALLOCATE( td_multi%t_mpp(td_multi%i_nmpp+1), stat=il_status)
                IF(il_status /= 0 )THEN
 
-                  CALL logger_error( " MULTI ADD FILE: not enough space to put "//&
-                  &  "file in multi structure ")
+                  CALL logger_error( " MULTI ADD MPP FILE: not enough space "//&
+                  &  "to put mpp file in multi mpp file structure ")
 
                ENDIF
 
-               ! copy file in multi before
-               td_multi%t_file(1:td_multi%i_nfile) = tl_file(:)
-
-               DEALLOCATE(tl_file)
+               ! copy mpp file in multi mpp file before
+               td_multi%t_mpp(1:td_multi%i_nmpp) = mpp_copy(tl_mpp(:))
+
+               ! clean
+               CALL mpp_clean(tl_mpp(:))
+               DEALLOCATE(tl_mpp)
             ENDIF
 
          ELSE
-            ! no processor in mpp structure
-            IF( ASSOCIATED(td_multi%t_file) )THEN
-               DEALLOCATE(td_multi%t_file)
+            ! no file in multi file structure
+            IF( ASSOCIATED(td_multi%t_mpp) )THEN
+               CALL mpp_clean(td_multi%t_mpp(:))
+               DEALLOCATE(td_multi%t_mpp)
             ENDIF
-            ALLOCATE( td_multi%t_file(td_multi%i_nfile+1), stat=il_status )
+            ALLOCATE( td_multi%t_mpp(td_multi%i_nmpp+1), stat=il_status )
             IF(il_status /= 0 )THEN
 
-               CALL logger_error( " MULTI ADD FILE: not enough space to put "//&
-               &  "file in multi structure " )
+               CALL logger_error( " MULTI ADD MPP FILE: not enough space "//&
+               &  "to put mpp file in multi mpp file structure " )
 
             ENDIF
          ENDIF
 
-         td_multi%i_nfile=td_multi%i_nfile+1
-
-         ! add new file
-         td_multi%t_file(td_multi%i_nfile)=td_file
-
-         multi_add_file=td_multi%i_nfile
-
-      ENDIF
-   END FUNCTION multi_add_file
-   !> @endcode
+         ! update number of mpp
+         td_multi%i_nmpp=td_multi%i_nmpp+1
+
+         ! add new mpp
+         td_multi%t_mpp(td_multi%i_nmpp)=mpp_copy(td_mpp)
+
+      ENDIF
+   END SUBROUTINE multi__add_mpp
 END MODULE multi
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/phycst.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/phycst.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/phycst.f90	(revision 5075)
@@ -11,5 +11,5 @@
 !> J.paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
@@ -19,17 +19,18 @@
 
    IMPLICIT NONE
-
-   PUBLIC :: dg_pi      !< pi
-   PUBLIC :: dg_eps     !< epsilon value
-   PUBLIC :: dg_rearth  !< earth radius (km)
-   PUBLIC :: dg_deg2rad !< 
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
-   REAL(dp), PARAMETER :: dg_pi = 3.14159274101257_dp
-   REAL(dp), PARAMETER :: dg_eps = EPSILON(1._dp)
-   REAL(dp), PARAMETER :: dg_rearth = 6871._dp
-   REAL(dp), PARAMETER :: dg_deg2rad = dg_pi/180.0
+   PUBLIC :: dp_pi      !< pi
+   PUBLIC :: dp_eps     !< epsilon value
+   PUBLIC :: dp_rearth  !< earth radius (km)
+   PUBLIC :: dp_deg2rad !< degree to radian ratio 
+   PUBLIC :: dp_delta   !<  
 
+   REAL(dp), PARAMETER :: dp_pi = 3.14159274101257_dp
+   REAL(dp), PARAMETER :: dp_eps = EPSILON(1._dp)
+   REAL(dp), PARAMETER :: dp_rearth = 6871._dp
+   REAL(dp), PARAMETER :: dp_deg2rad = dp_pi/180.0
+
+   REAL(dp), PARAMETER :: dp_delta=1.e-2
 END MODULE phycst
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/variable.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/variable.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/variable.f90	(revision 5075)
@@ -11,28 +11,60 @@
 !> @details
 !>    define type TVAR:<br/>
-!>    TYPE(TVAR) :: tl_var<br/>
+!> @code
+!>    TYPE(TVAR) :: tl_var
+!> @endcode
 !>
-!>    the variable value will always be 4D table of real(8).<br/>
+!>    @note the variable value inside structure will always be 4D array of real(8).<br/>
 !>    However the variable value could be initialised with
-!>    table of real(4), real(8), integer(4) or integer(8)
+!>    array of real(4), real(8), integer(4) or integer(8).
 !>        
 !>    to initialise a variable structure:<br/>
-!>    tl_var=var_init( cd_name, [value,] [id_start, [id_count,]] [td_dim,] [td_att] )
+!> @code
+!>    tl_var=var_init( cd_name, [value,] [id_start, [id_count,]] [id_type,] [td_dim,] [td_att]... )
+!> @endcode
 !>       - cd_name is the variable name
-!>       - value is a 4D table ordered as ('x','y','z','t') (optional)
-!>          (real(4), real(8), integer(4) or integer(8)
-!>       - id_start is a integer(4) 1D table of index from which the data 
-!>          values will be read (optional)
-!>       - id_count is a integer(4) 1D table of the number of indices selected
-!>          along each dimension (optional)
-!>       - td_dim is the table of dimension structure (optional)
-!>       - td_att is the table of attribute structure (optional)
+!>       - value is a 1D,2D,3D or 4D array, see var_init for more information [optional]
+!>       - id_start is a integer(4) 1D array of index from which the data 
+!>          values will be read [optional]
+!>       - id_count is a integer(4) 1D array of the number of indices selected
+!>          along each dimension [optional]
+!>       - id_type is the type of the variable to be used [optional]
+!>       - td_dim is the array of dimension structure [optional]
+!>       - td_att is the array of attribute structure [optional]
+!>    Note:<br/>
+!>       - others optionals arguments could be added, see var_init.
+!>       - to put variable 0D, use td_dim with all dimension unused
+!> (td_dim(:)%l_use=.FALSE.)
+!>    
+!>    to print information about variable structure:<br/>
+!> @code
+!>    CALL var_print(td_var [,ld_more])
+!> @endcode
+!>       - td_var is the variable structure
+!>       - ld_more to print more infomration about variable
 !>
-!>    to print information about variable structure:<br/>
-!>    CALL var_print(tl_var)
+!>    to clean variable structure:<br/>
+!> @code
+!>    CALL var_clean(tl_var)
+!> @endcode
+!>
+!>    to copy variable structure in another one (using different memory cell):<br/>
+!> @code
+!>    tl_var2=var_copy(tl_var1) 
+!> @endcode
+!>    @note as we use pointer for the value array of the variable structure,
+!>    the use of the assignment operator (=) to copy variable structure 
+!>    create a pointer on the same array. 
+!>    This is not the case with this copy function.
 !>
 !>    to get variable name:<br/>
 !>    - tl_var\%c_name
-!>    
+!>
+!>    to get grid point of the variable:<br/>
+!>    - tl_var\%c_point
+!>
+!>    to get EW overlap:<br/>
+!>    - tl_var\%i_ew
+!>
 !>    to get variable value:<br/>
 !>    - tl_var\%d_value(:,:,:,:)
@@ -42,5 +74,5 @@
 !>    - tl_var\%i_type
 !>
-!>    to get variable id (affected when variable will be added to a file):<br/>
+!>    to get variable id (read from a file):<br/>
 !>    - tl_var\%i_id
 !>
@@ -49,14 +81,15 @@
 !>    - tl_var\%i_ndim
 !>
-!>    to get the table of dimension structure (4 elts) associated to the
+!>    to get the array of dimension structure (4 elts) associated to the
 !>    variable:<br/>
 !>    - tl_var\%t_dim(:)
 !>
 !>    Variable attributes<br/>
-!>    attribue value are always character or real(8) 1D table.<br/>
+!>    @note attribue value are always character or real(8) 1D array.<br/>
+!>
 !>    to get the number of attributes of the variable:<br/>
 !>    - tl_var\%i_natt
 !>
-!>    to get the table of attribute structure associated to the
+!>    to get the array of attribute structure associated to the
 !>    variable:<br/>
 !>    - tl_var\%t_att(:)
@@ -66,6 +99,12 @@
 !>    - tl_var\%c_stdname
 !>
+!>    to get variable longname:<br/>
+!>    - tl_var\%c_longname
+!>
 !>    to get variable units:<br/>
 !>    - tl_var\%c_units
+!>
+!>    to get variable axis:<br/>
+!>    - tl_var\%c_axis
 !>
 !>    to get variable scale factor:<br/>
@@ -79,50 +118,169 @@
 !>
 !>    to add value to a variable structure:<br/>
-!>    CALL var_add_value(tl_var, value, [id_start, [id_count]]) 
-!>       - value : 4D table of value (real(4), real(8), integer(4), integer(8))
-!>       - id_start : 1D table of the index in the variable from which the data
+!> @code
+!>    CALL var_add_value(tl_var, value, [id_type,] [id_start, [id_count]]) 
+!> @endcode
+!>       - value : 4D array of value (real(4), real(8), integer(1), integer(2), integer(4), integer(8))
+!>       - id_type is the type of the variable to be used (default is the type
+!> of array value)
+!>       - id_start : 1D array of the index in the variable from which the data
 !>       values will be read (integer(4), optional)
-!>       - id_count : 1D table of the number of indices selected along each 
+!>       - id_count : 1D array of the number of indices selected along each 
 !>       dimension (integer(4), optional)
 !>
-!>    to add one attribute to a variable structure:<br/>
+!>    to add attribute to a variable structure:<br/>
+!> @code
 !>    CALL var_add_att(tl_var, td_att)
-!>       - td_att is an attribute structure 
+!> @endcode
+!>       - td_att is an attribute structure, or array of attribute structure 
 !>
-!>    to add one dimension to a variable structure:<br/>
+!>    to add dimension to a variable structure:<br/>
+!> @code
 !>    CALL var_add_dim(tl_var, td_dim)
-!>       - td_dim is a dimension structure
+!> @endcode
+!>       - td_dim is a dimension structure, or array of dimension structure
 !> 
 !>    to delete value of a variable structure:<br/>
+!> @code
 !>    CALL var_del_value(tl_var)
+!> @endcode
 !>
 !>    to delete one attribute of a variable structure:<br/>
+!> @code
 !>    CALL var_del_att(tl_var, td_att)
+!> @endcode
 !>       - td_att is an attribute structure 
+!> or
+!> @code
+!>    CALL var_del_att(tl_var, cd_name)
+!> @endcode
+!>       - cd_name is attribute name 
 !>
 !>    to delete one dimension of a variable structure:<br/>
+!> @code
 !>    CALL var_del_dim(tl_var, td_dim)
+!> @endcode
 !>       - td_dim is a dimension structure
 !>
 !>    to overwrite one attribute structure in variable structure:<br/>
+!> @code
 !>    CALL var_move_att(tl_var, td_att)
+!> @endcode
 !>       - td_att is an attribute structure
 !>
 !>    to overwrite one dimension structure in variable structure:<br/>
+!> @code
 !>    CALL var_move_dim(tl_var, td_dim)
+!> @endcode
 !>       - td_dim is a dimension structure
 !>
+!>    to get the mask of a variable strucutre, (based on its FillValue):<br/>
+!> @code
+!>    mask(:,:)=var_get_mask(tl_var)
+!> @endcode
+!>
+!>    to change FillValue to standard NETCDF Fill Value:<br/>
+!> @code
+!>    CALL  var_chg_FillValue(tl_var, [dd_fill])
+!> @endcode
+!>       - dd_fill is the FillValue to be used [optional]
+!>
+!>    to concatenate two variables:<br/>
+!> @code
+!>    tl_var=var_concat(tl_var1, tl_var2, [DIM])
+!> @endcode
+!>       - tl_var1 : variable structure 
+!>       - tl_var2 : variable structure 
+!>       - DIM : number of the dimension following which concatenate (1=>I, 2=>J, 3=>Z, 4=>T) [optional, default=4]
+!>
+!>    to forced min and max value of a variable:<br/>
+!>    define min and max value of the variable:<br/>
+!>    tl_var\%d_min=min<br/>
+!>    tl_var\%d_max=max<br/>
+!>    then<br/>
+!> @code
+!>    CALL  var_limit_value( tl_var )
+!> @endcode
+!>       - min and max : real(8) value
+!>
+!>    to get the biggest dimensions use in a array of variable:<br/>
+!> @code
+!>    tl_dim(:)=var_max_dim(tl_var(:))
+!> @endcode
+!>       - tl_var(:) : array of variable structure
+!>       - tl_dim(:) : array (4 elts) of dimension structure
+!>
+!>    to reorder dimension of a variable (default 'x','y','z','t'):<br/>
+!> @code
+!>    CALL var_reorder( td_var, cd_dimorder )
+!> @endcode
+!>       - td_var is variable structure
+!>       - cd_dimorder string character(LEN=4) of dimension order to be used (example:
+!> 'yxzt') [optional]
+!>
+!>    to get variable index, in an array of variable structure:<br/>
+!> @code
+!>   il_index=var_get_index( td_var, cd_name )
+!> @endcode
+!>    - td_var array of variable structure
+!>    - cd_name variable name
+!> 
+!>    to get variable id, read from a file:<br/>
+!>@code
+!>  il_id=var_get_id( td_var, cd_name )
+!>@endcode
+!>    - td_var array of variable structure
+!>    - cd_name variable name
+!>
+!>    to get free variable unit in an array of variable structure:<br/>
+!>@code
+!>  il_unit=var_get_unit(td_var)
+!>@endcode
+!>    - td_var array of variable structure
+!>
+!>    to convert time variable structure in date structure:<br/>
+!>@code
+!>   tl_date=var_to_date(td_var) 
+!>@endcode
+!>    - td_var is time variable structure
+!>    - tl_date is date structure
+!>
+!>    to read matrix value from character string in namelist
+!>@code
+!>    CALL var_read_matrix(td_var, cd_matrix)
+!>@endcode
+!>    - td_var is variable structure
+!>    - cd_matrix is matrix value
+!>
+!>    to read variable configuration file ('variable.cfg') and fill global array
+!> of variable structure:<br/>
+!>@code
+!>    CALL var_def_extra( cd_file )
+!>@endcode
+!>    - cd_file is filename
+!>
+!>    to add variable information get from namelist, in global array of variable 
+!> structure:
+!>@code
+!>    CALL var_chg_extra( cd_varinfo )
+!>@endcode
+!>    - cd_varinfo is variable information from namelist
+!>
+!>    to check variable dimension expected, as defined in file 'variable.cfg':<br/>
+!>@code
+!>    CALL var_check_dim( td_var )
+!>@endcode
+!>    - td_var is variable structure
+!> 
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
+!> @date November, 2013 - Initial Version
+!> @date September, 2014
+!>  - add var_reorder
+!> @date November, 2014 
+!> - Fix memory leaks bug
 !
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
-!> - manage ew_wrap in structure
-!> - manage c_point in structure
-!> - think about create init for 0D 1D 2D 3D input table
-!> - creer module cfg qui lit et def tg_varcfg (pb var_get_extra appele ds
-!> var_init)
 !----------------------------------------------------------------------
 MODULE var
@@ -130,10 +288,10 @@
    USE global                          ! global variable
    USE kind                            ! F90 kind parameter
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
+   USE date                            ! date manager
    USE fct                             ! basic useful function
    USE att                             ! attribute manager
    USE dim                             ! dimension manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
@@ -141,90 +299,97 @@
    PUBLIC :: TVAR        !< variable structure
 
-   PUBLIC :: tg_varextra !< table of variable structure with extra information.
+   PUBLIC :: tg_varextra !< array of variable structure with extra information.
 
    ! function and subroutine
-   PUBLIC :: ASSIGNMENT(=) !< copy variable structure
-   PUBLIC :: var_init      !< initialize variable structure
-   PUBLIC :: var_print     !< print variable information
-   PUBLIC :: var_clean     !< clean variable structure
-   PUBLIC :: var_get_id    !< return the variable id, from a table of variable structure 
-   PUBLIC :: var_add_value !< add table of value in variable structure
-   PUBLIC :: var_add_att   !< add attribute structure in variable structure
-   PUBLIC :: var_add_dim   !< add dimension structure in variable structure
-   PUBLIC :: var_del_value !< delete table of value of variable structure
-   PUBLIC :: var_del_att   !< delete one attribute structure of variable structure
-   PUBLIC :: var_del_dim   !< delete one dimension structure of variable structure
-   PUBLIC :: var_move_att  !< overwrite one attribute structure in variable structure
-   PUBLIC :: var_move_dim  !< overwrite one dimension structure in variable structure 
-   PUBLIC :: var_get_mask  !< return the mask of variable
-   PUBLIC :: var_chg_FillValue  !< change FillValue to standard NETCDF Fill Value
-   PUBLIC :: var_def_extra  !< read variable configuration file, and save extra information.
-   PUBLIC :: var_chg_extra  !< read variable namelist information, and modify extra information.
-   PUBLIC :: var_read_matrix !<  
-!   PUBLIC :: var_match_file !< read variable namelist information, and modify extra information.
-   PUBLIC :: var_max_dim    !< get table of maximum dimension use
-   PUBLIC :: var_concat       !< concatenate two variables
-   PUBLIC :: var_limit_value  !< forced min and max value
-   PUBLIC :: var_check_dim    !< check variable dimension expected
-
-!   PUBLIC :: var_ended     !< deallocate global variable
-
-   PRIVATE :: var__add_value_dp  !< add table of value real(8) in variable structure
-   PRIVATE :: var__add_value_rp  !< add table of value real(4) in variable structure
-   PRIVATE :: var__add_value_i1  !< add table of value integer(1) in variable structure
-   PRIVATE :: var__add_value_i2  !< add table of value integer(2) in variable structure
-   PRIVATE :: var__add_value_i4  !< add table of value integer(4) in variable structure
-   PRIVATE :: var__add_value_i8  !< add table of value integer(8) in variable structure
-   PRIVATE :: var__init          !< initialse variable structure without table of value
-   PRIVATE :: var__init_dp       !< initialse variable structure with real(8) 4D table of value
-   PRIVATE :: var__init_1D_dp    !< initialse variable structure with real(8) 1D table of value
-   PRIVATE :: var__init_2D_dp    !< initialse variable structure with real(8) 2D table of value
-   PRIVATE :: var__init_3D_dp    !< initialse variable structure with real(8) 3D table of value
-   PRIVATE :: var__init_sp       !< initialse variable structure with real(4) 4D table of value
-   PRIVATE :: var__init_1D_sp    !< initialse variable structure with real(4) 1D table of value
-   PRIVATE :: var__init_2D_sp    !< initialse variable structure with real(4) 2D table of value
-   PRIVATE :: var__init_3D_sp    !< initialse variable structure with real(4) 3D table of value
-   PRIVATE :: var__init_i1       !< initialse variable structure with integer(1) 4D table of value
-   PRIVATE :: var__init_1D_i1    !< initialse variable structure with integer(1) 1D table of value
-   PRIVATE :: var__init_2D_i1    !< initialse variable structure with integer(1) 2D table of value
-   PRIVATE :: var__init_3D_i1    !< initialse variable structure with integer(1) 3D table of value
-   PRIVATE :: var__init_i2       !< initialse variable structure with integer(2) 4D table of value
-   PRIVATE :: var__init_1D_i2    !< initialse variable structure with integer(2) 1D table of value
-   PRIVATE :: var__init_2D_i2    !< initialse variable structure with integer(2) 2D table of value
-   PRIVATE :: var__init_3D_i2    !< initialse variable structure with integer(2) 3D table of value
-   PRIVATE :: var__init_i4       !< initialse variable structure with integer(4) 4D table of value
-   PRIVATE :: var__init_1D_i4    !< initialse variable structure with integer(4) 1D table of value
-   PRIVATE :: var__init_2D_i4    !< initialse variable structure with integer(4) 2D table of value
-   PRIVATE :: var__init_3D_i4    !< initialse variable structure with integer(4) 3D table of value
-   PRIVATE :: var__init_i8       !< initialse variable structure with integer(8) 4D table of value
-   PRIVATE :: var__init_1D_i8    !< initialse variable structure with integer(8) 1D table of value
-   PRIVATE :: var__init_2D_i8    !< initialse variable structure with integer(8) 2D table of value
-   PRIVATE :: var__init_3D_i8    !< initialse variable structure with integer(8) 3D table of value
-   PRIVATE :: var__add_dim_unit  !< add one dimension structure in variable structure
-   PRIVATE :: var__add_dim_tab   !< add a table of dimension structure in variable structure
-   PRIVATE :: var__add_att_unit  !< add one attribute structure in variable structure
-   PRIVATE :: var__add_att_tab   !< add a table of attribute structure in variable structure
-   PRIVATE :: var__add_dim       !< add a dimension structure in a variable structure.
-   PRIVATE :: var__add_value     !< add a 4D table of double value in a variable structure.
-   PRIVATE :: var__copy_unit     !< copy variable structure
-   PRIVATE :: var__copy_tab      !< copy variable structure
-   PRIVATE :: var__get_extra     !< add extra information in variable structure
-   PRIVATE :: var__concat_i      !< concatenate varibales in i-direction
-   PRIVATE :: var__concat_j      !< concatenate varibales in j-direction
-   PRIVATE :: var__concat_k      !< concatenate varibales in k-direction
-   PRIVATE :: var__concat_l      !< concatenate varibales in l-direction
-   PRIVATE :: var__get_max       !< get maximum value from namelist 
-   PRIVATE :: var__get_min       !< get minimum value from namelist
-   PRIVATE :: var__get_interp    !< get interpolation method from namelist
-   PRIVATE :: var__get_extrap    !< get extrapolation method from namelist
-   PRIVATE :: var__get_filter    !< get filter method from namelist
-
-   !> @struct TVAR
-   TYPE TVAR
+   PUBLIC :: var_init          !< initialize variable structure
+   PUBLIC :: var_print         !< print variable information
+   PUBLIC :: var_clean         !< clean variable structure
+   PUBLIC :: var_copy          !< copy variable structure
+   PUBLIC :: var_add_value     !< add array of value in variable structure
+   PUBLIC :: var_add_att       !< add attribute structure in variable structure
+   PUBLIC :: var_add_dim       !< add dimension structure in variable structure
+   PUBLIC :: var_del_value     !< delete array of value of variable structure
+   PUBLIC :: var_del_att       !< delete one attribute structure of variable structure
+   PUBLIC :: var_del_dim       !< delete one dimension structure of variable structure
+   PUBLIC :: var_move_att      !< overwrite one attribute structure in variable structure
+   PUBLIC :: var_move_dim      !< overwrite one dimension structure in variable structure 
+   PUBLIC :: var_get_mask      !< return the mask of variable
+   PUBLIC :: var_chg_FillValue !< change FillValue to standard NETCDF Fill Value
+   PUBLIC :: var_concat        !< concatenate two variables
+   PUBLIC :: var_limit_value   !< forced min and max value
+   PUBLIC :: var_max_dim       !< get array of maximum dimension use
+   PUBLIC :: var_reorder       !< reorder table of value in variable structure
+   PUBLIC :: var_get_index     !< return the variable index, in an array of variable structure 
+   PUBLIC :: var_get_id        !< return the variable id, read from a file 
+   PUBLIC :: var_get_unit      !< get free variable unit in an array of variable structure
+   PUBLIC :: var_to_date       !< convert time variable structure in date structure
+   PUBLIC :: var_read_matrix   !< read matrix value from character string in namelist 
+   PUBLIC :: var_def_extra     !< read variable configuration file, and save extra information.
+   PUBLIC :: var_chg_extra     !< read variable namelist information, and modify extra information.
+   PUBLIC :: var_check_dim     !< check variable dimension expected
+
+   PRIVATE :: var__init          ! initialize variable structure without array of value
+   PRIVATE :: var__init_dp       ! initialize variable structure with real(8) 4D array of value
+   PRIVATE :: var__init_1D_dp    ! initialize variable structure with real(8) 1D array of value
+   PRIVATE :: var__init_2D_dp    ! initialize variable structure with real(8) 2D array of value
+   PRIVATE :: var__init_3D_dp    ! initialize variable structure with real(8) 3D array of value
+   PRIVATE :: var__init_sp       ! initialize variable structure with real(4) 4D array of value
+   PRIVATE :: var__init_1D_sp    ! initialize variable structure with real(4) 1D array of value
+   PRIVATE :: var__init_2D_sp    ! initialize variable structure with real(4) 2D array of value
+   PRIVATE :: var__init_3D_sp    ! initialize variable structure with real(4) 3D array of value
+   PRIVATE :: var__init_i1       ! initialize variable structure with integer(1) 4D array of value
+   PRIVATE :: var__init_1D_i1    ! initialize variable structure with integer(1) 1D array of value
+   PRIVATE :: var__init_2D_i1    ! initialize variable structure with integer(1) 2D array of value
+   PRIVATE :: var__init_3D_i1    ! initialize variable structure with integer(1) 3D array of value
+   PRIVATE :: var__init_i2       ! initialize variable structure with integer(2) 4D array of value
+   PRIVATE :: var__init_1D_i2    ! initialize variable structure with integer(2) 1D array of value
+   PRIVATE :: var__init_2D_i2    ! initialize variable structure with integer(2) 2D array of value
+   PRIVATE :: var__init_3D_i2    ! initialize variable structure with integer(2) 3D array of value
+   PRIVATE :: var__init_i4       ! initialize variable structure with integer(4) 4D array of value
+   PRIVATE :: var__init_1D_i4    ! initialize variable structure with integer(4) 1D array of value
+   PRIVATE :: var__init_2D_i4    ! initialize variable structure with integer(4) 2D array of value
+   PRIVATE :: var__init_3D_i4    ! initialize variable structure with integer(4) 3D array of value
+   PRIVATE :: var__init_i8       ! initialize variable structure with integer(8) 4D array of value
+   PRIVATE :: var__init_1D_i8    ! initialize variable structure with integer(8) 1D array of value
+   PRIVATE :: var__init_2D_i8    ! initialize variable structure with integer(8) 2D array of value
+   PRIVATE :: var__init_3D_i8    ! initialize variable structure with integer(8) 3D array of value
+   PRIVATE :: var__print_unit ! print information on one variable
+   PRIVATE :: var__print_arr  ! print information on a array of variables
+   PRIVATE :: var__clean_unit    ! clean variable structure
+   PRIVATE :: var__clean_arr_1D  ! clean 1D array of variable structure
+   PRIVATE :: var__clean_arr_2D  ! clean 2D array of variable structure
+   PRIVATE :: var__clean_arr_3D  ! clean 3D array of variable structure
+   PRIVATE :: var__add_value_dp  ! add array of value real(8) in variable structure
+   PRIVATE :: var__add_value_rp  ! add array of value real(4) in variable structure
+   PRIVATE :: var__add_value_i1  ! add array of value integer(1) in variable structure
+   PRIVATE :: var__add_value_i2  ! add array of value integer(2) in variable structure
+   PRIVATE :: var__add_value_i4  ! add array of value integer(4) in variable structure
+   PRIVATE :: var__add_value_i8  ! add array of value integer(8) in variable structure
+   PRIVATE :: var__add_att_unit  ! add one attribute structure in variable structure
+   PRIVATE :: var__add_att_arr   ! add a array of attribute structure in variable structure
+   PRIVATE :: var__del_att_name  ! delete one attribute given attribute name
+   PRIVATE :: var__del_att_str   ! delete one attribute given attribute structure
+   PRIVATE :: var__add_dim_unit  ! add one dimension structure in variable structure
+   PRIVATE :: var__add_dim_arr   ! add a array of dimension structure in variable structure
+   PRIVATE :: var__add_value     ! add a 4D array of real(8) value in a variable structure.
+   PRIVATE :: var__copy_unit     ! copy variable structure
+   PRIVATE :: var__copy_arr      ! copy a array of variable structure
+   PRIVATE :: var__get_extra     ! add extra information in variable structure
+   PRIVATE :: var__concat_i      ! concatenate varibales in i-direction
+   PRIVATE :: var__concat_j      ! concatenate varibales in j-direction
+   PRIVATE :: var__concat_k      ! concatenate varibales in k-direction
+   PRIVATE :: var__concat_l      ! concatenate varibales in l-direction
+   PRIVATE :: var__get_max       ! get maximum value from namelist 
+   PRIVATE :: var__get_min       ! get minimum value from namelist
+   PRIVATE :: var__get_interp    ! get interpolation method from namelist
+   PRIVATE :: var__get_extrap    ! get extrapolation method from namelist
+   PRIVATE :: var__get_filter    ! get filter method from namelist
+
+   TYPE TVAR   !< variable structure
 
       CHARACTER(LEN=lc) :: c_name  = ''  !< variable name
-      CHARACTER(LEN=lc) :: c_point = '' !< type of grid point
+      CHARACTER(LEN=lc) :: c_point = 'T' !< ARAKAWA C-grid point name (T,U,V,F)
       INTEGER(i4)       :: i_id = 0      !< variable id
-      INTEGER(i4)       :: i_ew = 0      !< east-west overlap
+      INTEGER(i4)       :: i_ew = -1     !< east-west overlap
 
       REAL(dp)   , DIMENSION(:,:,:,:), POINTER :: d_value => NULL() !< variable value
@@ -237,5 +402,7 @@
       TYPE(TDIM), DIMENSION(ip_maxdim)  :: t_dim           !< variable dimension
       
-      ! highlight some attribute
+      LOGICAL           :: l_file = .FALSE.  !< variable read in a file
+
+      ! highlight some attributes
       CHARACTER(LEN=lc) :: c_stdname  = ''!< variable standard name
       CHARACTER(LEN=lc) :: c_longname = ''!< variable long name
@@ -245,6 +412,6 @@
       REAL(dp)          :: d_ofs = 0.           !< offset
       REAL(dp)          :: d_fill= 0.           !< fill value     ! NF90_FILL_DOUBLE 
-      REAL(dp)          :: d_min = dg_fill      !< minimum value 
-      REAL(dp)          :: d_max = dg_fill      !< maximum value 
+      REAL(dp)          :: d_min = dp_fill      !< minimum value 
+      REAL(dp)          :: d_max = dp_fill      !< maximum value 
       
       !!! netcdf4
@@ -256,5 +423,5 @@
 
       !!! dimg
-      INTEGER(i4) :: i_rec = 0 !< record number
+      INTEGER(i4) :: i_rec  = 0 !< record number
 
       CHARACTER(LEN=lc), DIMENSION(2) :: c_interp = '' !< interpolation method
@@ -264,83 +431,104 @@
    END TYPE TVAR
 
-   TYPE(TVAR), DIMENSION(:), ALLOCATABLE :: tg_varextra !< table of variable structure with extra information.
+   TYPE(TVAR), DIMENSION(:), ALLOCATABLE :: tg_varextra !< array of variable structure with extra information.
                                                         !< fill when running var_def_extra() 
 
+   INTERFACE var_init
+      MODULE PROCEDURE var__init       ! initialize variable structure without array of value
+      MODULE PROCEDURE var__init_dp    ! initialize variable structure with real(8) 4D array of value
+      MODULE PROCEDURE var__init_1D_dp ! initialize variable structure with real(8) 1D array of value
+      MODULE PROCEDURE var__init_2D_dp ! initialize variable structure with real(8) 2D array of value
+      MODULE PROCEDURE var__init_3D_dp ! initialize variable structure with real(8) 3D array of value
+      MODULE PROCEDURE var__init_sp    ! initialize variable structure with real(4) 4D array of value
+      MODULE PROCEDURE var__init_1D_sp ! initialize variable structure with real(4) 1D array of value
+      MODULE PROCEDURE var__init_2D_sp ! initialize variable structure with real(4) 2D array of value
+      MODULE PROCEDURE var__init_3D_sp ! initialize variable structure with real(4) 3D array of value
+      MODULE PROCEDURE var__init_i1    ! initialize variable structure with integer(1) 4D array of value
+      MODULE PROCEDURE var__init_1D_i1 ! initialize variable structure with integer(1) 1D array of value
+      MODULE PROCEDURE var__init_2D_i1 ! initialize variable structure with integer(1) 2D array of value
+      MODULE PROCEDURE var__init_3D_i1 ! initialize variable structure with integer(1) 3D array of value
+      MODULE PROCEDURE var__init_i2    ! initialize variable structure with integer(2) 4D array of value
+      MODULE PROCEDURE var__init_1D_i2 ! initialize variable structure with integer(2) 1D array of value
+      MODULE PROCEDURE var__init_2D_i2 ! initialize variable structure with integer(2) 2D array of value
+      MODULE PROCEDURE var__init_3D_i2 ! initialize variable structure with integer(2) 3D array of value
+      MODULE PROCEDURE var__init_i4    ! initialize variable structure with integer(4) 4D array of value
+      MODULE PROCEDURE var__init_1D_i4 ! initialize variable structure with integer(4) 1D array of value
+      MODULE PROCEDURE var__init_2D_i4 ! initialize variable structure with integer(4) 2D array of value
+      MODULE PROCEDURE var__init_3D_i4 ! initialize variable structure with integer(4) 3D array of value
+      MODULE PROCEDURE var__init_i8    ! initialize variable structure with integer(8) 4D array of value
+      MODULE PROCEDURE var__init_1D_i8 ! initialize variable structure with integer(8) 1D array of value
+      MODULE PROCEDURE var__init_2D_i8 ! initialize variable structure with integer(8) 2D array of value
+      MODULE PROCEDURE var__init_3D_i8 ! initialize variable structure with integer(8) 3D array of value
+   END INTERFACE var_init
+
+   INTERFACE var_print
+      MODULE PROCEDURE var__print_unit ! print information on one variable
+      MODULE PROCEDURE var__print_arr  ! print information on a array of variables
+   END INTERFACE var_print
+   
+   INTERFACE var_clean
+      MODULE PROCEDURE var__clean_unit   
+      MODULE PROCEDURE var__clean_arr_1D    
+      MODULE PROCEDURE var__clean_arr_2D    
+      MODULE PROCEDURE var__clean_arr_3D    
+   END INTERFACE
+
    INTERFACE var_add_value
-      MODULE PROCEDURE var__add_value_dp  ! add table of value real(8) in variable structure
-      MODULE PROCEDURE var__add_value_rp  ! add table of value real(4) in variable structure
-      MODULE PROCEDURE var__add_value_i1  ! add table of value integer(1) in variable structure
-      MODULE PROCEDURE var__add_value_i2  ! add table of value integer(2) in variable structure
-      MODULE PROCEDURE var__add_value_i4  ! add table of value integer(4) in variable structure
-      MODULE PROCEDURE var__add_value_i8  ! add table of value integer(8) in variable structure
+      MODULE PROCEDURE var__add_value_dp  ! add array of value real(8) in variable structure
+      MODULE PROCEDURE var__add_value_rp  ! add array of value real(4) in variable structure
+      MODULE PROCEDURE var__add_value_i1  ! add array of value integer(1) in variable structure
+      MODULE PROCEDURE var__add_value_i2  ! add array of value integer(2) in variable structure
+      MODULE PROCEDURE var__add_value_i4  ! add array of value integer(4) in variable structure
+      MODULE PROCEDURE var__add_value_i8  ! add array of value integer(8) in variable structure
    END INTERFACE var_add_value
 
-   INTERFACE var_init
-      MODULE PROCEDURE var__init       ! initialse variable structure without table of value
-      MODULE PROCEDURE var__init_dp    ! initialse variable structure with real(8) 4D table of value
-      MODULE PROCEDURE var__init_1D_dp ! initialse variable structure with real(8) 1D table of value
-      MODULE PROCEDURE var__init_2D_dp ! initialse variable structure with real(8) 2D table of value
-      MODULE PROCEDURE var__init_3D_dp ! initialse variable structure with real(8) 3D table of value
-      MODULE PROCEDURE var__init_sp    ! initialse variable structure with real(4) 4D table of value
-      MODULE PROCEDURE var__init_1D_sp ! initialse variable structure with real(4) 1D table of value
-      MODULE PROCEDURE var__init_2D_sp ! initialse variable structure with real(4) 2D table of value
-      MODULE PROCEDURE var__init_3D_sp ! initialse variable structure with real(4) 3D table of value
-      MODULE PROCEDURE var__init_i1    ! initialse variable structure with integer(1) 4D table of value
-      MODULE PROCEDURE var__init_1D_i1 ! initialse variable structure with integer(1) 1D table of value
-      MODULE PROCEDURE var__init_2D_i1 ! initialse variable structure with integer(1) 2D table of value
-      MODULE PROCEDURE var__init_3D_i1 ! initialse variable structure with integer(1) 3D table of value
-      MODULE PROCEDURE var__init_i2    ! initialse variable structure with integer(2) 4D table of value
-      MODULE PROCEDURE var__init_1D_i2 ! initialse variable structure with integer(2) 1D table of value
-      MODULE PROCEDURE var__init_2D_i2 ! initialse variable structure with integer(2) 2D table of value
-      MODULE PROCEDURE var__init_3D_i2 ! initialse variable structure with integer(2) 3D table of value
-      MODULE PROCEDURE var__init_i4    ! initialse variable structure with integer(4) 4D table of value
-      MODULE PROCEDURE var__init_1D_i4 ! initialse variable structure with integer(4) 1D table of value
-      MODULE PROCEDURE var__init_2D_i4 ! initialse variable structure with integer(4) 2D table of value
-      MODULE PROCEDURE var__init_3D_i4 ! initialse variable structure with integer(4) 3D table of value
-      MODULE PROCEDURE var__init_i8    ! initialse variable structure with integer(8) 4D table of value
-      MODULE PROCEDURE var__init_1D_i8 ! initialse variable structure with integer(8) 1D table of value
-      MODULE PROCEDURE var__init_2D_i8 ! initialse variable structure with integer(8) 2D table of value
-      MODULE PROCEDURE var__init_3D_i8 ! initialse variable structure with integer(8) 3D table of value
-   END INTERFACE var_init
+   INTERFACE var_add_att
+      MODULE PROCEDURE var__add_att_unit ! add one attribute structure in variable structure
+      MODULE PROCEDURE var__add_att_arr  ! add a array of attribute structure in variable structure
+   END INTERFACE var_add_att
+
+   INTERFACE var_del_att               ! delete one attribute in variable structure
+      MODULE PROCEDURE var__del_att_name ! - given attribute name
+      MODULE PROCEDURE var__del_att_str  ! - given attribute structure
+   END INTERFACE var_del_att
 
    INTERFACE var_add_dim
       MODULE PROCEDURE var__add_dim_unit ! add one dimension structure in variable structure
-      MODULE PROCEDURE var__add_dim_tab  ! add a table of dimension structure in variable structure
+      MODULE PROCEDURE var__add_dim_arr  ! add a array of dimension structure in variable structure
    END INTERFACE var_add_dim
 
-   INTERFACE var_add_att
-      MODULE PROCEDURE var__add_att_unit ! add one attribute structure in variable structure
-      MODULE PROCEDURE var__add_att_tab  ! add a table of attribute structure in variable structure
-   END INTERFACE var_add_att
-
-   INTERFACE ASSIGNMENT(=)
+   INTERFACE var_copy
       MODULE PROCEDURE var__copy_unit   ! copy variable structure
-      MODULE PROCEDURE var__copy_tab    ! copy variable structure
+      MODULE PROCEDURE var__copy_arr    ! copy variable structure
    END INTERFACE
 CONTAINS
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine copy variable structure in another variable
-   !> structure
+   !> This subroutine copy variable structure in another one
    !> @details 
-   !> variable value are copied in a temporary table, so input and output
+   !> variable value are copied in a temporary array, so input and output
    !> variable structure value do not point on the same "memory cell", and so
    !> are independant. 
    !>
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_var=var_copy(var_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[out] td_var1  : variable structure
-   !> @param[in] td_var2  : variable structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__copy_unit( td_var1, td_var2 )
+   !> - November, 2013- Initial Version
+   !> @date November, 2014
+   !> - use function instead of overload assignment operator (to avoid memory leak)
+   !
+   !> @param[in] td_var   variable structure
+   !> @return copy of input variable structure
+   !-------------------------------------------------------------------
+   FUNCTION var__copy_unit( td_var )
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR), INTENT(OUT) :: td_var1
-      TYPE(TVAR), INTENT(IN)  :: td_var2
+      TYPE(TVAR), INTENT(IN) :: td_var
+      ! function
+      TYPE(TVAR) :: var__copy_unit
 
       ! local variable
@@ -353,97 +541,104 @@
 
       ! copy variable name, id, ..
-      td_var1%c_name     = TRIM(td_var2%c_name)
-      td_var1%c_point    = TRIM(td_var2%c_point)
-      td_var1%i_id       = td_var2%i_id
-      td_var1%i_ew       = td_var2%i_ew
-
-      td_var1%d_min      = td_var2%d_min
-      td_var1%d_max      = td_var2%d_max
-
-      td_var1%i_type     = td_var2%i_type
-      td_var1%i_natt     = td_var2%i_natt
-      td_var1%i_ndim     = td_var2%i_ndim
-      td_var1%i_ndim     = td_var2%i_ndim
+      var__copy_unit%c_name     = TRIM(td_var%c_name)
+      var__copy_unit%c_point    = TRIM(td_var%c_point)
+      var__copy_unit%i_id       = td_var%i_id
+      var__copy_unit%i_ew       = td_var%i_ew
+
+      var__copy_unit%d_min      = td_var%d_min
+      var__copy_unit%d_max      = td_var%d_max
+
+      var__copy_unit%i_type     = td_var%i_type
+      var__copy_unit%i_natt     = td_var%i_natt
+      var__copy_unit%i_ndim     = td_var%i_ndim
+      var__copy_unit%i_ndim     = td_var%i_ndim
 
       ! copy dimension
-      td_var1%t_dim(:)   = td_var2%t_dim(:)
+      var__copy_unit%t_dim(:)   = dim_copy(td_var%t_dim(:))
 
       ! copy attribute
-      IF( ASSOCIATED(td_var1%t_att) ) DEALLOCATE(td_var1%t_att)
-      IF( ASSOCIATED(td_var2%t_att) .AND. td_var1%i_natt > 0 )THEN
-         ALLOCATE( td_var1%t_att(td_var1%i_natt) )
-         DO ji=1,td_var1%i_natt
-            tl_att=td_var2%t_att(ji)
-            td_var1%t_att(ji)=tl_att
+      IF( ASSOCIATED(var__copy_unit%t_att) )THEN
+         CALL att_clean( var__copy_unit%t_att(:) )
+         DEALLOCATE(var__copy_unit%t_att)
+      ENDIF
+      IF( ASSOCIATED(td_var%t_att) .AND. var__copy_unit%i_natt > 0 )THEN
+         ALLOCATE( var__copy_unit%t_att(var__copy_unit%i_natt) )
+         DO ji=1,var__copy_unit%i_natt
+            tl_att=att_copy(td_var%t_att(ji))
+            var__copy_unit%t_att(ji)=att_copy(tl_att)
          ENDDO
+         ! clean
+         CALL att_clean(tl_att)
       ENDIF
 
       ! copy highlight attribute
-      td_var1%c_stdname  = TRIM(td_var2%c_stdname)
-      td_var1%c_longname = TRIM(td_var2%c_longname)
-      td_var1%c_units    = TRIM(td_var2%c_units)
-      td_var1%c_axis     = TRIM(td_var2%c_axis)
-      td_var1%d_scf      = td_var2%d_scf
-      td_var1%d_ofs      = td_var2%d_ofs
-      td_var1%d_fill     = td_var2%d_fill
+      var__copy_unit%c_stdname  = TRIM(td_var%c_stdname)
+      var__copy_unit%c_longname = TRIM(td_var%c_longname)
+      var__copy_unit%c_units    = TRIM(td_var%c_units)
+      var__copy_unit%c_axis     = TRIM(td_var%c_axis)
+      var__copy_unit%d_scf      = td_var%d_scf
+      var__copy_unit%d_ofs      = td_var%d_ofs
+      var__copy_unit%d_fill     = td_var%d_fill
       
       ! copy netcdf4 variable
-      td_var1%l_contiguous  = td_var2%l_contiguous
-      td_var1%l_shuffle     = td_var2%l_shuffle
-      td_var1%l_fletcher32  = td_var2%l_fletcher32 
-      td_var1%i_deflvl      = td_var2%i_deflvl
-      td_var1%i_chunksz(:)  = td_var2%i_chunksz(:)
+      var__copy_unit%l_contiguous  = td_var%l_contiguous
+      var__copy_unit%l_shuffle     = td_var%l_shuffle
+      var__copy_unit%l_fletcher32  = td_var%l_fletcher32 
+      var__copy_unit%i_deflvl      = td_var%i_deflvl
+      var__copy_unit%i_chunksz(:)  = td_var%i_chunksz(:)
       
       ! copy dimg variable
-      td_var1%i_rec = td_var2%i_rec
+      var__copy_unit%i_rec = td_var%i_rec
 
       ! copy pointer in an independant variable
-      IF( ASSOCIATED(td_var1%d_value) ) DEALLOCATE(td_var1%d_value)
-      IF( ASSOCIATED(td_var2%d_value) )THEN
-         ALLOCATE( dl_value( td_var2%t_dim(1)%i_len, &
-         &                   td_var2%t_dim(2)%i_len, &
-         &                   td_var2%t_dim(3)%i_len, &
-         &                   td_var2%t_dim(4)%i_len ) )
-         dl_value(:,:,:,:)=td_var2%d_value(:,:,:,:)
-
-         ALLOCATE( td_var1%d_value( td_var1%t_dim(1)%i_len, &
-         &                          td_var1%t_dim(2)%i_len, &
-         &                          td_var1%t_dim(3)%i_len, &
-         &                          td_var1%t_dim(4)%i_len ) )
-         td_var1%d_value(:,:,:,:)=dl_value(:,:,:,:)
+      IF( ASSOCIATED(var__copy_unit%d_value) ) DEALLOCATE(var__copy_unit%d_value)
+      IF( ASSOCIATED(td_var%d_value) )THEN
+         ALLOCATE( dl_value( td_var%t_dim(1)%i_len, &
+         &                   td_var%t_dim(2)%i_len, &
+         &                   td_var%t_dim(3)%i_len, &
+         &                   td_var%t_dim(4)%i_len ) )
+         dl_value(:,:,:,:)=td_var%d_value(:,:,:,:)
+
+         ALLOCATE( var__copy_unit%d_value( var__copy_unit%t_dim(1)%i_len, &
+         &                          var__copy_unit%t_dim(2)%i_len, &
+         &                          var__copy_unit%t_dim(3)%i_len, &
+         &                          var__copy_unit%t_dim(4)%i_len ) )
+         var__copy_unit%d_value(:,:,:,:)=dl_value(:,:,:,:)
 
          DEALLOCATE( dl_value )
       ENDIF
 
-      td_var1%c_interp(:)=td_var2%c_interp(:)
-      td_var1%c_extrap(:)=td_var2%c_extrap(:)
-      td_var1%c_filter(:)=td_var2%c_filter(:)
-
-   END SUBROUTINE var__copy_unit
-   !> @endcode
+      var__copy_unit%c_interp(:)=td_var%c_interp(:)
+      var__copy_unit%c_extrap(:)=td_var%c_extrap(:)
+      var__copy_unit%c_filter(:)=td_var%c_filter(:)
+
+   END FUNCTION var__copy_unit
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine copy variable structure in another variable
-   !> structure
+   !> This subroutine copy a array of variable structure in another one
    !> @details 
-   !> variable value are copied in a temporary table, so input and output
-   !> variable structure value do not point on the same "memory cell", and so
-   !> are independant. 
-   !>
+   !> see var__copy_unit
+   !>
+   !> @warning do not use on the output of a function who create or read an
+   !> structure (ex: tl_var=var_copy(var_init()) is forbidden).
+   !> This will create memory leaks.
    !> @warning to avoid infinite loop, do not use any function inside 
    !> this subroutine
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[out] td_var1  : variable structure
-   !> @param[in] td_var2  : variable structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__copy_tab( td_var1, td_var2 )
+   !> - November, 2013- Initial Version
+   !> @date November, 2014
+   !> - use function instead of overload assignment operator 
+   !> (to avoid memory leak)
+   !
+   !> @param[in] td_var   array of variable structure
+   !> @return copy of input array of variable structure
+   !-------------------------------------------------------------------
+   FUNCTION var__copy_arr( td_var )
       IMPLICIT NONE
       ! Argument
-      TYPE(TVAR), DIMENSION(:), INTENT(IN   )  :: td_var2
-      TYPE(TVAR), DIMENSION(:), INTENT(  OUT) :: td_var1
+      TYPE(TVAR), DIMENSION(:), INTENT(IN   ) :: td_var
+      ! function
+      TYPE(TVAR), DIMENSION(SIZE(td_var(:))) :: var__copy_arr
 
       ! local variable
@@ -452,24 +647,18 @@
       !----------------------------------------------------------------
 
-      IF( SIZE(td_var2(:))/=SIZE(td_var1(:)) )THEN
-         CALL logger_error("VAR COPY: variable structure dimension differ")
-      ELSE
-         DO ji=1,SIZE(td_var2(:))
-            td_var1(ji)=td_var2(ji)
-         ENDDO
-      ENDIF
-
-   END SUBROUTINE var__copy_tab
-   !> @endcode
+      DO ji=1,SIZE(td_var(:))
+         var__copy_arr(ji)=var_copy(td_var(ji))
+      ENDDO
+
+   END FUNCTION var__copy_arr
    !-------------------------------------------------------------------
    !> @brief This subroutine clean variable structure
-   !
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : variable strucutre
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var_clean( td_var )
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_var variable strucutre
+   !-------------------------------------------------------------------
+   SUBROUTINE var__clean_unit( td_var )
       IMPLICIT NONE
       ! Argument
@@ -480,25 +669,15 @@
 
       ! loop indices
-      INTEGER(i4) :: ji
       !----------------------------------------------------------------
-
-      CALL logger_info( &
-      &  " CLEAN: reset variable "//TRIM(td_var%c_name) )
 
       ! del attribute
       IF( ASSOCIATED(td_var%t_att) )THEN
-         ! clean each attribute
-         DO ji=td_var%i_natt,1,-1
-            CALL att_clean(td_var%t_att(ji) )
-         ENDDO
-         DEALLOCATE( td_var%t_att )
+         CALL att_clean( td_var%t_att(:) )
+         DEALLOCATE(td_var%t_att)
       ENDIF
 
       ! del dimension
       IF( td_var%i_ndim /= 0 )THEN
-         ! clean each dimension
-         DO ji=td_var%i_ndim,1,-1
-            CALL dim_clean(td_var%t_dim(ji))
-         ENDDO
+         CALL dim_clean(td_var%t_dim(:))
       ENDIF
 
@@ -509,42 +688,151 @@
 
       ! replace by empty structure
-      td_var=tl_var
-
-   END SUBROUTINE var_clean
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !
-   !> @details 
+      td_var=var_copy(tl_var)
+
+   END SUBROUTINE var__clean_unit
+   !-------------------------------------------------------------------
+   !> @brief This subroutine clean 1D array of variable structure
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] dd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !> @param[in] cd_interp  : interpolation method
-   !> @param[in] cd_extrap  : extrapolation method
-   !> @param[in] cd_filter  : filter method
-   !-------------------------------------------------------------------
-   !> @code
+   !> - September, 2014- Initial Version
+   !
+   !> @param[inout] td_var array of variable strucutre
+   !-------------------------------------------------------------------
+   SUBROUTINE var__clean_arr_1D( td_var )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR), DIMENSION(:), INTENT(INOUT) :: td_var
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+
+      DO ji=SIZE(td_var(:)),1,-1
+         CALL var_clean(td_var(ji))
+      ENDDO
+
+   END SUBROUTINE var__clean_arr_1D
+   !-------------------------------------------------------------------
+   !> @brief This subroutine clean 2D array of variable structure
+   !
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !
+   !> @param[inout] td_var array of variable strucutre
+   !-------------------------------------------------------------------
+   SUBROUTINE var__clean_arr_2D( td_var )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR), DIMENSION(:,:), INTENT(INOUT) :: td_var
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      !----------------------------------------------------------------
+
+      DO jj=SIZE(td_var(:,:),DIM=2),1,-1
+         DO ji=SIZE(td_var(:,:),DIM=1),1,-1
+            CALL var_clean(td_var(ji,jj))
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE var__clean_arr_2D
+   !-------------------------------------------------------------------
+   !> @brief This subroutine clean 3D array of variable structure
+   !
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !
+   !> @param[inout] td_var array of variable strucutre
+   !-------------------------------------------------------------------
+   SUBROUTINE var__clean_arr_3D( td_var )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR), DIMENSION(:,:,:), INTENT(INOUT) :: td_var
+
+      ! local variable
+      ! loop indices
+      INTEGER(i4) :: ji
+      INTEGER(i4) :: jj
+      INTEGER(i4) :: jk
+      !----------------------------------------------------------------
+
+      DO jk=SIZE(td_var(:,:,:),DIM=3),1,-1
+         DO jj=SIZE(td_var(:,:,:),DIM=2),1,-1
+            DO ji=SIZE(td_var(:,:,:),DIM=1),1,-1
+               CALL var_clean(td_var(ji,jj,jk))
+            ENDDO
+         ENDDO
+      ENDDO
+
+   END SUBROUTINE var__clean_arr_3D
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure, given variable name.
+   !
+   !> @details
+   !> Optionally you could add 1D,2D,3D or 4D array of value, 
+   !> see var__init_1D_dp, var__init_2D_dp... for more information.
+   !>
+   !> you could also add more information with the following optional arguments:
+   !>   - id_type :  integer(4) variable type, (as defined by NETCDF type constants).
+   !>   - td_dim : array of dimension structure.
+   !>   - td_att  : array of attribute structure.
+   !>   - dd_fill : real(8) variable FillValue. if none NETCDF FillValue will be used.
+   !>   - cd_units : string character of units.
+   !>   - cd_axis : string character of axis expected to be used
+   !>   - cd_stdname : string character of variable standard name.
+   !>   - cd_longname : string character of variable long name.
+   !>   - cd_point : one character for ARAKAWA C-grid point name (T,U,V,F).
+   !>   - id_id : variable id (read from a file).
+   !>   - id_ew : number of point composing east west wrap band.
+   !>   - dd_scf : real(8) value for scale factor attribute.
+   !>   - dd_ofs : real(8) value for add offset attribute.
+   !>   - id_rec : record id (for rstdimg file).
+   !>   - dd_min : real(8) value for minimum value.
+   !>   - dd_max : real(8) value for maximum value.
+   !>   - ld_contiguous : use contiguous storage or not (for netcdf4).
+   !>   - ld_shuffle :  shuffle filter is turned on or not (for netcdf4).
+   !>   - ld_fletcher32 : fletcher32 filter is turned on or not (for netcdf4).
+   !>   - id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use (for netcdf4).
+   !>   - id_chunksz : chunk size (for netcdf4).
+   !>   - cd_interp  : a array of character defining interpolation method.
+   !>   - cd_extrap  : a array of character defining extrapolation method.
+   !>   - cd_filter  : a array of character defining filtering method.
+   !>
+   !>  @note most of these optionals arguments will be inform automatically,
+   !>  when reading variable from a file, or using confiuguration file variable.cfg.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[in] cd_name         variable name
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] dd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle      shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @param[in] cd_interp       interpolation method
+   !> @param[in] cd_extrap       extrapolation method
+   !> @param[in] cd_filter       filter method
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init( cd_name, id_type, td_dim, &
    &                              td_att, dd_fill, cd_units, cd_axis, &
@@ -586,5 +874,5 @@
 
       ! local variable
-      INTEGER(i4) :: il_attid
+      INTEGER(i4) :: il_ind
 
       TYPE(TATT)  :: tl_att
@@ -637,14 +925,24 @@
       ! add _FillValue
       IF( PRESENT(dd_fill) )THEN
-         tl_att=att_init('_FillValue',dd_fill)
+         SELECT CASE( var__init%i_type )
+            CASE(NF90_BYTE)
+               tl_att=att_init('_FillValue', INT(dd_fill,i1) )
+            CASE(NF90_SHORT)
+               tl_att=att_init('_FillValue', INT(dd_fill,i2) )
+            CASE(NF90_INT)
+               tl_att=att_init('_FillValue', INT(dd_fill,i4) )
+            CASE(NF90_FLOAT)
+               tl_att=att_init('_FillValue', INT(dd_fill,sp) )
+            CASE DEFAULT ! NF90_DOUBLE
+                     tl_att=att_init('_FillValue', dd_fill )
+         END SELECT
          CALL var_move_att(var__init, tl_att)
       ELSE
-         il_attid=0
+         il_ind=0
          IF( ASSOCIATED(var__init%t_att) )THEN
-            il_attid=att_get_id(var__init%t_att(:),'_FillValue')
+            il_ind=att_get_index(var__init%t_att(:),'_FillValue')
          ENDIF
-         IF( il_attid == 0 )THEN
+         IF( il_ind == 0 )THEN
             SELECT CASE( var__init%i_type )
-
                CASE(NF90_BYTE)
                   tl_att=att_init('_FillValue',NF90_FILL_BYTE)
@@ -657,5 +955,4 @@
                CASE DEFAULT ! NF90_DOUBLE
                   tl_att=att_init('_FillValue',NF90_FILL_DOUBLE)
-
             END SELECT         
             CALL var_add_att(var__init, tl_att)
@@ -687,4 +984,6 @@
       IF( PRESENT(td_dim) )THEN
          CALL var_add_dim(var__init, td_dim(:))
+      ELSE
+         CALL var_add_dim(var__init, dim_fill_unused())
       ENDIF
 
@@ -703,4 +1002,5 @@
       ENDIF
 
+      ! netcdf4
       IF( PRESENT(ld_contiguous) )THEN
          var__init%l_contiguous=ld_contiguous
@@ -723,12 +1023,15 @@
       ENDIF
 
+      ! interp
       IF( PRESENT(cd_interp) )THEN
          var__init%c_interp(:)=cd_interp(:)
       ENDIF
 
+      !extrap
       IF( PRESENT(cd_extrap) )THEN
          var__init%c_extrap(:)=cd_extrap(:)
       ENDIF
 
+      !filter
       IF( PRESENT(cd_filter) )THEN
          var__init%c_filter(:)=cd_filter(:)
@@ -738,92 +1041,68 @@
       CALL var__get_extra(var__init)
 
-      ! delete some attribute
-      il_attid=att_get_id(var__init%t_att(:),'interpolation')
-      IF( il_attid /= 0 )THEN
-         tl_att=var__init%t_att(il_attid)
-         CALL var_del_att(var__init, tl_att)
-      ENDIF
-      il_attid=att_get_id(var__init%t_att(:),'extrapolation')
-      IF( il_attid /= 0 )THEN
-         tl_att=var__init%t_att(il_attid)
-         CALL var_del_att(var__init, tl_att)
-      ENDIF
-      il_attid=att_get_id(var__init%t_att(:),'filter')
-      IF( il_attid /= 0 )THEN
-         tl_att=var__init%t_att(il_attid)
-         CALL var_del_att(var__init, tl_att)
-      ENDIF
-      il_attid=att_get_id(var__init%t_att(:),'src_file')
-      IF( il_attid /= 0 )THEN
-         tl_att=var__init%t_att(il_attid)
-         CALL var_del_att(var__init, tl_att)
-      ENDIF
-      ! those attribute are deleted cause seems not to be informed correctly
-      il_attid=att_get_id(var__init%t_att(:),'valid_min')
-      IF( il_attid /= 0 )THEN
-         tl_att=var__init%t_att(il_attid)
-         CALL var_del_att(var__init, tl_att)
-      ENDIF
-      il_attid=att_get_id(var__init%t_att(:),'valid_max')
-      IF( il_attid /= 0 )THEN
-         tl_att=var__init%t_att(il_attid)
-         CALL var_del_att(var__init, tl_att)
-      ENDIF
-      il_attid=att_get_id(var__init%t_att(:),'missing_value')
-      IF( il_attid /= 0 )THEN
-         tl_att=var__init%t_att(il_attid)
-         CALL var_del_att(var__init, tl_att)
-      ENDIF
+      ! delete some attribute cause linked to file where variable come from
+      CALL var_del_att(var__init, 'refinment_factor')
+      CALL var_del_att(var__init, 'interpolation')
+      CALL var_del_att(var__init, 'extrapolation')
+      CALL var_del_att(var__init, 'filter')
+      CALL var_del_att(var__init, 'src_file')
+      CALL var_del_att(var__init, 'valid_min')
+      CALL var_del_att(var__init, 'valid_max')
+      CALL var_del_att(var__init, 'missing_value')
+
+      ! clean
+      CALL att_clean(tl_att)
 
    END FUNCTION var__init
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - real(8) 1D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a real(8) 1D array of value.
    !> @details 
+   !> Optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !
    !> Dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('z') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] dd_value : 1D table of real(8) value
-   !> @param[in] id_start : index in the variable from which the data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] dd_value        1D array of real(8) value
+   !> @param[in] id_start        index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] dd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] id_count        number of indices selected along each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] dd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle      shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_1D_dp( cd_name, dd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, dd_fill, cd_units,&
+   &                                    td_att, dd_fill, cd_units, cd_axis, &
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -843,4 +1122,5 @@
       REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -874,5 +1154,5 @@
       CALL var_clean(var__init_1D_dp)
 
-      ! ugly call to avoid warning
+      ! dummy call to avoid warning
       il_type=NF90_DOUBLE
       IF( PRESENT(id_type) ) il_type=id_type
@@ -880,5 +1160,5 @@
       tl_dim(1)=dim_init( 'Z', id_len=SIZE(dd_value(:)) )
       IF( PRESENT(td_dim) )THEN
-         tl_dim(1)=td_dim
+         tl_dim(1)=dim_copy(td_dim)
       ENDIF
 
@@ -895,5 +1175,5 @@
       ! reorder dimension
       CALL dim_reorder(tl_dim(:))
-      ! reorder table
+      ! reorder array
       il_start(:)=dim_reorder_2xyzt(tl_dim(:),il_start(:))
       il_count(:)=dim_reorder_2xyzt(tl_dim(:),il_count(:))
@@ -902,4 +1182,5 @@
       &                          td_dim=tl_dim(:), td_att=td_att,    &
       &                          dd_fill=dd_fill, cd_units=cd_units, &
+      &                          cd_axis=cd_axis,                    &
       &                          cd_stdname=cd_stdname,              &
       &                          cd_longname=cd_longname,            &
@@ -934,58 +1215,63 @@
 
       CALL var_add_value( var__init_1D_dp, dl_value(:,:,:,:), &
-      &                   il_start(:), il_count(:) )
-
+      &                   il_type, il_start(:), il_count(:) )
+
+      ! clean
       DEALLOCATE( dl_value )
+      CALL dim_clean(tl_dim)
 
    END FUNCTION var__init_1D_dp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - real(8) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a real(8) 2D array of value. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
    !
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> array of 2 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] dd_value : 1D table of real(8) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] dd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] dd_value        1D array of real(8) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] dd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle      shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates 
+   !> no deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_2D_dp( cd_name, dd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, dd_fill, cd_units,&
+   &                                    td_att, dd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -1005,4 +1291,5 @@
       REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -1036,5 +1323,5 @@
       CALL var_clean(var__init_2D_dp)
 
-      ! ugly call to avoid warning
+      ! dummy call to avoid warning
       il_type=NF90_DOUBLE
       IF( PRESENT(id_type) ) il_type=id_type
@@ -1047,6 +1334,6 @@
             &                 " not conform")
          ELSE
-            tl_dim(1)=td_dim(1)
-            tl_dim(2)=td_dim(2)
+            tl_dim(1)=dim_copy(td_dim(1))
+            tl_dim(2)=dim_copy(td_dim(2))
          ENDIF
       ENDIF
@@ -1055,5 +1342,5 @@
       IF( PRESENT(id_start) )THEN
          IF( SIZE(id_start(:)) /= 2 )THEN
-            CALL logger_error("VAR INIT: dimension of start table "//&
+            CALL logger_error("VAR INIT: dimension of start array "//&
             &                 " not conform")
          ELSE
@@ -1066,5 +1353,5 @@
       IF( PRESENT(id_count) )THEN
          IF( SIZE(id_count(:)) /= 2 )THEN
-            CALL logger_error("VAR INIT: dimension of count table "//&
+            CALL logger_error("VAR INIT: dimension of count array "//&
             &                 " not conform")
          ELSE
@@ -1076,5 +1363,5 @@
       ! reorder dimension
       CALL dim_reorder(tl_dim(:))
-      ! reorder table
+      ! reorder array
       il_start(:)=dim_reorder_2xyzt(tl_dim(:),il_start(:))
       il_count(:)=dim_reorder_2xyzt(tl_dim(:),il_count(:))
@@ -1083,4 +1370,5 @@
       &                          td_dim=tl_dim(:), td_att=td_att,    &
       &                          dd_fill=dd_fill, cd_units=cd_units, &
+      &                          cd_axis=cd_axis,                    &
       &                          cd_stdname=cd_stdname,              &
       &                          cd_longname=cd_longname,            &
@@ -1119,58 +1407,63 @@
 
       CALL var_add_value( var__init_2D_dp, dl_value(:,:,:,:), &
-      &                   il_start(:), il_count(:) )
-
+      &                   il_type, il_start(:), il_count(:) )
+
+      ! clean
       DEALLOCATE( dl_value )
+      CALL dim_clean(tl_dim)
 
    END FUNCTION var__init_2D_dp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - real(8) 3D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a real(8) 3D array of value.
    !> @details 
-   !> table of 3 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y','z') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 3 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y','z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] dd_value : 1D table of real(8) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] dd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] dd_value        1D array of real(8) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] dd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_3D_dp( cd_name, dd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, dd_fill, cd_units,&
+   &                                    td_att, dd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -1190,4 +1483,5 @@
       REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -1221,5 +1515,5 @@
       CALL var_clean(var__init_3D_dp)
 
-      ! ugly call to avoid warning
+      ! dummy call to avoid warning
       il_type=NF90_DOUBLE
       IF( PRESENT(id_type) ) il_type=id_type
@@ -1233,7 +1527,7 @@
             &                 " not conform")
          ELSE
-            tl_dim(1)=td_dim(1)
-            tl_dim(2)=td_dim(2)
-            tl_dim(3)=td_dim(3)
+            tl_dim(1)=dim_copy(td_dim(1))
+            tl_dim(2)=dim_copy(td_dim(2))
+            tl_dim(3)=dim_copy(td_dim(3))
          ENDIF
       ENDIF
@@ -1242,5 +1536,5 @@
       IF( PRESENT(id_start) )THEN
          IF( SIZE(id_start(:)) /= 3 )THEN
-            CALL logger_error("VAR INIT: dimension of start table "//&
+            CALL logger_error("VAR INIT: dimension of start array "//&
             &                 " not conform")
          ELSE
@@ -1254,5 +1548,5 @@
       IF( PRESENT(id_count) )THEN
          IF( SIZE(id_count(:)) /= 3 )THEN
-            CALL logger_error("VAR INIT: dimension of count table "//&
+            CALL logger_error("VAR INIT: dimension of count array "//&
             &                 " not conform")
          ELSE
@@ -1265,5 +1559,5 @@
       ! reorder dimension
       CALL dim_reorder(tl_dim(:))
-      ! reorder table
+      ! reorder array
       il_start(:)=dim_reorder_2xyzt(tl_dim(:),il_start(:))
       il_count(:)=dim_reorder_2xyzt(tl_dim(:),il_count(:))
@@ -1272,4 +1566,5 @@
       &                          td_dim=tl_dim(:), td_att=td_att,    &
       &                          dd_fill=dd_fill, cd_units=cd_units, &
+      &                          cd_axis=cd_axis,                    &
       &                          cd_stdname=cd_stdname,              &
       &                          cd_longname=cd_longname,            &
@@ -1304,58 +1599,63 @@
 
       CALL var_add_value( var__init_3D_dp, dl_value(:,:,:,:), &
-      &                   il_start(:), il_count(:) )
-
+      &                   il_type, il_start(:), il_count(:) )
+
+      ! clean
       DEALLOCATE( dl_value )
+      CALL dim_clean(tl_dim)
 
    END FUNCTION var__init_3D_dp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - real(8) 4D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a real(8) 4D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> Dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y','z','t') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('x','y','z','t') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] dd_value : 4D table of real(8) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] dd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] dd_value        4D array of real(8) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] dd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_dp( cd_name, dd_value,        &
    &                                 id_start, id_count, id_type, td_dim, &
-   &                                 td_att, dd_fill, cd_units,&
+   &                                 td_att, dd_fill, cd_units, cd_axis,&
    &                                 cd_stdname, cd_longname,  &
    &                                 cd_point, id_id, id_ew,   &
@@ -1375,4 +1675,5 @@
       REAL(dp)        ,                       INTENT(IN), OPTIONAL :: dd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -1404,5 +1705,5 @@
       CALL var_clean(var__init_dp)
 
-      ! ugly call to avoid warning
+      ! dummy call to avoid warning
       il_type=NF90_DOUBLE
       IF( PRESENT(id_type) ) il_type=id_type
@@ -1411,4 +1712,5 @@
       &                       td_dim=td_dim, td_att=td_att,       &
       &                       dd_fill=dd_fill, cd_units=cd_units, &
+      &                       cd_axis=cd_axis,                    &
       &                       cd_stdname=cd_stdname,              &
       &                       cd_longname=cd_longname,            &
@@ -1422,5 +1724,5 @@
       &                       id_deflvl=id_deflvl,                &
       &                       id_chunksz=id_chunksz(:))
-   
+ 
       ! add value
       IF( .NOT. PRESENT(td_dim) )THEN
@@ -1433,56 +1735,62 @@
 
       CALL var_add_value( var__init_dp, dd_value(:,:,:,:), &
-      &                   id_start(:), id_count(:) )
+      &                   il_type, id_start(:), id_count(:) )
+
+      ! clean
+      CALL dim_clean(tl_dim)
 
    END FUNCTION var__init_dp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - real(4) 1D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a real(4) 1D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('z') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] rd_value : 1D table of real(4) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] rd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] rd_value        1D array of real(4) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] rd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_1D_sp( cd_name, rd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, rd_fill, cd_units,&
+   &                                    td_att, rd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -1503,4 +1811,5 @@
       REAL(sp)        ,                       INTENT(IN), OPTIONAL :: rd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -1550,4 +1859,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -1565,53 +1875,56 @@
  
    END FUNCTION var__init_1D_sp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - real(4) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a real(4) 2D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 2 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] rd_value : 2D table of real(4) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] rd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         : variable name
+   !> @param[in] rd_value        : 2D array of real(4) value
+   !> @param[in] id_start        : index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        : number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         : variable type 
+   !> @param[in] td_dim          : array of dimension structure
+   !> @param[in] td_att          : array of attribute structure
+   !> @param[in] rd_fill         : fill value
+   !> @param[in] cd_units        : units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      : variable standard name
+   !> @param[in] cd_longname     : variable long name
+   !> @param[in] cd_point        : point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           : variable id
+   !> @param[in] id_ew           : east west wrap
+   !> @param[in] dd_scf          : scale factor
+   !> @param[in] dd_ofs          : add offset
+   !> @param[in] id_rec          : record id (for rstdimg file)
+   !> @param[in] dd_min          : minimum value
+   !> @param[in] dd_max          : maximum value
+   !> @param[in] ld_contiguous   : use contiguous storage or not 
+   !> @param[in] ld_shuffle      :  shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   : fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       : deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      : chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_2D_sp( cd_name, rd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, rd_fill, cd_units,&
+   &                                    td_att, rd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -1625,6 +1938,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       REAL(sp)        , DIMENSION(:,:)     ,  INTENT(IN) :: rd_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -1632,4 +1945,5 @@
       REAL(sp)        ,                       INTENT(IN), OPTIONAL :: rd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -1681,4 +1995,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -1696,53 +2011,56 @@
       
    END FUNCTION var__init_2D_sp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - real(4) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a real(4) 3D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 3 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y','z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] rd_value : 2D table of real(4) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] rd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         : variable name
+   !> @param[in] rd_value        : 2D array of real(4) value
+   !> @param[in] id_start        : index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        : number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         : variable type 
+   !> @param[in] td_dim          : array of dimension structure
+   !> @param[in] td_att          : array of attribute structure
+   !> @param[in] rd_fill         : fill value
+   !> @param[in] cd_units        : units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      : variable standard name
+   !> @param[in] cd_longname     : variable long name
+   !> @param[in] cd_point        : point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           : variable id
+   !> @param[in] id_ew           : east west wrap
+   !> @param[in] dd_scf          : scale factor
+   !> @param[in] dd_ofs          : add offset
+   !> @param[in] id_rec          : record id (for rstdimg file)
+   !> @param[in] dd_min          : minimum value
+   !> @param[in] dd_max          : maximum value
+   !> @param[in] ld_contiguous   : use contiguous storage or not 
+   !> @param[in] ld_shuffle      :  shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   : fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       : deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      : chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_3D_sp( cd_name, rd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, rd_fill, cd_units,&
+   &                                    td_att, rd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -1756,6 +2074,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       REAL(sp)        , DIMENSION(:,:,:)   ,  INTENT(IN) :: rd_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -1763,4 +2081,5 @@
       REAL(sp)        ,                       INTENT(IN), OPTIONAL :: rd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -1813,4 +2132,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -1828,53 +2148,56 @@
       
    END FUNCTION var__init_3D_sp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - real(4) 4D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a real(4) 4D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> Dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y','z','t') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('x','y','z','t') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] rd_value : 4D table of real(4) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] rd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] rd_value        4D array of real(4) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] rd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle      shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_sp( cd_name, rd_value,        &
    &                                 id_start, id_count, id_type, td_dim, &
-   &                                 td_att, rd_fill, cd_units,&
+   &                                 td_att, rd_fill, cd_units, cd_axis,&
    &                                 cd_stdname, cd_longname,  &
    &                                 cd_point, id_id, id_ew,   &
@@ -1895,4 +2218,5 @@
       REAL(sp)        ,                       INTENT(IN), OPTIONAL :: rd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -1946,4 +2270,5 @@
       &                      dd_fill=dl_fill,                    &
       &                      cd_units=cd_units,                  &
+      &                      cd_axis=cd_axis,                    &
       &                      cd_stdname=cd_stdname,              &
       &                      cd_longname=cd_longname,            &
@@ -1961,53 +2286,56 @@
       
    END FUNCTION var__init_sp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(8) 1D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(8) 1D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('z') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] kd_value : 1D table of integer(8) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] kd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         : variable name
+   !> @param[in] kd_value        : 1D array of integer(8) value
+   !> @param[in] id_start        : index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        : number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         : variable type 
+   !> @param[in] td_dim          : array of dimension structure
+   !> @param[in] td_att          : array of attribute structure
+   !> @param[in] kd_fill         : fill value
+   !> @param[in] cd_units        : units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      : variable standard name
+   !> @param[in] cd_longname     : variable long name
+   !> @param[in] cd_point        : point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           : variable id
+   !> @param[in] id_ew           : east west wrap
+   !> @param[in] dd_scf          : scale factor
+   !> @param[in] dd_ofs          : add offset
+   !> @param[in] id_rec          : record id (for rstdimg file)
+   !> @param[in] dd_min          : minimum value
+   !> @param[in] dd_max          : maximum value
+   !> @param[in] ld_contiguous   : use contiguous storage or not 
+   !> @param[in] ld_shuffle      :  shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   : fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       : deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      : chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_1D_i8( cd_name, kd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, kd_fill, cd_units,&
+   &                                    td_att, kd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -2028,4 +2356,5 @@
       INTEGER(i8)     ,                       INTENT(IN), OPTIONAL :: kd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -2075,4 +2404,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -2090,53 +2420,54 @@
  
    END FUNCTION var__init_1D_i8
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(8) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(8) 2D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 2 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] kd_value : 2D table of integer(8) value
-   !> @param[in] id_start : index in the variable from which the data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] kd_value        2D array of integer(8) value
+   !> @param[in] id_start        index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] kd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] id_count        number of indices selected along each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] kd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_2D_i8( cd_name, kd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, kd_fill, cd_units,&
+   &                                    td_att, kd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -2150,6 +2481,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       INTEGER(i8)     , DIMENSION(:,:)     ,  INTENT(IN) :: kd_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -2157,4 +2488,5 @@
       INTEGER(i8)     ,                       INTENT(IN), OPTIONAL :: kd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -2206,4 +2538,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -2221,53 +2554,56 @@
       
    END FUNCTION var__init_2D_i8
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(8) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(8) 3D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 3 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y','z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] kd_value : 2D table of integer(8) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] kd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] kd_value        2D array of integer(8) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] kd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_3D_i8( cd_name, kd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, kd_fill, cd_units,&
+   &                                    td_att, kd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -2281,6 +2617,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       INTEGER(i8)     , DIMENSION(:,:,:)   ,  INTENT(IN) :: kd_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -2288,4 +2624,5 @@
       INTEGER(i8)     ,                       INTENT(IN), OPTIONAL :: kd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -2338,4 +2675,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -2353,53 +2691,56 @@
       
    END FUNCTION var__init_3D_i8
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(8) 4D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(8) 4D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> Dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y','z','t') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('x','y','z','t') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] kd_value : 4D table of integer(8) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] kd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] kd_value        4D array of integer(8) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] kd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_i8( cd_name, kd_value,        &
    &                                 id_start, id_count, id_type, td_dim, &
-   &                                 td_att, kd_fill, cd_units,&
+   &                                 td_att, kd_fill, cd_units, cd_axis,&
    &                                 cd_stdname, cd_longname,  &
    &                                 cd_point, id_id, id_ew,   &
@@ -2420,4 +2761,5 @@
       INTEGER(i8)     ,                       INTENT(IN), OPTIONAL :: kd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -2471,4 +2813,5 @@
       &                      dd_fill=dl_fill,                    &
       &                      cd_units=cd_units,                  &
+      &                      cd_axis=cd_axis,                    &
       &                      cd_stdname=cd_stdname,              &
       &                      cd_longname=cd_longname,            &
@@ -2486,53 +2829,56 @@
       
    END FUNCTION var__init_i8
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(4) 1D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(4) 1D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('z') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] id_value : 1D table of integer(4) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] id_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] id_value        1D array of integer(4) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] id_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_1D_i4( cd_name, id_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, id_fill, cd_units,&
+   &                                    td_att, id_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -2553,4 +2899,5 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -2600,4 +2947,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -2615,53 +2963,56 @@
  
    END FUNCTION var__init_1D_i4
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(4) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(4) 2D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 2 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] id_value : 2D table of integer(4) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] id_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] id_value        2D array of integer(4) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] id_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_2D_i4( cd_name, id_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, id_fill, cd_units,&
+   &                                    td_att, id_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -2675,6 +3026,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       INTEGER(i4)     , DIMENSION(:,:)     ,  INTENT(IN) :: id_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -2682,4 +3033,5 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -2731,4 +3083,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -2746,53 +3099,56 @@
       
    END FUNCTION var__init_2D_i4
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(4) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(4) 3D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 3 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y','z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] id_value : 2D table of integer(4) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] id_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] id_value        3D array of integer(4) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] id_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_3D_i4( cd_name, id_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, id_fill, cd_units,&
+   &                                    td_att, id_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -2806,6 +3162,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       INTEGER(i4)     , DIMENSION(:,:,:)   ,  INTENT(IN) :: id_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -2813,4 +3169,5 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -2863,4 +3220,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -2878,53 +3236,56 @@
       
    END FUNCTION var__init_3D_i4
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(4) 4D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(4) 4D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> Dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y','z','t') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('x','y','z','t') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] id_value : 4D table of integer(4) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] id_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] id_value        4D array of integer(4) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] id_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_i4( cd_name, id_value,        &
    &                                 id_start, id_count, id_type, td_dim, &
-   &                                 td_att, id_fill, cd_units,&
+   &                                 td_att, id_fill, cd_units, cd_axis,&
    &                                 cd_stdname, cd_longname,  &
    &                                 cd_point, id_id, id_ew,   &
@@ -2945,4 +3306,5 @@
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -2996,4 +3358,5 @@
       &                      dd_fill=dl_fill,                    &
       &                      cd_units=cd_units,                  &
+      &                      cd_axis=cd_axis,                    &
       &                      cd_stdname=cd_stdname,              &
       &                      cd_longname=cd_longname,            &
@@ -3010,65 +3373,57 @@
       DEALLOCATE( dl_value )
       
-!      ! add value
-!      IF( .NOT. PRESENT(td_dim) )THEN
-!         il_shape(:)=SHAPE(id_value(:,:,:,:)) 
-!         DO ji=1,ip_maxdim
-!            tl_dim=dim_init( cp_dimorder(ji:ji), id_len=il_shape(ji)) 
-!            CALL var_add_dim(var__init_i4, tl_dim)
-!         ENDDO
-!      ENDIF
-!      CALL var_add_value(var__init_i4, id_value(:,:,:,:), &
-!      &                  id_start(:), id_count(:))
-      
    END FUNCTION var__init_i4
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(2) 1D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(2) 1D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('z') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] sd_value : 1D table of integer(2) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] sd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] sd_value        1D array of integer(2) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] sd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_1D_i2( cd_name, sd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, sd_fill, cd_units,&
+   &                                    td_att, sd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -3089,4 +3444,5 @@
       INTEGER(i2)     ,                       INTENT(IN), OPTIONAL :: sd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -3136,4 +3492,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -3151,53 +3508,56 @@
  
    END FUNCTION var__init_1D_i2
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(2) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(2) 2D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 2 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] sd_value : 2D table of integer(2) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] sd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] sd_value        2D array of integer(2) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] sd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_2D_i2( cd_name, sd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, sd_fill, cd_units,&
+   &                                    td_att, sd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -3211,6 +3571,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       INTEGER(i2)     , DIMENSION(:,:)     ,  INTENT(IN) :: sd_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -3218,4 +3578,5 @@
       INTEGER(i2)     ,                       INTENT(IN), OPTIONAL :: sd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -3267,4 +3628,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -3282,53 +3644,56 @@
       
    END FUNCTION var__init_2D_i2
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(2) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(2) 3D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 3 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y','z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] sd_value : 2D table of integer(2) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] sd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] sd_value        3D array of integer(2) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] sd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_3D_i2( cd_name, sd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, sd_fill, cd_units,&
+   &                                    td_att, sd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -3342,6 +3707,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       INTEGER(i2)     , DIMENSION(:,:,:)   ,  INTENT(IN) :: sd_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -3349,4 +3714,5 @@
       INTEGER(i2)     ,                       INTENT(IN), OPTIONAL :: sd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -3399,4 +3765,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -3414,53 +3781,56 @@
       
    END FUNCTION var__init_3D_i2
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(2) 4D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(2) 4D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> Dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y','z','t') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('x','y','z','t') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] sd_value : 4D table of integer(2) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] sd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] sd_value        4D array of integer(2) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] sd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_i2( cd_name, sd_value,        &
    &                                 id_start, id_count, id_type, td_dim, &
-   &                                 td_att, sd_fill, cd_units,&
+   &                                 td_att, sd_fill, cd_units, cd_axis,&
    &                                 cd_stdname, cd_longname,  &
    &                                 cd_point, id_id, id_ew,   &
@@ -3481,4 +3851,5 @@
       INTEGER(i2)     ,                       INTENT(IN), OPTIONAL :: sd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -3532,4 +3903,5 @@
       &                      dd_fill=dl_fill,                    &
       &                      cd_units=cd_units,                  &
+      &                      cd_axis=cd_axis,                    &
       &                      cd_stdname=cd_stdname,              &
       &                      cd_longname=cd_longname,            &
@@ -3546,65 +3918,57 @@
       DEALLOCATE( dl_value )
       
-!      ! add value
-!      IF( .NOT. PRESENT(td_dim) )THEN
-!         il_shape(:)=SHAPE(sd_value(:,:,:,:)) 
-!         DO ji=1,ip_maxdim
-!            tl_dim=dim_init( cp_dimorder(ji:ji), id_len=il_shape(ji)) 
-!            CALL var_add_dim(var__init_i2, tl_dim)
-!         ENDDO
-!      ENDIF
-!      CALL var_add_value(var__init_i2, sd_value(:,:,:,:), &
-!      &                  id_start(:), id_count(:))
-      
    END FUNCTION var__init_i2
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(1) 1D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(1) 1D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('z') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] bd_value : 1D table of integer(1) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] bd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] bd_value        1D array of integer(1) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] bd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_1D_i1( cd_name, bd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, bd_fill, cd_units,&
+   &                                    td_att, bd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -3625,4 +3989,5 @@
       INTEGER(i1)     ,                       INTENT(IN), OPTIONAL :: bd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -3672,4 +4037,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -3687,53 +4053,56 @@
  
    END FUNCTION var__init_1D_i1
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(1) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(1) 2D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 2 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] bd_value : 2D table of integer(1) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] bd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] bd_value        2D array of integer(1) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] bd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_2D_i1( cd_name, bd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, bd_fill, cd_units,&
+   &                                    td_att, bd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -3747,6 +4116,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       INTEGER(i1)     , DIMENSION(:,:)     ,  INTENT(IN) :: bd_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -3754,4 +4123,5 @@
       INTEGER(i1)     ,                       INTENT(IN), OPTIONAL :: bd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -3803,4 +4173,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -3818,53 +4189,56 @@
       
    END FUNCTION var__init_2D_i1
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(1) 2D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(1) 3D array of value.
    !> @details 
-   !> table of 2 dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y') and we 
-   !> use table size as lentgh dimension. 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
+   !> array of 3 dimension structure is needed to put value in variable structure. 
+   !> If none is given, we assume array is ordered as ('x','y','z') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
+   !> start and count array are given. Dimension structure is needed in that 
    !> case.    
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] bd_value : 2D table of integer(1) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] bd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] bd_value        3D array of integer(1) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] bd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_3D_i1( cd_name, bd_value,        &
    &                                    id_start, id_count, id_type, td_dim, &
-   &                                    td_att, bd_fill, cd_units,&
+   &                                    td_att, bd_fill, cd_units, cd_axis,&
    &                                    cd_stdname, cd_longname,  &
    &                                    cd_point, id_id, id_ew,   &
@@ -3878,6 +4252,6 @@
       CHARACTER(LEN=*),                       INTENT(IN) :: cd_name
       INTEGER(i1)     , DIMENSION(:,:,:)   ,  INTENT(IN) :: bd_value
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_start
-      INTEGER(i4)     , DIMENSION(:)       , INTENT(IN), OPTIONAL :: id_count
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_start
+      INTEGER(i4)     , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: id_count
       INTEGER(i4)     ,                       INTENT(IN), OPTIONAL :: id_type 
       TYPE(TDIM)      , DIMENSION(:)       ,  INTENT(IN), OPTIONAL :: td_dim
@@ -3885,4 +4259,5 @@
       INTEGER(i1)     ,                       INTENT(IN), OPTIONAL :: bd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -3935,4 +4310,5 @@
       &                         dd_fill=dl_fill,                    &
       &                         cd_units=cd_units,                  &
+      &                         cd_axis=cd_axis,                    &
       &                         cd_stdname=cd_stdname,              &
       &                         cd_longname=cd_longname,            &
@@ -3950,53 +4326,56 @@
       
    END FUNCTION var__init_3D_i1
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function initalise a variable structure.
-   !> - integer(1) 4D table of value could be added. 
-   !> - dimension structure could be added.
-   !> - attribute structure could be added
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function initialize a variable structure,
+   !> with a integer(1) 4D array of value.
    !> @details 
+   !> optionally could be added:<br/>
+   !> - dimension structure.
+   !> - attribute structure.
+   !>
    !> Dimension structure is needed to put value in variable structure. 
-   !> If none is given, we assume table is ordered as ('x','y','z','t') and we 
-   !> use table size as lentgh dimension. 
+   !> If none is given, we assume array is ordered as ('x','y','z','t') and we 
+   !> use array size as lentgh dimension. 
    !>
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. Dimension structure is needed in that 
-   !> case.    
+   !> start and count array are given. Dimension structure is needed in that 
+   !> case. 
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_name : variable name
-   !> @param[in] bd_value : 4D table of integer(1) value
-   !> @param[in] id_start : index in the variable from which the data values 
-   !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !> @param[in] id_type : variable type 
-   !> @param[in] td_dim   : table of dimension structure
-   !> @param[in] td_att  : table of attribute structure
-   !> @param[in] bd_fill : fill value
-   !> @param[in] cd_units : units
-   !> @param[in] cd_stdname : variable standard name
-   !> @param[in] cd_longname : variable long name
-   !> @param[in] cd_point : point on Arakawa-C grid (T,U,V,F)
-   !> @param[in] id_id : variable id
-   !> @param[in] id_ew : east west wrap
-   !> @param[in] dd_scf  : scale factor
-   !> @param[in] dd_ofs  : add offset
-   !> @param[in] id_rec : record id (for rstdimg file)
-   !> @param[in] dd_min : minimum value
-   !> @param[in] dd_max : maximum value
-   !> @param[in] ld_contiguous : use contiguous storage or not 
-   !> @param[in] ld_shuffle :  shuffle filter is turned on or not
-   !> @param[in] ld_fletcher32 : fletcher32 filter is turned on or not
-   !> @param[in] id_deflvl : deflate level from 0 to 9, 0 indicates no deflation is in use
-   !> @param[in] id_chunksz : chunk size
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name         variable name
+   !> @param[in] bd_value        4D array of integer(1) value
+   !> @param[in] id_start        index in the variable from which the 
+   !> data values will be read
+   !> @param[in] id_count        number of indices selected along 
+   !> each dimension
+   !> @param[in] id_type         variable type 
+   !> @param[in] td_dim          array of dimension structure
+   !> @param[in] td_att          array of attribute structure
+   !> @param[in] bd_fill         fill value
+   !> @param[in] cd_units        units
+   !> @param[in] cd_axis         axis expected to be used
+   !> @param[in] cd_stdname      variable standard name
+   !> @param[in] cd_longname     variable long name
+   !> @param[in] cd_point        point on Arakawa-C grid (T,U,V,F)
+   !> @param[in] id_id           variable id
+   !> @param[in] id_ew           east west wrap
+   !> @param[in] dd_scf          scale factor
+   !> @param[in] dd_ofs          add offset
+   !> @param[in] id_rec          record id (for rstdimg file)
+   !> @param[in] dd_min          minimum value
+   !> @param[in] dd_max          maximum value
+   !> @param[in] ld_contiguous   use contiguous storage or not 
+   !> @param[in] ld_shuffle       shuffle filter is turned on or not
+   !> @param[in] ld_fletcher32   fletcher32 filter is turned on or not
+   !> @param[in] id_deflvl       deflate level from 0 to 9, 0 indicates no 
+   !> deflation is in use
+   !> @param[in] id_chunksz      chunk size
+   !> @return variable structure
+   !-------------------------------------------------------------------
    TYPE(TVAR) FUNCTION var__init_i1( cd_name, bd_value,        &
    &                                 id_start, id_count, id_type, td_dim, &
-   &                                 td_att, bd_fill, cd_units,&
+   &                                 td_att, bd_fill, cd_units, cd_axis,&
    &                                 cd_stdname, cd_longname,  &
    &                                 cd_point, id_id, id_ew,   &
@@ -4017,4 +4396,5 @@
       INTEGER(i1)     ,                       INTENT(IN), OPTIONAL :: bd_fill
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_units
+      CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_axis 
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_stdname
       CHARACTER(LEN=*),                       INTENT(IN), OPTIONAL :: cd_longname
@@ -4068,4 +4448,5 @@
       &                      dd_fill=dl_fill,                    &
       &                      cd_units=cd_units,                  &
+      &                      cd_axis=cd_axis,                    &
       &                      cd_stdname=cd_stdname,              &
       &                      cd_longname=cd_longname,            &
@@ -4082,17 +4463,5 @@
       DEALLOCATE( dl_value )
       
-!      ! add value
-!      IF( .NOT. PRESENT(td_dim) )THEN
-!         il_shape(:)=SHAPE(bd_value(:,:,:,:)) 
-!         DO ji=1,ip_maxdim
-!            tl_dim=dim_init( cp_dimorder(ji:ji), id_len=il_shape(ji)) 
-!            CALL var_add_dim(var__init_i1, tl_dim)
-!         ENDDO
-!      ENDIF
-!      CALL var_add_value(var__init_i1, bd_value(:,:,:,:), &
-!      &                  id_start(:), id_count(:))
-      
    END FUNCTION var__init_i1
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief  This function concatenate variable value following DIM direction.
@@ -4101,14 +4470,14 @@
    !> By default variable are concatenate following time dimension. To
    !> concatenate following another dimension, specify DIM=x where x is the
-   !> dimension number (1,2,3,4) 
+   !> dimension number (jp_I, jp_J,jp_K, jp_L). 
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var1 : variable structure
-   !> @param[in] td_var2 : variable structure
-   !> @param[in] DIM : dimension following which concatenate  
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var1   variable structure
+   !> @param[in] td_var2   variable structure
+   !> @param[in] DIM       dimension following which concatenate
+   !> @return variable structure
+   !-------------------------------------------------------------------
    FUNCTION var_concat(td_var1, td_var2, DIM)
       IMPLICIT NONE
@@ -4125,5 +4494,5 @@
       !----------------------------------------------------------------
       il_dim=4
-      IF( PRESENT(DIM) )il_dim=DIM
+      IF( PRESENT(DIM) ) il_dim=DIM
 
       IF( .NOT. ASSOCIATED(td_var1%d_value) )THEN
@@ -4138,28 +4507,26 @@
          ! check other dimension
          SELECT CASE(il_dim)
-         CASE(1)
+         CASE(jp_I)
             var_concat=var__concat_i(td_var1, td_var2)
-         CASE(2)
+         CASE(jp_J)
             var_concat=var__concat_j(td_var1, td_var2)
-         CASE(3)
+         CASE(jp_K)
             var_concat=var__concat_k(td_var1, td_var2)
-         CASE(4)
+         CASE(jp_L)
             var_concat=var__concat_l(td_var1, td_var2)
          END SELECT
-
       ENDIF
 
    END FUNCTION var_concat
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief  This function concatenate variable value following i-direction.
    !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var1 : variable structure
-   !> @param[in] td_var2 : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var1   variable structure
+   !> @param[in] td_var2   variable structure
+   !> @return variable structure
+   !-------------------------------------------------------------------
    FUNCTION var__concat_i(td_var1, td_var2)
       IMPLICIT NONE
@@ -4176,6 +4543,9 @@
 
       !----------------------------------------------------------------
-      IF( ANY(td_var1%t_dim(2:4)%i_len /=  td_var2%t_dim(2:4)%i_len) )THEN
-         CALL logger_error("VAR CONCAT: dimension not conform")
+      IF( .NOT. td_var1%t_dim(1)%l_use .OR. &
+      &   .NOT. td_var1%t_dim(1)%l_use )THEN
+         CALL logger_error("VAR CONCAT: can not concatenate variable "//&
+         &  TRIM(td_var1%c_name)//" on an unused dimension I")
+      ELSEIF( ANY(td_var1%t_dim(2:4)%i_len /=  td_var2%t_dim(2:4)%i_len) )THEN
 
          cl_tmp='('//":"//","//&
@@ -4191,6 +4561,8 @@
          CALL logger_debug("VAR CONCAT: second variable dimensions "//&
          &  TRIM(cl_tmp) )
+
+         CALL logger_error("VAR CONCAT: dimension not conform")
       ELSE
-         tl_var=td_var1
+         tl_var=var_copy(td_var1)
 
          DEALLOCATE(tl_var%d_value)
@@ -4212,21 +4584,21 @@
 
          ! save result
-         var__concat_i=tl_var
-
+         var__concat_i=var_copy(tl_var)
+
+         ! clean
          CALL var_clean(tl_var)
       ENDIF
 
    END FUNCTION var__concat_i
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief  This function concatenate variable value following j-direction.
    !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var1 : variable structure
-   !> @param[in] td_var2 : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var1   variable structure
+   !> @param[in] td_var2   variable structure
+   !> @return variable structure
+   !-------------------------------------------------------------------
    FUNCTION var__concat_j(td_var1, td_var2)
       IMPLICIT NONE
@@ -4243,7 +4615,10 @@
 
       !----------------------------------------------------------------
-      IF(     td_var1%t_dim(1)%i_len   /=  td_var2%t_dim(1)%i_len  .OR. &
+      IF( .NOT. td_var1%t_dim(2)%l_use .OR. &
+      &   .NOT. td_var1%t_dim(2)%l_use )THEN
+         CALL logger_error("VAR CONCAT: can not concatenate variable "//&
+         &  TRIM(td_var1%c_name)//" on an unused dimension J")      
+      ELSEIF(     td_var1%t_dim(1)%i_len   /=  td_var2%t_dim(1)%i_len  .OR. &
       &   ANY(td_var1%t_dim(3:4)%i_len /=  td_var2%t_dim(3:4)%i_len) )THEN
-         CALL logger_error("VAR CONCAT: dimension not conform")
 
          cl_tmp='('//&
@@ -4261,6 +4636,8 @@
          CALL logger_debug("VAR CONCAT: second variable dimensions "//&
          &  TRIM(cl_tmp) )
+
+         CALL logger_error("VAR CONCAT: dimension not conform")
       ELSE
-         tl_var=td_var1
+         tl_var=var_copy(td_var1)
 
          DEALLOCATE(tl_var%d_value)
@@ -4282,21 +4659,21 @@
 
          ! save result
-         var__concat_j=tl_var
-
+         var__concat_j=var_copy(tl_var)
+
+         ! clean
          CALL var_clean(tl_var)
       ENDIF
 
    END FUNCTION var__concat_j
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief  This function concatenate variable value following k-direction.
    !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var1 : variable structure
-   !> @param[in] td_var2 : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var1   variable structure
+   !> @param[in] td_var2   variable structure
+   !> @return variable structure
+   !-------------------------------------------------------------------
    FUNCTION var__concat_k(td_var1, td_var2)
       IMPLICIT NONE
@@ -4313,7 +4690,10 @@
 
       !----------------------------------------------------------------
-      IF(     td_var1%t_dim(4)%i_len   /=  td_var2%t_dim(4)%i_len  .OR. &
+      IF( .NOT. td_var1%t_dim(3)%l_use .OR. &
+      &   .NOT. td_var1%t_dim(3)%l_use )THEN
+         CALL logger_error("VAR CONCAT: can not concatenate variable "//&
+         &  TRIM(td_var1%c_name)//" on an unused dimension K")      
+      ELSEIF(     td_var1%t_dim(4)%i_len   /=  td_var2%t_dim(4)%i_len  .OR. &
       &   ANY(td_var1%t_dim(1:2)%i_len /=  td_var2%t_dim(1:2)%i_len) )THEN
-         CALL logger_error("VAR CONCAT: dimension not conform")
 
          cl_tmp='('//&
@@ -4331,6 +4711,8 @@
          CALL logger_debug("VAR CONCAT: second variable dimensions "//&
          &  TRIM(cl_tmp) )
+
+         CALL logger_error("VAR CONCAT: dimension not conform")
       ELSE
-         tl_var=td_var1
+         tl_var=var_copy(td_var1)
 
          DEALLOCATE(tl_var%d_value)
@@ -4352,21 +4734,21 @@
 
          ! save result
-         var__concat_k=tl_var
-
+         var__concat_k=var_copy(tl_var)
+
+         ! clean
          CALL var_clean(tl_var)
       ENDIF
 
    END FUNCTION var__concat_k
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief  This function concatenate variable value following l-direction.
    !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var1 : variable structure
-   !> @param[in] td_var2 : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var1   variable structure
+   !> @param[in] td_var2   variable structure
+   !> @return variable structure
+   !-------------------------------------------------------------------
    FUNCTION var__concat_l(td_var1, td_var2)
       IMPLICIT NONE
@@ -4383,6 +4765,9 @@
 
       !----------------------------------------------------------------
-      IF( ANY(td_var1%t_dim(1:3)%i_len /=  td_var2%t_dim(1:3)%i_len) )THEN
-         CALL logger_error("VAR CONCAT: dimension not conform")
+      IF( .NOT. td_var1%t_dim(4)%l_use .OR. &
+      &   .NOT. td_var1%t_dim(4)%l_use )THEN
+         CALL logger_error("VAR CONCAT: can not concatenate variable "//&
+         &  TRIM(td_var1%c_name)//" on an unused dimension L")      
+      ELSEIF( ANY(td_var1%t_dim(1:3)%i_len /=  td_var2%t_dim(1:3)%i_len) )THEN
 
          cl_tmp='('//&
@@ -4400,6 +4785,8 @@
          CALL logger_debug("VAR CONCAT: second variable dimensions "//&
          &  TRIM(cl_tmp) )
+
+         CALL logger_error("VAR CONCAT: dimension not conform")
       ELSE
-         tl_var=td_var1
+         tl_var=var_copy(td_var1)
 
          DEALLOCATE(tl_var%d_value)
@@ -4421,23 +4808,22 @@
 
          ! save result
-         var__concat_l=tl_var
-
+         var__concat_l=var_copy(tl_var)
+
+         ! clean
          CALL var_clean(tl_var)
       ENDIF
 
    END FUNCTION var__concat_l
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a table of attribute structure 
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add an array of attribute structure 
    !> in a variable structure.
-   !
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_att : table of attribute structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_att_tab(td_var, td_att)
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_att    array of attribute structure
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_att_arr(td_var, td_att)
       IMPLICIT NONE
       ! Argument      
@@ -4458,19 +4844,15 @@
       ENDDO
 
-   END SUBROUTINE var__add_att_tab
-   !> @endcode   
+   END SUBROUTINE var__add_att_arr
    !-------------------------------------------------------------------
    !> @brief This subroutine add an attribute structure 
    !> in a variable structure.
    !
-   !> @details
-   !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_att : attribute structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_att    attribute structure
+   !-------------------------------------------------------------------
    SUBROUTINE var__add_att_unit(td_var, td_att)
       IMPLICIT NONE
@@ -4481,5 +4863,5 @@
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_attid
+      INTEGER(i4) :: il_ind
       TYPE(TATT), DIMENSION(:), ALLOCATABLE :: tl_att
 
@@ -4489,24 +4871,24 @@
 
       ! check if attribute already in variable structure
-      il_attid=0
+      il_ind=0
       IF( ASSOCIATED(td_var%t_att) )THEN
-         il_attid=att_get_id( td_var%t_att(:), td_att%c_name )
-      ENDIF
-
-      IF( il_attid /= 0 )THEN
+         il_ind=att_get_index( td_var%t_att(:), td_att%c_name )
+      ENDIF
+
+      IF( il_ind /= 0 )THEN
 
          CALL logger_error( &
-         &  " ADD ATT: attribute "//TRIM(td_att%c_name)//&
+         &  " VAR ADD ATT: attribute "//TRIM(td_att%c_name)//&
          &  ", already in variable "//TRIM(td_var%c_name) )
 
          DO ji=1,td_var%i_natt
             CALL logger_debug( &
-            &  " ADD ATT: in variable "//TRIM(td_var%t_att(ji)%c_name) )
+            &  " VAR ADD ATT: in variable "//TRIM(td_var%t_att(ji)%c_name) )
          ENDDO
 
       ELSE
          
-         CALL logger_debug( &
-         &  " ADD ATT: add attribute "//TRIM(td_att%c_name)//&
+         CALL logger_trace( &
+         &  " VAR ADD ATT: add attribute "//TRIM(td_att%c_name)//&
          &  ", in variable "//TRIM(td_var%c_name) )
 
@@ -4517,5 +4899,5 @@
 
                CALL logger_error( &
-               &  " ADD ATT: not enough space to put attributes from "//&
+               &  " VAR ADD ATT: not enough space to put attributes from "//&
                &  TRIM(td_var%c_name)//" in temporary attribute structure")
 
@@ -4523,6 +4905,7 @@
 
                ! save temporary global attribute's variable structure
-               tl_att(:)=td_var%t_att(:)
-
+               tl_att(:)=att_copy(td_var%t_att(:))
+
+               CALL att_clean(td_var%t_att(:))
                DEALLOCATE( td_var%t_att )
                ALLOCATE( td_var%t_att(td_var%i_natt+1), stat=il_status )
@@ -4530,5 +4913,5 @@
 
                   CALL logger_error( &
-                  &  " ADD ATT: not enough space to put attributes "//&
+                  &  " VAR ADD ATT: not enough space to put attributes "//&
                   &  "in variable structure "//TRIM(td_var%c_name) )
 
@@ -4536,6 +4919,8 @@
 
                ! copy attribute in variable before
-               td_var%t_att(1:td_var%i_natt)=tl_att(:)
-
+               td_var%t_att(1:td_var%i_natt)=att_copy(tl_att(:))
+
+               ! clean
+               CALL att_clean(tl_att(:))
                DEALLOCATE(tl_att)
                
@@ -4544,4 +4929,5 @@
          ! no attribute in variable structure
             IF( ASSOCIATED(td_var%t_att) )THEN
+               CALL att_clean(td_var%t_att(:))
                DEALLOCATE(td_var%t_att)
             ENDIF
@@ -4550,5 +4936,5 @@
 
                CALL logger_error( &
-               &  " ADD ATT: not enough space to put attributes "//&
+               &  " VAR ADD ATT: not enough space to put attributes "//&
                &  "in variable structure "//TRIM(td_var%c_name) )
 
@@ -4558,11 +4944,9 @@
          td_var%i_natt=td_var%i_natt+1
 
-         ! add new attributes
-         td_var%t_att(td_var%i_natt)=td_att
-
-         ! change attribute id
-         DO ji=1,td_var%i_natt
-            td_var%t_att(ji)%i_id=ji
-         ENDDO
+         ! add new attribute
+         td_var%t_att(td_var%i_natt)=att_copy(td_att)
+
+         !! add new attribute id
+         !td_var%t_att(td_var%i_natt)%i_id=att_get_unit(td_var%t_att(:))
 
          ! highlight some attribute
@@ -4577,8 +4961,14 @@
                CASE("_FillValue")
                   td_var%d_fill = td_var%t_att(td_var%i_natt)%d_value(1)
+               CASE("ew_overlap")
+                  td_var%i_ew = INT(td_var%t_att(td_var%i_natt)%d_value(1),i4) 
                CASE("standard_name")
                   td_var%c_stdname = TRIM(td_var%t_att(td_var%i_natt)%c_value)
+               CASE("long_name")
+                  td_var%c_longname = TRIM(td_var%t_att(td_var%i_natt)%c_value)
                CASE("units")
                   td_var%c_units = TRIM(td_var%t_att(td_var%i_natt)%c_value)
+               CASE("grid_point")
+                  td_var%c_point = TRIM(td_var%t_att(td_var%i_natt)%c_value)
 
             END SELECT
@@ -4587,19 +4977,56 @@
 
    END SUBROUTINE var__add_att_unit
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine delete an attribute 
    !> from variable structure.
    !
-   !> @details
-   !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_att : attribute structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var_del_att(td_var, td_att)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] cd_name   attribute name
+   !-------------------------------------------------------------------
+   SUBROUTINE var__del_att_name(td_var, cd_name)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TVAR)      , INTENT(INOUT) :: td_var
+      CHARACTER(LEN=*), INTENT(IN   ) :: cd_name
+
+      ! local variable
+      INTEGER(i4) :: il_ind
+
+      ! loop indices
+      !----------------------------------------------------------------
+
+      ! check if attribute already in variable structure
+      il_ind=0
+      IF( ASSOCIATED(td_var%t_att) )THEN
+         il_ind=att_get_index( td_var%t_att(:), TRIM(cd_name) )
+      ENDIF
+
+      IF( il_ind == 0 )THEN
+
+         CALL logger_warn( &
+         &  " VAR DEL ATT: no attribute "//TRIM(cd_name)//&
+         &  ", in variable "//TRIM(td_var%c_name) )
+
+      ELSE
+         
+         CALL var_del_att(td_var, td_var%t_att(il_ind))
+
+      ENDIF
+
+   END SUBROUTINE var__del_att_name
+   !-------------------------------------------------------------------
+   !> @brief This subroutine delete an attribute 
+   !> from variable structure.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_att    attribute structure
+   !-------------------------------------------------------------------
+   SUBROUTINE var__del_att_str(td_var, td_att)
       IMPLICIT NONE
       ! Argument      
@@ -4609,31 +5036,32 @@
       ! local variable
       INTEGER(i4) :: il_status
-      INTEGER(i4) :: il_attid
+      INTEGER(i4) :: il_ind
       TYPE(TATT), DIMENSION(:), ALLOCATABLE :: tl_att
 
       ! loop indices
-      INTEGER(i4) :: ji
+      !INTEGER(i4) :: ji
       !----------------------------------------------------------------
 
       ! check if attribute already in variable structure
-      il_attid=0
+      il_ind=0
       IF( ASSOCIATED(td_var%t_att) )THEN
-         il_attid=att_get_id( td_var%t_att(:), td_att%c_name )
-      ENDIF
-
-      IF( il_attid == 0 )THEN
+         il_ind=att_get_index( td_var%t_att(:), td_att%c_name )
+      ENDIF
+
+      IF( il_ind == 0 )THEN
 
          CALL logger_warn( &
-         &  " DEL ATT: no attribute "//TRIM(td_att%c_name)//&
+         &  " VAR DEL ATT: no attribute "//TRIM(td_att%c_name)//&
          &  ", in variable "//TRIM(td_var%c_name) )
 
       ELSE
          
-         CALL logger_debug( &
-         &  " DEL ATT: del attribute "//TRIM(td_att%c_name)//&
+         CALL logger_trace( &
+         &  " VAR DEL ATT: del attribute "//TRIM(td_att%c_name)//&
          &  ", in var "//TRIM(td_var%c_name) )
 
          IF( td_var%i_natt == 1 )THEN
 
+            CALL att_clean(td_var%t_att(:))
             DEALLOCATE(td_var%t_att)
 
@@ -4646,5 +5074,5 @@
 
                CALL logger_error( &
-               &  " ADD ATT: not enough space to put attributes from "//&
+               &  " VAR ADD ATT: not enough space to put attributes from "//&
                &  TRIM(td_var%c_name)//" in temporary attribute structure")
 
@@ -4652,9 +5080,10 @@
 
                ! save temporary global attribute's variable structure
-               tl_att(1:il_attid-1)=td_var%t_att(1:il_attid-1)
-               IF( il_attid < td_var%i_natt )THEN
-                  tl_att(il_attid:)=td_var%t_att(il_attid+1:)
+               tl_att(1:il_ind-1)=att_copy(td_var%t_att(1:il_ind-1))
+               IF( il_ind < td_var%i_natt )THEN
+                  tl_att(il_ind:)=att_copy(td_var%t_att(il_ind+1:))
                ENDIF
 
+               CALL att_clean(td_var%t_att(:))
                DEALLOCATE( td_var%t_att )
 
@@ -4666,5 +5095,5 @@
 
                   CALL logger_error( &
-                  &  " ADD ATT: not enough space to put attributes "//&
+                  &  " VAR ADD ATT: not enough space to put attributes "//&
                   &  "in variable structure "//TRIM(td_var%c_name) )
 
@@ -4672,11 +5101,13 @@
 
                ! copy attribute in variable before
-               td_var%t_att(1:td_var%i_natt)=tl_att(:)
-
-               ! change attribute id
-               DO ji=1,td_var%i_natt
-                  td_var%t_att(ji)%i_id=ji
-               ENDDO
-
+               td_var%t_att(1:td_var%i_natt)=att_copy(tl_att(:))
+
+               !! change attribute id
+               !DO ji=1,td_var%i_natt
+               !   td_var%t_att(ji)%i_id=ji
+               !ENDDO
+
+               ! clean
+               CALL att_clean(tl_att(:))
                DEALLOCATE(tl_att)
             ENDIF 
@@ -4684,20 +5115,15 @@
       ENDIF
 
-   END SUBROUTINE var_del_att
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine move a global attribute structure 
+   END SUBROUTINE var__del_att_str
+   !-------------------------------------------------------------------
+   !> @brief This subroutine move an attribute structure 
    !> from variable structure.
    !
-   !> @details
-   !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_att : attribute structure
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_att    attribute structure
+   !-------------------------------------------------------------------
    SUBROUTINE var_move_att(td_var, td_att)
       IMPLICIT NONE
@@ -4711,5 +5137,5 @@
       !----------------------------------------------------------------
       ! copy attribute
-      tl_att=td_att
+      tl_att=att_copy(td_att)
 
       ! remove attribute with same name
@@ -4719,8 +5145,10 @@
       CALL var_add_att(td_var, tl_att)
 
+      ! clean
+      CALL att_clean(tl_att)
+
    END SUBROUTINE var_move_att
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a table of dimension structure in a variable 
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add an array of dimension structure in a variable 
    !> structure.
    !> - number of dimension in variable can't be greater than 4
@@ -4728,13 +5156,10 @@
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dim : dimension structure
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_dim_tab(td_var, td_dim)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dim    dimension structure
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_dim_arr(td_var, td_dim)
       IMPLICIT NONE
       ! Argument      
@@ -4749,5 +5174,5 @@
       !----------------------------------------------------------------
       il_ndim=SIZE(td_dim(:))
-      IF( il_ndim <= 4 )THEN
+      IF( il_ndim <= ip_maxdim )THEN
 
          DO ji=1,il_ndim
@@ -4757,85 +5182,191 @@
       ELSE
          CALL logger_error( &
-         &  " ADD DIM: too much dimension to put in structure "//&
+         &  " VAR ADD DIM: too much dimension to put in structure "//&
          &  "("//TRIM(fct_str(il_ndim))//")" )
       ENDIF
 
-   END SUBROUTINE var__add_dim_tab
-   !> @endcode   
+   END SUBROUTINE var__add_dim_arr
    !-------------------------------------------------------------------
    !> @brief This subroutine add one dimension in a variable 
-   !> structure, after some check.
+   !> structure.
+   !> @details
    !> - number of dimension in variable can't be greater than 4
    !> - dimension can't be already uses in variable structure 
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dim : dimension structure
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_dim_unit(td_var, td_dim)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dim    dimension structure
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_dim_unit(td_var, td_dim) 
       IMPLICIT NONE
       ! Argument      
-      TYPE(TVAR), INTENT(INOUT) :: td_var
-      TYPE(TDIM), INTENT(IN) :: td_dim
+      TYPE(TVAR)      , INTENT(INOUT) :: td_var
+      TYPE(TDIM)      , INTENT(IN   ) :: td_dim
 
       ! local variable
+      INTEGER(i4) :: il_ind
+
+      !----------------------------------------------------------------
+
+      IF( td_var%i_ndim <= 4 )THEN
+
+         ! check if dimension already used in variable structure
+         il_ind=SCAN(TRIM(cp_dimorder),TRIM(td_dim%c_sname))
+         IF( il_ind == 0 )THEN
+            CALL logger_warn( &
+            &  " VAR ADD DIM: dimension "//TRIM(td_dim%c_name)//&
+            &  ", short name "//TRIM(td_dim%c_sname)//&
+            &  ", will not be added in variable "//TRIM(td_var%c_name) )
+         ELSEIF( td_var%t_dim(il_ind)%l_use )THEN
+            CALL logger_error( &
+            &  " VAR ADD DIM: dimension "//TRIM(td_dim%c_name)//&
+            &  ", short name "//TRIM(td_dim%c_sname)//&
+            &  ", already used in variable "//TRIM(td_var%c_name) )
+         ELSE
+
+         ! back to unorder dimension array 
+         CALL dim_unorder(td_var%t_dim(:))
+            ! add new dimension
+            td_var%t_dim(td_var%i_ndim+1)=dim_copy(td_dim)
+
+            ! update number of attribute
+            td_var%i_ndim=COUNT(td_var%t_dim(:)%l_use)
+
+         ENDIF
+         ! reorder dimension to ('x','y','z','t')
+         CALL dim_reorder(td_var%t_dim(:))
+
+      ELSE
+         CALL logger_error( &
+         &  " VAR ADD DIM: too much dimension in variable "//&
+         &  TRIM(td_var%c_name)//" ("//TRIM(fct_str(td_var%i_ndim))//")")
+      ENDIF
+
+   END SUBROUTINE var__add_dim_unit
+   !-------------------------------------------------------------------
+   !> @brief This subroutine delete a dimension structure in a variable 
+   !> structure.
+   !
+   !> @warning delete variable value too.
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dim    dimension structure
+   !-------------------------------------------------------------------
+   SUBROUTINE var_del_dim(td_var, td_dim)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TVAR)      , INTENT(INOUT) :: td_var
+      TYPE(TDIM)      , INTENT(IN   ) :: td_dim
+
+      ! local variable
+      INTEGER(i4) :: il_ind
+      INTEGER(i4), DIMENSION(ip_maxdim) :: il_shape
+
+      TYPE(TDIM)  :: tl_dim ! empty dimension structure
+
+      !----------------------------------------------------------------
+
+      IF( td_var%i_ndim <= 4 )THEN
+
+         CALL logger_trace( &
+         &  " VAR DEL DIM: delete dimension "//TRIM(td_dim%c_name)//&
+         &  ", short name "//TRIM(td_dim%c_sname)//&
+         &  ", in variable "//TRIM(td_var%c_name) )
+         
+         ! check if dimension already in variable structure
+         il_ind=SCAN(TRIM(cp_dimorder),TRIM(td_dim%c_sname))
+
+         ! replace dimension by empty one
+         td_var%t_dim(il_ind)=dim_copy(tl_dim)
+
+         ! update number of dimension
+         td_var%i_ndim=COUNT(td_var%t_dim(:)%l_use)
+
+         ! remove variable value using this dimension
+         IF( ASSOCIATED(td_var%d_value) )THEN
+            il_shape(:)=SHAPE(td_var%d_value(:,:,:,:))
+            IF(il_shape(il_ind)/=td_dim%i_len)THEN
+               CALL logger_warn("VAR DEL DIM: remove value of variable "//&
+               &  TRIM(td_var%c_name) )
+               CALL var_del_value(td_var)
+            ENDIF
+         ENDIF
+
+         ! reorder dimension to ('x','y','z','t')
+         CALL dim_reorder(td_var%t_dim)
+
+      ELSE
+         CALL logger_error( &
+         &  " VAR DEL DIM: too much dimension in variable "//&
+         &  TRIM(td_var%c_name)//" ("//TRIM(fct_str(td_var%i_ndim))//")")
+      ENDIF
+
+   END SUBROUTINE var_del_dim
+   !-------------------------------------------------------------------
+   !> @brief This subroutine move a dimension structure 
+   !> in variable structure.
+   !>
+   !> @warning 
+   !> - dimension order could be changed
+   !> - delete variable value 
+   !
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] td_dim    dimension structure
+   !-------------------------------------------------------------------
+   SUBROUTINE var_move_dim(td_var, td_dim)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TVAR)      , INTENT(INOUT) :: td_var
+      TYPE(TDIM)      , INTENT(IN   ) :: td_dim
+
+      ! local variable
+      INTEGER(i4) :: il_ind
       INTEGER(i4) :: il_dimid
       !----------------------------------------------------------------
-      IF( td_var%i_ndim <= 4 )THEN
-
-         ! check if dimension already used in variable structure
-         il_dimid=dim_get_id( td_var%t_dim(:), td_dim%c_name, td_dim%c_sname )
-
-         IF( il_dimid == 0 )THEN
-
-               ! add dimension
-               CALL var__add_dim(td_var, td_dim)
+
+      IF( td_var%i_ndim <= ip_maxdim )THEN
+
+         ! check if dimension already in mpp structure
+         il_ind=dim_get_index(td_var%t_dim(:), td_dim%c_name, td_dim%c_sname)
+         IF( il_ind /= 0 )THEN
+
+            il_dimid=td_var%t_dim(il_ind)%i_id
+            ! replace dimension
+            td_var%t_dim(il_ind)=dim_copy(td_dim)
+            td_var%t_dim(il_ind)%i_id=il_dimid
+            td_var%t_dim(il_ind)%l_use=.TRUE.
 
          ELSE
-
-            IF( td_var%t_dim(il_dimid)%l_use )THEN
-
-               CALL logger_error( &
-               &  " ADD DIM: dimension "//TRIM(td_dim%c_name)//&
-               &  ", short name "//TRIM(td_dim%c_sname)//&
-               &  ", already used in variable "//TRIM(td_var%c_name) )
-            ELSE
-               ! add dimension
-               CALL var__add_dim(td_var, td_dim)
-            ENDIF
-
+            CALL var_add_dim(td_var, td_dim)
          ENDIF
 
       ELSE
          CALL logger_error( &
-         &  " ADD DIM: too much dimension in variable "//&
+         &  "VAR MOVE DIM: too much dimension in variale "//&
          &  TRIM(td_var%c_name)//" ("//TRIM(fct_str(td_var%i_ndim))//")")
       ENDIF
 
-   END SUBROUTINE var__add_dim_unit
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a dimension structure in a variable 
-   !> structure.
-   !
+   END SUBROUTINE var_move_dim
+   !-------------------------------------------------------------------
+   !> @brief This subroutine print informations of an array of variables. 
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dim : dimension structure
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_dim(td_var, td_dim)
+   !> - June, 2014- Initial Version
+   !
+   !> @param[in] td_var array of variables structure
+   !-------------------------------------------------------------------
+   SUBROUTINE var__print_arr(td_var)
       IMPLICIT NONE
+
       ! Argument      
-      TYPE(TVAR), INTENT(INOUT) :: td_var
-      TYPE(TDIM), INTENT(IN) :: td_dim
+      TYPE(TVAR), DIMENSION(:), INTENT(IN) :: td_var
 
       ! loop indices
@@ -4843,160 +5374,22 @@
       !----------------------------------------------------------------
 
-      CALL logger_info( &
-      &  " ADD DIM: add dimension "//TRIM(td_dim%c_name)//&
-      &  ", short name "//TRIM(td_dim%c_sname)//&
-      &  ", length "//TRIM(fct_str(td_dim%i_len))//&
-      &  ", in variable "//TRIM(td_var%c_name) )
-
-      ! if dimension order already changed
-      IF( ANY(td_var%t_dim(:)%i_xyzt2 /= 0 ) )THEN
-         ! unordered dimension structure
-         CALL dim_unorder(td_var%t_dim(:))
-      ENDIF
-
-      ! search unused dimension
-      DO ji=1,ip_maxdim
-         IF( .NOT. td_var%t_dim(ji)%l_use )THEN
-            ! add new dimension
-            td_var%t_dim(ji)=td_dim
-            td_var%t_dim(ji)%i_id=ji
-            !!td_var%t_dim(ji)%l_use=.TRUE.
-            IF( td_var%t_dim(ji)%l_use )THEN
-               ! update number of attribute
-               td_var%i_ndim=td_var%i_ndim+1
-            ENDIF
-            EXIT
-         ENDIF
+      DO ji=1,SIZE(td_var(:))
+         CALL var_print(td_var(ji))
       ENDDO
 
-      ! reorder dimension to ('x','y','z','t')
-      CALL dim_reorder(td_var%t_dim(:))
-
-   END SUBROUTINE var__add_dim
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine delete a dimension structure in a variable 
-   !> structure.<br/>
-   !
-   !> @warning delete variable value too
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dim : dimension structure
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var_del_dim(td_var, td_dim)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TVAR), INTENT(INOUT) :: td_var
-      TYPE(TDIM), INTENT(IN) :: td_dim
-
-      ! local variable
-      INTEGER(i4) :: il_dimid
-      TYPE(TDIM)  :: tl_dim ! empty dimension structure
-
-      INTEGER(i4), DIMENSION(ip_maxdim) :: il_shape
-
-      !----------------------------------------------------------------
-      IF( td_var%i_ndim <= 4 )THEN
-
-         ! check if dimension already in variable structure
-         il_dimid=dim_get_id( td_var%t_dim(:), td_dim%c_name, td_dim%c_sname )
-         IF( il_dimid == 0 )THEN
-
-            CALL logger_warn( &
-            &  " DEL DIM: no dimension "//TRIM(td_dim%c_name)//&
-            &  ", short name "//TRIM(td_dim%c_sname)//&
-            &  ", in variable "//TRIM(td_var%c_name) )
-
-         ELSE
-
-            CALL logger_debug( &
-            &  " DEL DIM: delete dimension "//TRIM(td_dim%c_name)//&
-            &  ", short name "//TRIM(td_dim%c_sname)//&
-            &  ", in variable "//TRIM(td_var%c_name)//&
-            &  " id "//TRIM(fct_str(il_dimid)) )
-
-            ! replace dimension by empty one
-            td_var%t_dim(il_dimid)=tl_dim
-
-            ! update number of dimension
-            td_var%i_ndim=td_var%i_ndim-1
-
-            IF( ASSOCIATED(td_var%d_value) )THEN
-               il_shape(:)=SHAPE(td_var%d_value(:,:,:,:))
-               IF(il_shape(il_dimid)/=td_dim%i_len)THEN
-                  CALL logger_warn("VAR DEL DIM: remove value of variable "//&
-                  &  TRIM(td_var%c_name) )
-                  CALL var_del_value(td_var)
-               ENDIF
-            ENDIF
-
-            ! reorder dimension to ('x','y','z','t')
-            CALL dim_reorder(td_var%t_dim)
-
-         ENDIF
-      ELSE
-         CALL logger_error( &
-         &  " DEL DIM: too much dimension in variable "//&
-         &  TRIM(td_var%c_name)//" ("//TRIM(fct_str(td_var%i_ndim))//")")
-      ENDIF
-
-   END SUBROUTINE var_del_dim
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine move a dimension structure 
-   !> in variable structure.
-   !>
-   !> @warning 
-   !> - dimension order could be changed
-   !> - delete variable value 
-   !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] td_dim : dimension structure
-   !> @todo
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var_move_dim(td_var, td_dim)
-      IMPLICIT NONE
-      ! Argument      
-      TYPE(TVAR), INTENT(INOUT) :: td_var
-      TYPE(TDIM), INTENT(IN)    :: td_dim
-
-      ! local variable
-      TYPE(TDIM) :: tl_dim
-      !----------------------------------------------------------------
-
-      ! copy dimension
-      tl_dim=td_dim
-
-      ! remove dimension with same name
-      CALL var_del_dim(td_var, tl_dim)
-
-      ! add new dimension
-      CALL var_add_dim(td_var, tl_dim)
-
-   END SUBROUTINE var_move_dim
-   !> @endcode    
+   END SUBROUTINE var__print_arr
    !-------------------------------------------------------------------
    !> @brief This subroutine print variable information.</br/>
+   !> @details
    !> If ld_more is TRUE (default), print information about variable dimensions
    !> and variable attributes.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : variable structure
-   !> @param[in] ld_more : print more infomration about variable
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var_print(td_var, ld_more)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var    variable structure
+   !> @param[in] ld_more   print more infomration about variable
+   !-------------------------------------------------------------------
+   SUBROUTINE var__print_unit(td_var, ld_more)
       IMPLICIT NONE
 
@@ -5039,6 +5432,21 @@
       END SELECT      
 
+      WRITE(*,'((/a,a),4(/3x,a,a),4(/3x,a,i3),&
+      &         (/3x,a,a),3(/3x,a,ES12.4))')&
+      &        " Variable : ",TRIM(td_var%c_name),    &
+      &        " standard name : ",TRIM(td_var%c_stdname), &
+      &        " long name     : ",TRIM(td_var%c_longname), &
+      &        " units         : ",TRIM(td_var%c_units),   &
+      &        " point         : ",TRIM(td_var%c_point),   &
+      &        " id            : ",td_var%i_id,            &
+      &        " rec           : ",td_var%i_rec,           &
+      &        " ndim          : ",td_var%i_ndim,          &
+      &        " natt          : ",td_var%i_natt,          &
+      &        " type          : ",TRIM(cl_type),          &
+      &        " scale factor  : ",td_var%d_scf,           &
+      &        " add offset    : ",td_var%d_ofs,           &
+      &        " _FillValue    : ",td_var%d_fill
+
       IF( ASSOCIATED(td_var%d_value) )THEN
-         WRITE(*,*) "ASSOCIATED"
          dl_min=MINVAL(td_var%d_value(:,:,:,:), &
          &             mask=(td_var%d_value(:,:,:,:)/=td_var%d_fill) )&
@@ -5047,30 +5455,15 @@
          &             mask=(td_var%d_value(:,:,:,:)/=td_var%d_fill) )&
          &      *td_var%d_scf+td_var%d_ofs
-      ELSE
-         WRITE(*,*) "NOT ASSOCIATED"
-         dl_min=0.
-         dl_max=0.
-      ENDIF
-
-      WRITE(*,'((a,a),3(/3x,a,a),3(/3x,a,i3),&
-      &         (/3x,a,a),5(/3x,a,ES12.4))')&
-      &        " Variable : ",TRIM(td_var%c_name),    &
-      &        " standard name : ",TRIM(td_var%c_stdname), &
-      &        " units         : ",TRIM(td_var%c_units),   &
-      &        " point         : ",TRIM(td_var%c_point),   &
-      &        " id            : ",td_var%i_id,            &
-      &        " ndim          : ",td_var%i_ndim,          &
-      &        " natt          : ",td_var%i_natt,          &
-      &        " type          : ",TRIM(cl_type),          &
-      &        " scale factor  : ",td_var%d_scf,           &
-      &        " add offset    : ",td_var%d_ofs,           &
-      &        " _FillValue    : ",td_var%d_fill,          &
-      &        " min value     : ",dl_min,                 &        
-      &        " max value     : ",dl_max
+
+         WRITE(*,'((3x,a),2(/3x,a,ES12.4))')&
+         &        "VALUE ASSOCIATED" ,       &
+         &        " min value     : ",dl_min,&        
+         &        " max value     : ",dl_max
+      ENDIF      
 
       IF( ll_more )THEN
          ! print dimension
          IF(  td_var%i_ndim /= 0 )THEN
-            WRITE(*,'(/a)') " Variable dimension"
+            WRITE(*,'(a)') " Variable dimension"
             DO ji=1,ip_maxdim
                IF( td_var%t_dim(ji)%l_use )THEN
@@ -5082,5 +5475,5 @@
          ! print attribute
          IF( td_var%i_natt /= 0 )THEN
-            WRITE(*,'(/a)') " Variable attribute"
+            WRITE(*,'(a)') " Variable attribute"
             DO ji=1,td_var%i_natt
                CALL att_print(td_var%t_att(ji))
@@ -5089,28 +5482,23 @@
       ENDIF
 
-   END SUBROUTINE var_print
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a 4D table of double value in a variable 
+   END SUBROUTINE var__print_unit
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add a 4D array of real(8) value in a variable 
    !> structure.
-   !>
-   !> @warning Dimension of the table must be ordered as ('x','y','z','t')
    !
    !> @details 
    !> indices in the variable where value will be written could be specify if
-   !> start and count table are given. 
-   !
+   !> start and count array are given. 
+   !> @warning Dimension of the array must be ordered as ('x','y','z','t')
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] dd_value : table of variable value
-   !> @param[in] id_start : index in the variable from which the data values 
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_var variable structure
+   !> @param[in] dd_value  array of variable value
+   !> @param[in] id_start  index in the variable from which the data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
    SUBROUTINE var__add_value(td_var, dd_value, id_start, id_count)
       IMPLICIT NONE
@@ -5135,10 +5523,10 @@
           ((.NOT. PRESENT(id_start)) .AND.        PRESENT(id_count) ) )THEN
          CALL logger_warn( &
-         &  " ADD VALUE: id_start and id_count should be both specified")
+         &  " VAR ADD VALUE: id_start and id_count should be both specified")
       ENDIF
 
       IF( PRESENT(id_start).AND.PRESENT(id_count) )THEN
 
-         ! keep ordered table ('x','y','z','t')
+         ! keep ordered array ('x','y','z','t')
          il_start(:)=id_start(:)
          il_count(:)=id_count(:)
@@ -5146,5 +5534,5 @@
       ELSE
 
-         ! keep ordered table ('x','y','z','t')
+         ! keep ordered array ('x','y','z','t')
          il_start(:)=(/1,1,1,1/)
          il_count(:)=td_var%t_dim(:)%i_len
@@ -5152,16 +5540,16 @@
       ENDIF
 
-      ! check dimension of input table
+      ! check dimension of input array
       il_shape(:)=SHAPE(dd_value(:,:,:,:))
       IF(.NOT.ALL( il_count(:) == il_shape(:)) )THEN
-         CALL logger_error( &
-         &  " ADD VALUE: dimension of input table, and count table differ " )
 
          CALL logger_debug(" ADD VALUE: check dimension order !!")
          DO ji = 1, ip_maxdim
             CALL logger_debug( &
-            &  " ADD VALUE: count : "//TRIM(fct_str(il_count(ji)))//&
-            &  " table dimension : "//TRIM(fct_str(il_shape(ji))))
+            &  " VAR ADD VALUE: count : "//TRIM(fct_str(il_count(ji)))//&
+            &  " array dimension : "//TRIM(fct_str(il_shape(ji))))
          ENDDO
+         CALL logger_error( &
+         &  " VAR ADD VALUE: dimension of input array, and count array differ " )
 
       ELSE
@@ -5169,15 +5557,15 @@
          ! check dimension of variable
          IF(.NOT.ALL(il_start(:)+il_count(:)-1 <= td_var%t_dim(:)%i_len) )THEN
-            CALL logger_error( &
-            &  " ADD VALUE: start + count exceed variable dimension. " )
-
-            CALL logger_debug(" ADD VALUE: check dimension order !!")
+
+            CALL logger_debug(" VAR ADD VALUE: check dimension order !!")
             DO ji = 1, ip_maxdim
                CALL logger_debug( &
-               &  " ADD VALUE: start ("//TRIM(fct_str(il_start(ji)))//") "//&
+               &  " VAR ADD VALUE: start ("//TRIM(fct_str(il_start(ji)))//") "//&
                &  "+ count ("//TRIM(fct_str(il_count(ji)))//") "//&
                &  "variable dimension "//TRIM(fct_str(td_var%t_dim(ji)%i_len)))
             ENDDO
 
+            CALL logger_error( &
+            &  " VAR ADD VALUE: start + count exceed variable dimension bound. " )
          ELSE
 
@@ -5191,5 +5579,5 @@
 
                CALL logger_warn( &
-               &  " ADD VALUE: value already in variable "//&
+               &  "VAR ADD VALUE: value already in variable "//&
                &  TRIM(td_var%c_name)//&
                &  " (standard name "//TRIM(td_var%c_stdname)//")" )
@@ -5206,5 +5594,5 @@
 
                  CALL logger_error( &
-                  &  " ADD VALUE: not enough space to put variable "//&
+                  &  " VAR ADD VALUE: not enough space to put variable "//&
                   &  TRIM(td_var%c_name)//&
                   &  " in variable structure")
@@ -5212,7 +5600,7 @@
                ENDIF
                
-               ! initialise table
-               CALL logger_info( &
-               &  " ADD VALUE: value in variable "//TRIM(td_var%c_name)//&
+               ! initialise array
+               CALL logger_trace( &
+               &  " VAR ADD VALUE: value in variable "//TRIM(td_var%c_name)//&
                &  ", initialise to FillValue "//TRIM(fct_str(td_var%d_fill)) )
                td_var%d_value(:,:,:,:)=td_var%d_fill
@@ -5220,6 +5608,6 @@
             ENDIF
 
-            CALL logger_info( &
-            &  " ADD VALUE: put value in variable "//TRIM(td_var%c_name)//&
+            CALL logger_debug( &
+            &  " VAR ADD VALUE: put value in variable "//TRIM(td_var%c_name)//&
             &  " (standard name "//TRIM(td_var%c_stdname)//")" )
 
@@ -5234,32 +5622,28 @@
 
    END SUBROUTINE var__add_value
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a 4D table of real(8) value in a variable 
-   !> structure. Dimension of the table must be ordered as ('x','y','z','t')
-   !
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add a 4D array of real(8) value in a variable 
+   !> structure. Dimension of the array must be ordered as ('x','y','z','t')
+   !>
    !> @details 
-   !> indices of the variable where value will be written could be specify
-   !> with start and count table.
-   !>
-   !> @note variable type is forced to DOUBLE
-   !
+   !> Optionally, you could specify the type of the variable to be used (default real(8)),
+   !> and indices of the variable where value will be written with start and count array.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] dd_value : table of variable value
-   !> @param[in] id_start : start indices of the variable where data values 
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_var variable structure
+   !> @param[in] dd_value  array of variable value
+   !> @param[in] id_type   type of the variable to be used (default real(8)) 
+   !> @param[in] id_start  start indices of the variable where data values 
    !> will be written
-   !> @param[in] id_count : number of indices selected along each dimension
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_value_dp(td_var, dd_value, id_start, id_count)
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_value_dp(td_var, dd_value, id_type, id_start, id_count)
       IMPLICIT NONE
       ! Argument      
       TYPE(TVAR),                        INTENT(INOUT) :: td_var
       REAL(dp),    DIMENSION(:,:,:,:),   INTENT(IN)    :: dd_value
+      INTEGER(i4),                       INTENT(IN),   OPTIONAL  :: id_type
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_start
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_count
@@ -5269,7 +5653,7 @@
       !----------------------------------------------------------------
 
-      IF( td_var%i_type == 0 )THEN
-         td_var%i_type=NF90_DOUBLE
-      ELSE
+      IF( PRESENT(id_type) )THEN
+         td_var%i_type=id_type
+
          cl_type=''
          SELECT CASE(td_var%i_type)
@@ -5285,5 +5669,5 @@
             cl_type='BYTE'
          END SELECT
-         CALL logger_info("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
+         CALL logger_trace("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
          &                " value will be saved as "//TRIM(cl_type)) 
       ENDIF
@@ -5292,32 +5676,28 @@
 
    END SUBROUTINE var__add_value_dp
-   !> @endcode   
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a 4D table of real value in a variable 
-   !> structure. Dimension of the table must be ordered as ('x','y','z','t')
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add a 4D array of real(4) value in a variable 
+   !> structure. Dimension of the array must be ordered as ('x','y','z','t')
    !
    !> @details 
-   !> indices of the variable where value will be written could be specify
-   !> wiht start and count table.   
-   !>
-   !> @note variable type is forced to FLOAT
-   !
+   !> Optionally, you could specify the type of the variable to be used (default real(4)),
+   !> and indices of the variable where value will be written with start and count array.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] rd_value : table of variable value
-   !> @param[in] id_start : start indices of the variable where data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] rd_value  array of variable value
+   !> @param[in] id_type   type of the variable to be used (default real(4)) 
+   !> @param[in] id_start  start indices of the variable where data values 
    !> will be written
-   !> @param[in] id_count : number of indices selected along each dimension
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_value_rp(td_var, rd_value, id_start, id_count)
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_value_rp(td_var, rd_value, id_type, id_start, id_count)
       IMPLICIT NONE
       ! Argument      
       TYPE(TVAR),                        INTENT(INOUT) :: td_var
       REAL(sp),    DIMENSION(:,:,:,:),   INTENT(IN)    :: rd_value
+      INTEGER(i4),                       INTENT(IN),   OPTIONAL  :: id_type
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_start
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_count
@@ -5332,7 +5712,7 @@
       !----------------------------------------------------------------
 
-      IF( td_var%i_type == 0 )THEN
-         td_var%i_type=NF90_FLOAT
-      ELSE
+      IF( PRESENT(id_type) )THEN
+         td_var%i_type=id_type
+
          cl_type=''
          SELECT CASE(td_var%i_type)
@@ -5348,5 +5728,5 @@
             cl_type='BYTE'
          END SELECT
-         CALL logger_info("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
+         CALL logger_trace("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
          &                " value will be saved as "//TRIM(cl_type)) 
       ENDIF      
@@ -5358,5 +5738,5 @@
 
         CALL logger_error( &
-         &  " ADD VALUE: not enough space to put variable "//&
+         &  " VAR ADD VALUE: not enough space to put variable "//&
          &  TRIM(td_var%c_name)//&
          &  " in variable structure")
@@ -5370,32 +5750,30 @@
 
    END SUBROUTINE var__add_value_rp
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a 4D table of integer(1) value in a variable 
-   !> structure. Dimension of the table must be ordered as ('x','y','z','t')
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add a 4D array of integer(1) value in a variable 
+   !> structure. Dimension of the array must be ordered as ('x','y','z','t')
    !
    !> @details 
-   !> indices in the variable where value will be written could be specify if
-   !> start and count table are given.   
+   !> Optionally, you could specify the type of the variable to be used (default integer(1)),
+   !> and indices of the variable where value will be written with start and count array.
    !>
    !> @note variable type is forced to BYTE
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variabele structure
-   !> @param[in] bd_value : table of variable value
-   !> @param[in] id_start : start indices of the variable where data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variabele structure
+   !> @param[in] bd_value  array of variable value
+   !> @param[in] id_type   type of the variable to be used (default integer(1)) 
+   !> @param[in] id_start  start indices of the variable where data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_value_i1(td_var, bd_value, id_start, id_count)
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_value_i1(td_var, bd_value, id_type, id_start, id_count)
       IMPLICIT NONE
       ! Argument      
       TYPE(TVAR),                        INTENT(INOUT) :: td_var
       INTEGER(i1), DIMENSION(:,:,:,:),   INTENT(IN)    :: bd_value
+      INTEGER(i4),                       INTENT(IN),   OPTIONAL  :: id_type
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_start
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_count
@@ -5410,7 +5788,7 @@
       !----------------------------------------------------------------
 
-      IF( td_var%i_type == 0 )THEN
-         td_var%i_type=NF90_BYTE
-      ELSE
+      IF( PRESENT(id_type) )THEN
+         td_var%i_type=id_type
+
          cl_type=''
          SELECT CASE(td_var%i_type)
@@ -5426,5 +5804,5 @@
             cl_type='BYTE'
          END SELECT
-         CALL logger_info("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
+         CALL logger_trace("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
          &                " value will be saved as "//TRIM(cl_type)) 
       ENDIF
@@ -5436,5 +5814,5 @@
 
         CALL logger_error( &
-         &  " ADD VALUE: not enough space to put variable "//&
+         &  " VAR ADD VALUE: not enough space to put variable "//&
          &  TRIM(td_var%c_name)//&
          &  " in variable structure")
@@ -5448,32 +5826,30 @@
 
    END SUBROUTINE var__add_value_i1
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a 4D table of integer(1) value in a variable 
-   !> structure. Dimension of the table must be ordered as ('x','y','z','t')
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add a 4D array of integer(2) value in a variable 
+   !> structure. Dimension of the array must be ordered as ('x','y','z','t')
    !
    !> @details 
-   !> indices in the variable where value will be written could be specify if
-   !> start and count table are given.   
+   !> Optionally, you could specify the type of the variable to be used (default integer(2)),
+   !> and indices of the variable where value will be written with start and count array.
    !>
    !> @note variable type is forced to SHORT
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variabele structure
-   !> @param[in] sd_value : table of variable value
-   !> @param[in] id_start : start indices of the variable where data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variabele structure
+   !> @param[in] sd_value  array of variable value
+   !> @param[in] id_type   type of the variable to be used (default integer(2)) 
+   !> @param[in] id_start  start indices of the variable where data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_value_i2(td_var, sd_value, id_start, id_count)
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_value_i2(td_var, sd_value, id_type, id_start, id_count)
       IMPLICIT NONE
       ! Argument      
       TYPE(TVAR),                        INTENT(INOUT) :: td_var
       INTEGER(i2), DIMENSION(:,:,:,:),   INTENT(IN)    :: sd_value
+      INTEGER(i4),                       INTENT(IN),   OPTIONAL  :: id_type
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_start
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_count
@@ -5488,7 +5864,7 @@
       !----------------------------------------------------------------
 
-      IF( td_var%i_type == 0 )THEN
-         td_var%i_type=NF90_SHORT
-      ELSE
+      IF( PRESENT(id_type) )THEN
+         td_var%i_type=id_type
+
          cl_type=''
          SELECT CASE(td_var%i_type)
@@ -5504,5 +5880,5 @@
             cl_type='BYTE'
          END SELECT
-         CALL logger_info("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
+         CALL logger_trace("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
          &                " value will be saved as "//TRIM(cl_type)) 
       ENDIF
@@ -5514,5 +5890,5 @@
 
         CALL logger_error( &
-         &  " ADD VALUE: not enough space to put variable "//&
+         &  " VAR ADD VALUE: not enough space to put variable "//&
          &  TRIM(td_var%c_name)//&
          &  " in variable structure")
@@ -5526,32 +5902,30 @@
 
    END SUBROUTINE var__add_value_i2
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a 4D table of integer(4) value in a variable 
-   !> structure. Dimension of the table must be ordered as ('x','y','z','t')
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add a 4D array of integer(4) value in a variable 
+   !> structure. Dimension of the array must be ordered as ('x','y','z','t')
    !
    !> @details 
-   !> indices in the variable where value will be written could be specify if
-   !> start and count table are given.   
+   !> Optionally, you could specify the type of the variable to be used (default integer(4)),
+   !> and indices of the variable where value will be written with start and count array.
    !>
    !> @note variable type is forced to INT
    !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variabele structure
-   !> @param[in] id_value : table of variable value
-   !> @param[in] id_start : start indices of the variable where data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variabele structure
+   !> @param[in] id_value  array of variable value
+   !> @param[in] id_type   type of the variable to be used (default integer(4)) 
+   !> @param[in] id_start  start indices of the variable where data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_value_i4(td_var, id_value, id_start, id_count)
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_value_i4(td_var, id_value, id_type, id_start, id_count)
       IMPLICIT NONE
       ! Argument      
       TYPE(TVAR),                        INTENT(INOUT) :: td_var
       INTEGER(i4), DIMENSION(:,:,:,:),   INTENT(IN)    :: id_value
+      INTEGER(i4),                       INTENT(IN),   OPTIONAL  :: id_type
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_start
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_count
@@ -5566,7 +5940,7 @@
       !----------------------------------------------------------------
 
-      IF( td_var%i_type == 0 )THEN
-         td_var%i_type=NF90_INT
-      ELSE
+      IF( PRESENT(id_type) )THEN
+         td_var%i_type=id_type
+
          cl_type=''
          SELECT CASE(td_var%i_type)
@@ -5582,5 +5956,5 @@
             cl_type='BYTE'
          END SELECT
-         CALL logger_info("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
+         CALL logger_trace("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
          &                " value will be saved as "//TRIM(cl_type)) 
       ENDIF
@@ -5592,5 +5966,5 @@
 
         CALL logger_error( &
-         &  " ADD VALUE: not enough space to put variable "//&
+         &  " VAR ADD VALUE: not enough space to put variable "//&
          &  TRIM(td_var%c_name)//&
          &  " in variable structure")
@@ -5604,32 +5978,28 @@
 
    END SUBROUTINE var__add_value_i4
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This subroutine add a 4D table of integer(4) value in a variable 
-   !> structure. Dimension of the table must be ordered as ('x','y','z','t')
+   !-------------------------------------------------------------------
+   !> @brief This subroutine add a 4D array of integer(8) value in a variable 
+   !> structure. Dimension of the array must be ordered as ('x','y','z','t')
    !
    !> @details 
-   !> indices in the variable where value will be written could be specify if
-   !> start and count table are given.   
-   !>
-   !> @note variable type is forced to INT
-   !
+   !> Optionally, you could specify the type of the variable to be used (default integer(4)),
+   !> and indices of the variable where value will be written with start and count array.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] kd_value : table of variable value
-   !> @param[in] id_start : start indices of the variable where data values 
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] kd_value  array of variable value
+   !> @param[in] id_type   type of the variable to be used (default integer(8)) 
+   !> @param[in] id_start  start indices of the variable where data values 
    !> will be read
-   !> @param[in] id_count : number of indices selected along each dimension
-   !
-   !> @todo 
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var__add_value_i8(td_var, kd_value, id_start, id_count)
+   !> @param[in] id_count  number of indices selected along each dimension
+   !-------------------------------------------------------------------
+   SUBROUTINE var__add_value_i8(td_var, kd_value, id_type, id_start, id_count)
       IMPLICIT NONE
       ! Argument      
       TYPE(TVAR),                        INTENT(INOUT) :: td_var
       INTEGER(i8), DIMENSION(:,:,:,:),   INTENT(IN)    :: kd_value
+      INTEGER(i4),                       INTENT(IN),   OPTIONAL  :: id_type
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_start
       INTEGER(i4), DIMENSION(ip_maxdim), INTENT(IN),   OPTIONAL  :: id_count
@@ -5644,7 +6014,7 @@
       !----------------------------------------------------------------
 
-      IF( td_var%i_type == 0 )THEN
-         td_var%i_type=NF90_INT
-      ELSE
+      IF( PRESENT(id_type) )THEN
+         td_var%i_type=id_type
+
          cl_type=''
          SELECT CASE(td_var%i_type)
@@ -5660,5 +6030,5 @@
             cl_type='BYTE'
          END SELECT
-         CALL logger_info("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
+         CALL logger_trace("VAR ADD VALUE: "//TRIM(td_var%c_name)//&
          &                " value will be saved as "//TRIM(cl_type)) 
       ENDIF
@@ -5670,5 +6040,5 @@
 
         CALL logger_error( &
-         &  " ADD VALUE: not enough space to put variable "//&
+         &  " VAR ADD VALUE: not enough space to put variable "//&
          &  TRIM(td_var%c_name)//&
          &  " in variable structure")
@@ -5682,16 +6052,13 @@
 
    END SUBROUTINE var__add_value_i8
-   !> @endcode   
    !-------------------------------------------------------------------
    !> @brief This subroutine remove variable value in a variable 
    !> structure.
-   !
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_var variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE var_del_value(td_var)
       IMPLICIT NONE
@@ -5700,6 +6067,6 @@
 
       !----------------------------------------------------------------
-      CALL logger_warn( &
-      &  " DEL VALUE: value in variable "//TRIM(td_var%c_name)//&
+      CALL logger_debug( &
+      &  " VAR DEL VALUE: value in variable "//TRIM(td_var%c_name)//&
       &  ", standard name "//TRIM(td_var%c_stdname)//&
       &  " will be remove ")
@@ -5708,18 +6075,81 @@
 
    END SUBROUTINE var_del_value
-   !> @endcode
-   !-------------------------------------------------------------------
-   !> @brief This function return the variable id, in a table of variable
-   !> structure,  given variable name or standard name 
-   !
+   !-------------------------------------------------------------------
+   !> @brief This function return the variable index, in a array of variable
+   !> structure,  given variable name or standard name. 
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : table of variable structure
-   !> @param[in] cd_name : variable name
-   !> @param[in] cd_stdname : variable standard name
-   !> @return variable id in table of variable structure (0 if not found)
-   !-------------------------------------------------------------------
-   !> @code
+   !> - September, 2014- Initial Version
+   !>
+   !> @param[in] td_var       array of variable structure
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_stdname   variable standard name
+   !> @return variable index in array of variable structure (0 if not found)
+   !-------------------------------------------------------------------
+   INTEGER(i4) FUNCTION var_get_index(td_var, cd_name, cd_stdname)
+      IMPLICIT NONE
+      ! Argument      
+      TYPE(TVAR)      , DIMENSION(:), INTENT(IN) :: td_var
+      CHARACTER(LEN=*),               INTENT(IN) :: cd_name
+      CHARACTER(LEN=*),               INTENT(IN), OPTIONAL :: cd_stdname
+
+      ! local variable
+      INTEGER(i4) :: il_size
+
+      ! loop indices
+      INTEGER(i4) :: ji
+      !----------------------------------------------------------------
+      var_get_index=0
+      il_size=SIZE(td_var(:))
+
+      ! check if variable is in array of variable structure
+      DO ji=1,il_size
+         ! look for variable name
+         IF( fct_lower(td_var(ji)%c_name) == fct_lower(cd_name) )THEN
+         
+            var_get_index=ji
+            EXIT
+
+         ! look for variable standard name
+         ELSE IF( fct_lower(td_var(ji)%c_stdname) == fct_lower(cd_name) .AND.&
+         &    TRIM(fct_lower(td_var(ji)%c_stdname)) /= '' )THEN
+            
+            var_get_index=ji
+            EXIT
+
+         ELSE IF( PRESENT(cd_stdname) )THEN 
+            IF( fct_lower(td_var(ji)%c_stdname) == fct_lower(cd_stdname) .AND.&
+            &    TRIM(fct_lower(td_var(ji)%c_stdname)) /= '' )THEN
+            
+               var_get_index=ji
+               EXIT
+            ENDIF
+
+         ! look for variable longname
+         ELSE IF( fct_lower(td_var(ji)%c_longname) == fct_lower(cd_name) .AND.&
+         &    TRIM(fct_lower(td_var(ji)%c_longname)) /= '' )THEN
+            
+            var_get_index=ji
+            EXIT
+
+         ENDIF
+
+      ENDDO
+
+   END FUNCTION var_get_index
+   !-------------------------------------------------------------------
+   !> @brief This function return the variable id, 
+   !> given variable name or standard name. 
+   !>
+   !> @warning only variable read from file, have an id.
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var       array of variable structure
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_stdname   variable standard name
+   !> @return variable id in array of variable structure (0 if not found)
+   !-------------------------------------------------------------------
    INTEGER(i4) FUNCTION var_get_id(td_var, cd_name, cd_stdname)
       IMPLICIT NONE
@@ -5738,10 +6168,10 @@
       il_size=SIZE(td_var(:))
 
-      ! check if variable is in table of variable structure
+      ! check if variable is in array of variable structure
       DO ji=1,il_size
          ! look for variable name
          IF( fct_lower(td_var(ji)%c_name) == fct_lower(cd_name) )THEN
          
-            var_get_id=ji
+            var_get_id=td_var(ji)%i_id
             EXIT
 
@@ -5749,7 +6179,6 @@
          ELSE IF( fct_lower(td_var(ji)%c_stdname) == fct_lower(cd_name) .AND.&
          &    TRIM(fct_lower(td_var(ji)%c_stdname)) /= '' )THEN
-         !&    TRIM(ADJUSTL(cd_stdname)) /= 'unknown' )THEN
             
-            var_get_id=ji
+            var_get_id=td_var(ji)%i_id
             EXIT
 
@@ -5757,7 +6186,6 @@
             IF( fct_lower(td_var(ji)%c_stdname) == fct_lower(cd_stdname) .AND.&
             &    TRIM(fct_lower(td_var(ji)%c_stdname)) /= '' )THEN
-            !&    TRIM(ADJUSTL(cd_stdname)) /= 'unknown' )THEN
             
-               var_get_id=ji
+               var_get_id=td_var(ji)%i_id
                EXIT
             ENDIF
@@ -5767,18 +6195,14 @@
 
    END FUNCTION var_get_id
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This function return the mask of variable, given variable structure 
-   !> @detail
-   !> 
-   !
+   !> This function return the mask 3D of variable, given variable structure.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : table of variable structure
-   !> @return variable id in table of variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var array of variable structure
+   !> @return variable mask(3D)
+   !-------------------------------------------------------------------
    FUNCTION var_get_mask(td_var)
       IMPLICIT NONE
@@ -5787,7 +6211,7 @@
 
       ! function
-      !INTEGER(i4), DIMENSION(:,:), POINTER :: var_get_mask
       INTEGER(i4), DIMENSION(td_var%t_dim(1)%i_len, &
-      &                      td_var%t_dim(2)%i_len) :: var_get_mask
+      &                      td_var%t_dim(2)%i_len, &
+      &                      td_var%t_dim(3)%i_len ) :: var_get_mask
 
       ! local variable
@@ -5795,39 +6219,45 @@
       IF( ASSOCIATED(td_var%d_value) )THEN
 
-         CALL logger_trace( "GET MASK: create mask from variable "//&
+         CALL logger_trace( "VAR GET MASK: create mask from variable "//&
          &               TRIM(td_var%c_name) )
-         var_get_mask(:,:)=1
-         WHERE( td_var%d_value(:,:,1,1) == td_var%d_fill )
-            var_get_mask(:,:)=0
+         var_get_mask(:,:,:)=1
+         WHERE( td_var%d_value(:,:,:,1) == td_var%d_fill )
+            var_get_mask(:,:,:)=0
          ENDWHERE
 
       ELSE
-         CALL logger_error("GET MASK: variable value not define.")
+         CALL logger_error("VAR GET MASK: variable value not define.")
       ENDIF
    END FUNCTION var_get_mask
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine change Fill Value of the variable to 
-   !> standard NETCDF Fill Value 
-   !> @detail
+   !> This subroutine change FillValue of the variable to 
+   !> standard NETCDF FillValue. 
+   !>
+   !> @details
+   !> optionally, you could specify a dummy _FillValue to be used
    !> 
-   !
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : table of variable structure
-   !-------------------------------------------------------------------
-   !> @code
-   SUBROUTINE var_chg_FillValue(td_var)
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var array of variable structure
+   !> @param[in] dd_fill _FillValue to be used
+   !-------------------------------------------------------------------
+   SUBROUTINE var_chg_FillValue(td_var, dd_fill)
       IMPLICIT NONE
       ! Argument      
       TYPE(TVAR), INTENT(INOUT) :: td_var
+      REAL(dp)  , INTENT(IN)   , OPTIONAL :: dd_fill
 
       ! local variable
       TYPE(TATT) :: tl_att
+
+      INTEGER(i1) :: bl_fill
+      INTEGER(i2) :: sl_fill
+      INTEGER(i4) :: il_fill
+      REAL(sp)    :: rl_fill
       !----------------------------------------------------------------
 
-      CALL logger_debug( "CHG FILL VALUE: change _FillValue in variable "//&
+      CALL logger_trace( "VAR CHG FILL VALUE: change _FillValue in variable "//&
       &  TRIM(td_var%c_name) )
 
@@ -5836,15 +6266,37 @@
 
          CASE(NF90_BYTE)
-            tl_att=att_init('_FillValue',NF90_FILL_BYTE)
+            IF( PRESENT(dd_fill) )THEN
+               bl_fill=INT(dd_fill,i1)
+               tl_att=att_init('_FillValue',bl_fill)
+            ELSE
+               tl_att=att_init('_FillValue',NF90_FILL_BYTE)
+            ENDIF
          CASE(NF90_SHORT)
-            tl_att=att_init('_FillValue',NF90_FILL_SHORT)
+            IF( PRESENT(dd_fill) )THEN
+               sl_fill=INT(dd_fill,i2)
+               tl_att=att_init('_FillValue',sl_fill)
+            ELSE
+               tl_att=att_init('_FillValue',NF90_FILL_SHORT)
+            ENDIF
          CASE(NF90_INT)
-            tl_att=att_init('_FillValue',NF90_FILL_INT)
+            IF( PRESENT(dd_fill) )THEN
+               il_fill=INT(dd_fill,i4)
+               tl_att=att_init('_FillValue',il_fill)
+            ELSE
+               tl_att=att_init('_FillValue',NF90_FILL_INT)
+            ENDIF
          CASE(NF90_FLOAT)
-            tl_att=att_init('_FillValue',NF90_FILL_FLOAT)
-         CASE(NF90_DOUBLE)
-            tl_att=att_init('_FillValue',NF90_FILL_DOUBLE)
-         CASE DEFAULT
-            tl_att=att_init('_FillValue',NF90_FILL_DOUBLE)
+            IF( PRESENT(dd_fill) )THEN
+               rl_fill=REAL(dd_fill,sp)
+               tl_att=att_init('_FillValue',rl_fill)
+            ELSE
+               tl_att=att_init('_FillValue',NF90_FILL_FLOAT)
+            ENDIF
+         CASE DEFAULT ! NF90_DOUBLE
+            IF( PRESENT(dd_fill) )THEN
+               tl_att=att_init('_FillValue',dd_fill)
+            ELSE
+               tl_att=att_init('_FillValue',NF90_FILL_DOUBLE)
+            ENDIF
 
       END SELECT
@@ -5860,19 +6312,18 @@
       CALL var_move_att(td_var, tl_att)
 
+      ! clean
+      CALL att_clean(tl_att)
+
    END SUBROUTINE var_chg_FillValue
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine read variable configuration file, fill and save 
-   !> a global table of variable structure with extra information :tg_varextra.
+   !> This subroutine read variable configuration file. And save 
+   !> global array of variable structure with extra information: tg_varextra.
    !> 
-   !> @details 
-   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_file : configuration file of variable
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_file   configuration file of variable
+   !-------------------------------------------------------------------
    SUBROUTINE var_def_extra( cd_file )
       IMPLICIT NONE
@@ -5894,5 +6345,8 @@
       !----------------------------------------------------------------
 
-      IF( ALLOCATED(tg_varextra) ) DEALLOCATE(tg_varextra)
+      IF( ALLOCATED(tg_varextra) )THEN
+         CALL var_clean(tg_varextra(:))
+         DEALLOCATE(tg_varextra)
+      ENDIF
 
       ! read config variable file
@@ -5901,7 +6355,7 @@
          
          ! get number of variable to be read
+
          il_fileid=fct_getunit()
-
-         CALL logger_debug("VAR DEF EXTRA: open "//TRIM(cd_file))
+         CALL logger_trace("VAR DEF EXTRA: open "//TRIM(cd_file))
          OPEN( il_fileid, FILE=TRIM(cd_file), &
          &                FORM='FORMATTED',   &
@@ -5922,5 +6376,5 @@
 
          ! search line do not beginning with comment character
-            IF( SCAN( TRIM(fct_concat(cg_com(:))) ,cl_line(1:1)) == 0 )THEN
+            IF( SCAN( TRIM(fct_concat(cp_com(:))) ,cl_line(1:1)) == 0 )THEN
                il_nvar=il_nvar+1
             ENDIF
@@ -5941,7 +6395,8 @@
          ELSE
             CALL logger_info("VAR DEF EXTRA: "//TRIM(fct_str(il_nvar))//&
-            &            " variable to be read on varaible config file")
-
-            CALL logger_debug("VAR DEF EXTRA: rewind "//TRIM(cd_file))
+            &            " variable to be read on varaible config file"//&
+            &            TRIM(cd_file))
+
+            CALL logger_trace("VAR DEF EXTRA: rewind "//TRIM(cd_file))
             REWIND( il_fileid, IOSTAT=il_status)
             CALL fct_err(il_status)
@@ -5958,5 +6413,5 @@
             DO WHILE( il_status == 0 )
 
-               IF( SCAN( TRIM(fct_concat(cg_com(:))) ,cl_line(1:1)) == 0 )THEN
+               IF( SCAN( TRIM(fct_concat(cp_com(:))) ,cl_line(1:1)) == 0 )THEN
                   tg_varextra(ji)%i_id      = ji
                   tg_varextra(ji)%c_name    =TRIM(fct_split(cl_line,1))
@@ -5996,28 +6451,28 @@
 
    END SUBROUTINE var_def_extra
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !> This subroutine add variable information get from namelist in 
-   !> global table of variable structure with extra information :tg_varextra.
+   !> global array of variable structure with extra information: tg_varextra.
    !> 
    !> @details 
-   !> string character format must be : "varname:interp|filter|extrap"
+   !> string character format must be : <br/>
+   !> "varname:interp; filter; extrap; > min; < max"<br/>
    !> you could specify only interpolation, filter or extrapolation method, 
-   !> or two whatever the order. you could find more
-   !> information about available method in interpolation, filter, and
-   !> extrapolation module. Here you cuold find some exemples: 
-   !> cn_varinfo='Bathymetry:2*hamming(2,3)'
-   !> cn_varinfo='votemper:cubic|dist_weight'
-   !>
-   !> @note If you do not specify one method which is required, default one is
+   !> whatever the order. you could find more
+   !> information about available method in \ref interp, \ref filter, and
+   !> \ref extrap module.<br/>
+   !> Examples: 
+   !> cn_varinfo='Bathymetry:2*hamming(2,3); > 10.'
+   !> cn_varinfo='votemper:cubic; dist_weight; <40.'
+   !>
+   !> @note If you do not specify a method which is required, default one is
    !> apply.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_varinfo : variable information from namelist
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_varinfo   variable information from namelist
+   !-------------------------------------------------------------------
    SUBROUTINE var_chg_extra( cd_varinfo )
       IMPLICIT NONE
@@ -6032,5 +6487,5 @@
       CHARACTER(LEN=lc), DIMENSION(5)              :: cl_filter
 
-      INTEGER(i4)                                  :: il_varid
+      INTEGER(i4)                                  :: il_ind
       INTEGER(i4)                                  :: il_nvar
 
@@ -6044,91 +6499,103 @@
       !----------------------------------------------------------------
 
-      ji=1
-      DO WHILE( TRIM(cd_varinfo(ji)) /= '' )
-
-         cl_name  =fct_lower(fct_split(cd_varinfo(ji),1,':'))
-         cl_method=fct_split(cd_varinfo(ji),2,':')
-
-         dl_min=var__get_min(cl_name, cl_method)
-         dl_max=var__get_max(cl_name, cl_method)
-         cl_interp(:)=var__get_interp(cl_name, cl_method)
-         cl_extrap(:)=var__get_extrap(cl_name, cl_method)
-         cl_filter(:)=var__get_filter(cl_name, cl_method)
-
-         il_varid=var_get_id(tg_varextra(:), TRIM(cl_name))
-         IF( il_varid /= 0 )THEN
-            IF( dl_min /= dg_fill ) tg_varextra(il_varid)%d_min=dl_min
-            IF( dl_max /= dg_fill ) tg_varextra(il_varid)%d_max=dl_max
-            IF(cl_interp(1)/='') tg_varextra(il_varid)%c_interp(:)=cl_interp(:)
-            IF(cl_extrap(1)/='') tg_varextra(il_varid)%c_extrap(:)=cl_extrap(:)
-            IF(cl_filter(1)/='') tg_varextra(il_varid)%c_filter(:)=cl_filter(:)
-         ELSE
-
-            IF( ALLOCATED(tg_varextra) )THEN
-               il_nvar=SIZE(tg_varextra(:))
-               ! save older variable
-               ALLOCATE( tl_varextra(il_nvar) )
-               tl_varextra(:)=tg_varextra(:)
-
-               DEALLOCATE(tg_varextra)
-               ALLOCATE( tg_varextra(il_nvar+1) )
-               
-               tg_varextra(1:il_nvar)=tl_varextra(:)
-               DEALLOCATE(tl_varextra)
-
+      IF( ALLOCATED(tg_varextra) )THEN
+         ji=1
+         DO WHILE( TRIM(cd_varinfo(ji)) /= '' )
+
+            cl_name  =fct_lower(fct_split(cd_varinfo(ji),1,':'))
+            cl_method=fct_split(cd_varinfo(ji),2,':')
+
+            dl_min=var__get_min(cl_name, cl_method)
+            dl_max=var__get_max(cl_name, cl_method)
+            cl_interp(:)=var__get_interp(cl_name, cl_method)
+            cl_extrap(:)=var__get_extrap(cl_name, cl_method)
+            cl_filter(:)=var__get_filter(cl_name, cl_method)
+
+            il_ind=var_get_index(tg_varextra(:), TRIM(cl_name))
+            IF( il_ind /= 0 )THEN
+               IF( dl_min /= dp_fill ) tg_varextra(il_ind)%d_min=dl_min
+               IF( dl_max /= dp_fill ) tg_varextra(il_ind)%d_max=dl_max
+               IF(cl_interp(1)/='') tg_varextra(il_ind)%c_interp(:)=cl_interp(:)
+               IF(cl_extrap(1)/='') tg_varextra(il_ind)%c_extrap(:)=cl_extrap(:)
+               IF(cl_filter(1)/='') tg_varextra(il_ind)%c_filter(:)=cl_filter(:)
             ELSE
 
-               il_varid=0
-               ALLOCATE( tg_varextra(1) )
+               IF( ALLOCATED(tg_varextra) )THEN
+                  il_nvar=SIZE(tg_varextra(:))
+                  ! save older variable
+                  ALLOCATE( tl_varextra(il_nvar) )
+                  tl_varextra(:)=var_copy(tg_varextra(:))
+
+                  CALL var_clean(tg_varextra(:))
+                  DEALLOCATE(tg_varextra)
+                  ALLOCATE( tg_varextra(il_nvar+1) )
+                  
+                  tg_varextra(1:il_nvar)=var_copy(tl_varextra(:))
+
+                  ! clean
+                  CALL var_clean(tl_varextra(:))
+                  DEALLOCATE(tl_varextra)
+
+               ELSE
+
+                  il_nvar=0
+                  ALLOCATE( tg_varextra(1) )
+
+               ENDIF
+
+               ! add new variable
+               il_ind=il_nvar+1
+               tg_varextra(il_ind)=var_init( TRIM(cl_name), &
+               &                               cd_interp=cl_interp(:), &
+               &                               cd_extrap=cl_extrap(:), &
+               &                               cd_filter=cl_filter(:), &
+               &                               dd_min = dl_min, &
+               &                               dd_max = dl_max )
 
             ENDIF
 
-            ! add new variable
-            il_varid=il_nvar+1
-            tg_varextra(il_varid)=var_init( TRIM(cl_name), &
-            &                               cd_interp=cl_interp(:), &
-            &                               cd_extrap=cl_extrap(:), &
-            &                               cd_filter=cl_filter(:), &
-            &                               dd_min = dl_min, &
-            &                               dd_max = dl_max )
-
-         ENDIF
-
-         ji=ji+1
-         CALL logger_trace( "VAR CHG EXTRA: name       "//&
-         &                  TRIM(tg_varextra(il_varid)%c_name) )
-         CALL logger_trace( "VAR CHG EXTRA: interp     "//&
-         &                  TRIM(tg_varextra(il_varid)%c_interp(1)) )         
-         CALL logger_trace( "VAR CHG EXTRA: filter     "//&
-         &                  TRIM(tg_varextra(il_varid)%c_filter(1)) )         
-         CALL logger_trace( "VAR CHG EXTRA: extrap     "//&
-         &                  TRIM(tg_varextra(il_varid)%c_extrap(1)) )
-         IF( tg_varextra(il_varid)%d_min /= dg_fill )THEN
-            CALL logger_trace( "VAR CHG EXTRA: min value  "//&
-            &                  TRIM(fct_str(tg_varextra(il_varid)%d_min)) )
-         ENDIF
-         IF( tg_varextra(il_varid)%d_max /= dg_fill )THEN
-            CALL logger_trace( "VAR CHG EXTRA: max value  "//&
-            &                  TRIM(fct_str(tg_varextra(il_varid)%d_max)) )
-         ENDIF
-      ENDDO
+            ji=ji+1
+            CALL logger_trace( "VAR CHG EXTRA: name       "//&
+            &                  TRIM(tg_varextra(il_ind)%c_name) )
+            CALL logger_trace( "VAR CHG EXTRA: interp     "//&
+            &                  TRIM(tg_varextra(il_ind)%c_interp(1)) )         
+            CALL logger_trace( "VAR CHG EXTRA: filter     "//&
+            &                  TRIM(tg_varextra(il_ind)%c_filter(1)) )         
+            CALL logger_trace( "VAR CHG EXTRA: extrap     "//&
+            &                  TRIM(tg_varextra(il_ind)%c_extrap(1)) )
+            IF( tg_varextra(il_ind)%d_min /= dp_fill )THEN
+               CALL logger_trace( "VAR CHG EXTRA: min value  "//&
+               &                  TRIM(fct_str(tg_varextra(il_ind)%d_min)) )
+            ENDIF
+            IF( tg_varextra(il_ind)%d_max /= dp_fill )THEN
+               CALL logger_trace( "VAR CHG EXTRA: max value  "//&
+               &                  TRIM(fct_str(tg_varextra(il_ind)%d_max)) )
+            ENDIF
+         ENDDO
+      ENDIF
 
    END SUBROUTINE var_chg_extra
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine read matrix value from character string
+   !> This subroutine read matrix value from character string in namelist
    !> and fill variable strucutre value.
-
-   !> @detail
-   !> 
-   !
+   !>
+   !> @details
+   !> to split matrix, separator use are:<br/>
+   !> - ',' for line
+   !> - '/' for row
+   !> - '\' for level<br/>
+   !> Example:<br/>
+   !> 3,2,3/1,4,5  => 
+   !> @f$ \left( \begin{array}{ccc}
+   !> 3 & 2 & 3 \\
+   !> 1 & 4 & 5 \end{array} \right) @f$
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !> @param[in] cd_matrix : matrix value
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !> @param[in] cd_matrix matrix value
+   !-------------------------------------------------------------------
    SUBROUTINE var_read_matrix(td_var, cd_matrix)
       IMPLICIT NONE
@@ -6138,5 +6605,5 @@
 
       ! local variable
-      CHARACTER(LEN=lc)                                  :: cl_table
+      CHARACTER(LEN=lc)                                  :: cl_array
       CHARACTER(LEN=lc)                                  :: cl_line
       CHARACTER(LEN=lc)                                  :: cl_elt
@@ -6158,13 +6625,13 @@
 
          !1- read matrix
-         ALLOCATE( dl_matrix(ig_maxmtx, ig_maxmtx, ig_maxmtx) )
+         ALLOCATE( dl_matrix(ip_maxmtx, ip_maxmtx, ip_maxmtx) )
          dl_matrix(:,:,:)=td_var%d_fill
 
          jk=1
-         cl_table=fct_split(TRIM(cd_matrix),jk,'\ ')
-         CALL logger_debug("VAR MATRIX table "//TRIM(cl_table) )
-         DO WHILE( TRIM(cl_table) /= '' )
+         cl_array=fct_split(TRIM(cd_matrix),jk,'\ ')
+         CALL logger_debug("VAR MATRIX array "//TRIM(cl_array) )
+         DO WHILE( TRIM(cl_array) /= '' )
             jj=1
-            cl_line=fct_split(TRIM(cl_table),jj,'/')
+            cl_line=fct_split(TRIM(cl_array),jj,'/')
             CALL logger_debug("VAR MATRIX line "//TRIM(cl_line) )
             DO WHILE( TRIM(cl_line) /= '' )
@@ -6179,10 +6646,10 @@
                ENDDO
                jj=jj+1
-               cl_line=fct_split(TRIM(cl_table),jj,'/')
+               cl_line=fct_split(TRIM(cl_array),jj,'/')
                CALL logger_debug("VAR MATRIX line "//TRIM(cl_line) )
             ENDDO
             jk=jk+1
-            cl_table=fct_split(TRIM(cd_matrix),jk,'\ ')
-            CALL logger_debug("VAR MATRIX table "//TRIM(cl_table) )
+            cl_array=fct_split(TRIM(cd_matrix),jk,'\ ')
+            CALL logger_debug("VAR MATRIX array "//TRIM(cl_array) )
          ENDDO
 
@@ -6200,9 +6667,10 @@
          
          CALL var_add_dim(td_var, tl_dim(:))
+         ! clean
          CALL dim_clean(tl_dim)
          DEALLOCATE( tl_dim )
 
          IF( ASSOCIATED(td_var%d_value) ) DEALLOCATE(td_var%d_value)
-         CALL var_add_value(td_var, dl_value(:,:,:,:))
+         CALL var_add_value(td_var, dl_value(:,:,:,:), id_type=NF90_FLOAT)
 
          DEALLOCATE( dl_value )
@@ -6210,17 +6678,17 @@
 
    END SUBROUTINE var_read_matrix
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine add extra information in variable structure
+   !> This subroutine add extra information in variable structure.
    !> 
    !> @details 
-   !>
+   !> if variable name is informed in global array of variable structure (tg_varextra).
+   !> fill empty parameter on variable structure.
+   !> 
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !>
+   !> @param[inout] td_var variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE var__get_extra( td_var )
       IMPLICIT NONE
@@ -6229,5 +6697,5 @@
 
       ! local variable
-      INTEGER(i4)       :: il_varid
+      INTEGER(i4)       :: il_ind
       TYPE(TATT)        :: tl_att
 
@@ -6237,18 +6705,20 @@
       IF( ALLOCATED(tg_varextra) )THEN
 
-         il_varid=var_get_id( tg_varextra(:), TRIM(td_var%c_name),  &
-                                              TRIM(td_var%c_stdname))
-         IF( il_varid /= 0 )THEN
+         il_ind=var_get_index( tg_varextra(:), TRIM(td_var%c_name),  &
+                                               TRIM(td_var%c_stdname))
+         IF( il_ind /= 0 )THEN
 
             ! name
             IF( TRIM(td_var%c_name) == '' .AND. &
-            &   TRIM(tg_varextra(il_varid)%c_name) /= '' )THEN
-               td_var%c_name=TRIM(tg_varextra(il_varid)%c_name)
+            &   TRIM(tg_varextra(il_ind)%c_name) /= '' )THEN
+               td_var%c_name=TRIM(tg_varextra(il_ind)%c_name)
             ENDIF
 
             ! standard name
-            IF( TRIM(td_var%c_stdname) == '' .AND. &
-            &   TRIM(tg_varextra(il_varid)%c_stdname) /= ''  )THEN
-               td_var%c_stdname=TRIM(tg_varextra(il_varid)%c_stdname)
+            IF( TRIM(tg_varextra(il_ind)%c_stdname) /= '' .AND. &
+            &   ( TRIM(td_var%c_stdname) == '' .OR. &
+            &     TRIM(tg_varextra(il_ind)%c_stdname) /= &
+            &     TRIM(td_var%c_stdname) ) )THEN
+               td_var%c_stdname=TRIM(tg_varextra(il_ind)%c_stdname)
                ! create attibute
                tl_att=att_init('standard_name',TRIM(td_var%c_stdname))
@@ -6257,9 +6727,11 @@
 
             ! long_name
-            IF( TRIM(td_var%c_longname) == '' .AND. &
-            &   TRIM(tg_varextra(il_varid)%c_longname) /= '' )THEN
-               td_var%c_longname=TRIM(tg_varextra(il_varid)%c_longname)
+            IF( TRIM(tg_varextra(il_ind)%c_longname) /= '' .AND. &
+            &   ( TRIM(td_var%c_longname) == '' .OR. &
+            &     TRIM(tg_varextra(il_ind)%c_longname) /= &
+            &     TRIM(td_var%c_longname) ) )THEN
+               td_var%c_longname=TRIM(tg_varextra(il_ind)%c_longname)
                ! create attibute
-               tl_att=att_init('long_name',TRIM(td_var%c_stdname))
+               tl_att=att_init('long_name',TRIM(td_var%c_longname))
                CALL var_move_att(td_var, tl_att)               
             ENDIF
@@ -6267,6 +6739,6 @@
             ! units
             IF( TRIM(td_var%c_units) == '' .AND. & 
-            &   TRIM(tg_varextra(il_varid)%c_units) /= '' )THEN
-               td_var%c_units=TRIM(tg_varextra(il_varid)%c_units)
+            &   TRIM(tg_varextra(il_ind)%c_units) /= '' )THEN
+               td_var%c_units=TRIM(tg_varextra(il_ind)%c_units)
                ! create attibute
                tl_att=att_init('units',TRIM(td_var%c_units))
@@ -6275,7 +6747,9 @@
 
             ! axis
-            IF( TRIM(td_var%c_axis) == '' .AND. & 
-            &   TRIM(tg_varextra(il_varid)%c_axis) /= '' )THEN
-               td_var%c_axis=TRIM(tg_varextra(il_varid)%c_axis)
+            IF( TRIM(tg_varextra(il_ind)%c_axis) /= '' .AND. &
+            &   ( TRIM(td_var%c_axis) == '' .OR. & 
+            &     TRIM(tg_varextra(il_ind)%c_axis) /= &
+            &     TRIM(td_var%c_axis) ) )THEN
+               td_var%c_axis=TRIM(tg_varextra(il_ind)%c_axis)
                ! create attibute
                tl_att=att_init('axis',TRIM(td_var%c_axis))
@@ -6284,12 +6758,16 @@
 
             ! grid point
-            IF( TRIM(td_var%c_point) == '' .AND. &
-            &   TRIM(tg_varextra(il_varid)%c_point) /= '' )THEN
-               td_var%c_point=TRIM(tg_varextra(il_varid)%c_point)
+            IF( TRIM(tg_varextra(il_ind)%c_point) /= '' .AND. &
+            &   ( TRIM(td_var%c_point) == '' .OR. &
+            &     TRIM(tg_varextra(il_ind)%c_point) /= &
+            &     TRIM(td_var%c_point) ) )THEN
+               td_var%c_point=TRIM(tg_varextra(il_ind)%c_point)
             ELSE
-               CALL logger_warn("VAR GET EXTRA: unknown grid point "//&
-               &  "for variable "//TRIM(td_var%c_name)//&
-               &  ". assume it is a T-point.")
-               td_var%c_point='T'
+               IF( TRIM(td_var%c_point) == '' )THEN
+                  CALL logger_warn("VAR GET EXTRA: unknown grid point "//&
+                  &  "for variable "//TRIM(td_var%c_name)//&
+                  &  ". assume it is a T-point.")
+                  td_var%c_point='T'
+               ENDIF
             ENDIF
             ! create attibute
@@ -6297,32 +6775,35 @@
             CALL var_move_att(td_var, tl_att)               
 
+            ! clean
+            CALL att_clean(tl_att)
+
             ! interp
             IF( TRIM(td_var%c_interp(1)) == '' .AND. &
-            &   TRIM(tg_varextra(il_varid)%c_interp(1)) /= '' )THEN
-               td_var%c_interp(:)=tg_varextra(il_varid)%c_interp(:)
+            &   TRIM(tg_varextra(il_ind)%c_interp(1)) /= '' )THEN
+               td_var%c_interp(:)=tg_varextra(il_ind)%c_interp(:)
             ENDIF
 
             ! extrap
             IF( TRIM(td_var%c_extrap(1)) == '' .AND. &
-            &   TRIM(tg_varextra(il_varid)%c_extrap(1)) /= '' )THEN
-               td_var%c_extrap(:)=tg_varextra(il_varid)%c_extrap(:)
+            &   TRIM(tg_varextra(il_ind)%c_extrap(1)) /= '' )THEN
+               td_var%c_extrap(:)=tg_varextra(il_ind)%c_extrap(:)
             ENDIF
 
             ! filter
             IF( TRIM(td_var%c_filter(1)) == '' .AND. &
-            &   TRIM(tg_varextra(il_varid)%c_filter(1)) /= '' )THEN
-               td_var%c_filter(:)=tg_varextra(il_varid)%c_filter(:)
+            &   TRIM(tg_varextra(il_ind)%c_filter(1)) /= '' )THEN
+               td_var%c_filter(:)=tg_varextra(il_ind)%c_filter(:)
             ENDIF            
 
             ! min value
-            IF( td_var%d_min == dg_fill .AND. &
-            &   tg_varextra(il_varid)%d_min /= dg_fill )THEN
-               td_var%d_min=tg_varextra(il_varid)%d_min
+            IF( td_var%d_min == dp_fill .AND. &
+            &   tg_varextra(il_ind)%d_min /= dp_fill )THEN
+               td_var%d_min=tg_varextra(il_ind)%d_min
             ENDIF
 
             ! max value
-            IF( td_var%d_max == dg_fill .AND. &
-            &   tg_varextra(il_varid)%d_max /= dg_fill )THEN
-               td_var%d_max=tg_varextra(il_varid)%d_max
+            IF( td_var%d_max == dp_fill .AND. &
+            &   tg_varextra(il_ind)%d_max /= dp_fill )THEN
+               td_var%d_max=tg_varextra(il_ind)%d_max
             ENDIF
 
@@ -6346,9 +6827,8 @@
 
    END SUBROUTINE var__get_extra
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !> This function check if variable information read in namelist contains 
-   !> minimum value and return it if true 
+   !> minimum value and return it if true. 
    !> 
    !> @details
@@ -6356,9 +6836,10 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_varinfo : variable information read in namelist 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_varinfo   variable information read in namelist 
+   !> @return minimum value to be used (FillValue if none)
+   !-------------------------------------------------------------------
    FUNCTION var__get_min( cd_name, cd_varinfo )
       IMPLICIT NONE
@@ -6381,5 +6862,5 @@
       ! init
       cl_min=''
-      var__get_min=dg_fill
+      var__get_min=dp_fill
 
       ji=1
@@ -6398,5 +6879,5 @@
          IF( fct_is_num(cl_min) )THEN
             READ(cl_min,*) var__get_min
-            CALL logger_info("VAR GET MIN: will use minimum value of "//&
+            CALL logger_debug("VAR GET MIN: will use minimum value of "//&
             &  TRIM(fct_str(var__get_min))//" for variable "//TRIM(cd_name) )
          ELSE
@@ -6407,9 +6888,8 @@
 
    END FUNCTION var__get_min
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !> This function check if variable information read in namelist contains 
-   !> maximum value and return it if true 
+   !> maximum value and return it if true. 
    !> 
    !> @details
@@ -6417,9 +6897,10 @@
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_varinfo : variable information read in namelist 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_varinfo   variable information read in namelist 
+   !> @return maximum value to be used (FillValue if none)
+   !-------------------------------------------------------------------
    FUNCTION var__get_max( cd_name, cd_varinfo )
       IMPLICIT NONE
@@ -6442,5 +6923,5 @@
       ! init
       cl_max=''
-      var__get_max=dg_fill
+      var__get_max=dp_fill
 
       ji=1
@@ -6459,5 +6940,5 @@
          IF( fct_is_num(cl_max) )THEN
             READ(cl_max,*) var__get_max
-            CALL logger_info("VAR GET MAX: will use maximum value of "//&
+            CALL logger_debug("VAR GET MAX: will use maximum value of "//&
             &  TRIM(fct_str(var__get_max))//" for variable "//TRIM(cd_name) )
          ELSE
@@ -6468,18 +6949,26 @@
 
    END FUNCTION var__get_max
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !> This function check if variable information read in namelist contains 
-   !> interpolation method and return it if true 
+   !> interpolation method and return it if true. 
    !> 
    !> @details 
+   !> split namelist information, using ';' as separator.
+   !> compare method name with the list of interpolation method available (see
+   !> module global).
+   !> check if factor (*rhoi, /rhoj..) are present.<br/>
+   !> Example:<br/> 
+   !> - cubic/rhoi ; dist_weight
+   !> - bilin
+   !> see @ref interp module for more information.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_varinfo : variable information read in namelist 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_varinfo   variable information read in namelist
+   !> @return array of character information about interpolation 
+   !-------------------------------------------------------------------
    FUNCTION var__get_interp( cd_name, cd_varinfo )
       IMPLICIT NONE
@@ -6511,10 +7000,10 @@
       cl_tmp=fct_split(cd_varinfo,ji,';')
       DO WHILE( TRIM(cl_tmp) /= '' )
-         DO jj=1,ig_ninterp
-            il_ind= INDEX(fct_lower(cl_tmp),TRIM(cg_interp_list(jj)))
+         DO jj=1,ip_ninterp
+            il_ind= INDEX(fct_lower(cl_tmp),TRIM(cp_interp_list(jj)))
             IF( il_ind /= 0 )THEN
 
-               var__get_interp(1)=TRIM(cg_interp_list(jj))
-               il_len=LEN(TRIM(cg_interp_list(jj)))
+               var__get_interp(1)=TRIM(cp_interp_list(jj))
+               il_len=LEN(TRIM(cp_interp_list(jj)))
                
                ! look for factor
@@ -6563,5 +7052,5 @@
             ENDIF
          ENDDO
-         IF( jj /= ig_ninterp + 1 ) EXIT
+         IF( jj /= ip_ninterp + 1 ) EXIT
          ji=ji+1
          cl_tmp=fct_split(cd_varinfo,ji,';')         
@@ -6569,18 +7058,25 @@
 
    END FUNCTION var__get_interp
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
    !> This function check if variable information read in namelist contains 
-   !> extrapolation method and return it if true 
+   !> extrapolation method and return it if true. 
    !> 
    !> @details 
+   !> split namelist information, using ';' as separator.
+   !> compare method name with the list of extrapolation method available (see
+   !> module global).<br/>
+   !> Example:<br/>
+   !> - cubic ; dist_weight
+   !> - min_error
+   !> see @ref extrap module for more information.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_varinfo : variable information read in namelist 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_varinfo   variable information read in namelist
+   !> @return array of character information about extrapolation
+   !-------------------------------------------------------------------
    FUNCTION var__get_extrap( cd_name, cd_varinfo )
       IMPLICIT NONE
@@ -6605,9 +7101,9 @@
       cl_tmp=fct_split(cd_varinfo,ji,';')
       DO WHILE( TRIM(cl_tmp) /= '' )
-         DO jj=1,ig_nextrap
-            IF( TRIM(fct_lower(cl_tmp)) == TRIM(cg_extrap_list(jj)) )THEN
-               var__get_extrap(1)=TRIM(cg_extrap_list(jj))
-
-               CALL logger_info("VAR GET EXTRAP: variable "//TRIM(cd_name)//&
+         DO jj=1,ip_nextrap
+            IF( TRIM(fct_lower(cl_tmp)) == TRIM(cp_extrap_list(jj)) )THEN
+               var__get_extrap(1)=TRIM(cp_extrap_list(jj))
+
+               CALL logger_trace("VAR GET EXTRAP: variable "//TRIM(cd_name)//&
                &  " will use extrapolation method "//TRIM(var__get_extrap(1)) )
 
@@ -6615,5 +7111,5 @@
             ENDIF
          ENDDO
-         IF( jj /= ig_nextrap + 1 ) EXIT
+         IF( jj /= ip_nextrap + 1 ) EXIT
          ji=ji+1
          cl_tmp=fct_split(cd_varinfo,ji,';')         
@@ -6622,5 +7118,4 @@
 
    END FUNCTION var__get_extrap
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
@@ -6629,11 +7124,20 @@
    !> 
    !> @details 
+   !> split namelist information, using ';' as separator.
+   !> compare method name with the list of filter method available (see
+   !> module global).
+   !> look for the number of turn, using '*' separator, and method parameters inside
+   !> bracket.<br/>
+   !> Example:<br/>
+   !> - cubic ; 2*hamming(2,3)
+   !> - hann
+   !> see @ref filter module for more information.
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] cd_varinfo : variable information read in namelist 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] cd_name      variable name
+   !> @param[in] cd_varinfo   variable information read in namelist 
+   !-------------------------------------------------------------------
    FUNCTION var__get_filter( cd_name, cd_varinfo )
       IMPLICIT NONE
@@ -6659,8 +7163,8 @@
       cl_tmp=fct_split(cd_varinfo,ji,';')
       DO WHILE( TRIM(cl_tmp) /= '' )
-         DO jj=1,ig_nfilter
-            il_ind=INDEX(fct_lower(cl_tmp),TRIM(cg_filter_list(jj)))
+         DO jj=1,ip_nfilter
+            il_ind=INDEX(fct_lower(cl_tmp),TRIM(cp_filter_list(jj)))
             IF( il_ind /= 0 )THEN
-               var__get_filter(1)=TRIM(cg_filter_list(jj))
+               var__get_filter(1)=TRIM(cp_filter_list(jj))
 
                ! look for number of turn
@@ -6711,5 +7215,5 @@
             ENDIF
          ENDDO
-         IF( jj /= ig_nfilter + 1 ) EXIT
+         IF( jj /= ip_nfilter + 1 ) EXIT
          ji=ji+1
          cl_tmp=fct_split(cd_varinfo,ji,';')         
@@ -6717,18 +7221,15 @@
 
    END FUNCTION var__get_filter
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief 
    !> This function search and save the biggest dimensions use 
-   !> in those variables.
-   !>
-   !
+   !> in an array of variable structure.
+   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] td_var : table of variable structure
-   !> @return table of dimension 
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[in] td_var array of variable structure
+   !> @return array of dimension 
+   !-------------------------------------------------------------------
    FUNCTION var_max_dim(td_var)
       IMPLICIT NONE
@@ -6749,44 +7250,43 @@
       il_nvar=SIZE(td_var(:))
                           
-      var_max_dim(:)=td_var(1)%t_dim(:)
-
-      DO ji=2,il_nvar     
-                          
-         IF( td_var(ji)%t_dim(1)%l_use .AND. &
-         &   td_var(ji)%t_dim(1)%i_len >= var_max_dim(1)%i_len )THEN
-            var_max_dim(1)=td_var(ji)%t_dim(1)
-         ENDIF            
-                          
-         IF( td_var(ji)%t_dim(2)%l_use .AND. &
-         &   td_var(ji)%t_dim(2)%i_len >= var_max_dim(2)%i_len )THEN 
-            var_max_dim(2)=td_var(ji)%t_dim(2)
-         ENDIF            
-                          
-         IF( td_var(ji)%t_dim(3)%l_use .AND. &
-         &   td_var(ji)%t_dim(3)%i_len >= var_max_dim(3)%i_len )THEN 
-            var_max_dim(3)=td_var(ji)%t_dim(3)
-         ENDIF            
-                          
-         IF( td_var(ji)%t_dim(4)%l_use .AND. &
-         &   td_var(ji)%t_dim(4)%i_len >= var_max_dim(4)%i_len )THEN
-            var_max_dim(4)=td_var(ji)%t_dim(4)
-         ENDIF
-
-      ENDDO
+      var_max_dim(:)=dim_copy(td_var(1)%t_dim(:))
+
+      IF( il_nvar > 1 )THEN
+         DO ji=2,il_nvar     
+                             
+            IF( td_var(ji)%t_dim(1)%l_use .AND. &
+            &   td_var(ji)%t_dim(1)%i_len >= var_max_dim(1)%i_len )THEN
+               var_max_dim(1)=dim_copy(td_var(ji)%t_dim(1))
+            ENDIF            
+                             
+            IF( td_var(ji)%t_dim(2)%l_use .AND. &
+            &   td_var(ji)%t_dim(2)%i_len >= var_max_dim(2)%i_len )THEN 
+               var_max_dim(2)=dim_copy(td_var(ji)%t_dim(2))
+            ENDIF            
+                             
+            IF( td_var(ji)%t_dim(3)%l_use .AND. &
+            &   td_var(ji)%t_dim(3)%i_len >= var_max_dim(3)%i_len )THEN 
+               var_max_dim(3)=dim_copy(td_var(ji)%t_dim(3))
+            ENDIF            
+                             
+            IF( td_var(ji)%t_dim(4)%l_use .AND. &
+            &   td_var(ji)%t_dim(4)%i_len >= var_max_dim(4)%i_len )THEN
+               var_max_dim(4)=dim_copy(td_var(ji)%t_dim(4))
+            ENDIF
+
+         ENDDO
+      ENDIF
 
    END FUNCTION var_max_dim
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine forced minimum and maximum value of variable.
+   !> This subroutine forced minimum and maximum value of variable,
+   !> with value of variable structure attribute d_min and d_max.
    !> 
-   !> @details 
-   !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE var_limit_value( td_var )
       IMPLICIT NONE
@@ -6801,5 +7301,5 @@
       IF( ASSOCIATED(td_var%d_value) )THEN
          !1- forced minimum value
-         IF( td_var%d_min /= dg_fill )THEN
+         IF( td_var%d_min /= dp_fill )THEN
             WHERE( td_var%d_value(:,:,:,:) /= td_var%d_fill .AND. &
                &   td_var%d_value(:,:,:,:) <  td_var%d_min )
@@ -6809,5 +7309,5 @@
 
          !2- forced maximum value 
-         IF( td_var%d_max /= dg_fill )THEN
+         IF( td_var%d_max /= dp_fill )THEN
             WHERE( td_var%d_value(:,:,:,:) /= td_var%d_fill .AND. &
                &   td_var%d_value(:,:,:,:) >  td_var%d_max )
@@ -6819,17 +7319,18 @@
 
    END SUBROUTINE var_limit_value
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief
-   !> This subroutine forced minimum and maximum value of variable.
+   !> This subroutine check variable dimension expected, as defined in
+   !> file 'variable.cfg'.
    !> 
    !> @details 
+   !> compare dimension used in variable structure with string character
+   !> axis from configuration file. 
    !>
    !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[inout] td_var : variable structure
-   !-------------------------------------------------------------------
-   !> @code
+   !> - November, 2013- Initial Version
+   !
+   !> @param[inout] td_var    variable structure
+   !-------------------------------------------------------------------
    SUBROUTINE var_check_dim( td_var )
       IMPLICIT NONE
@@ -6879,13 +7380,17 @@
             CALL logger_warn("VAR CHECK DIM: too much dimension for "//&
             &                "variable "//TRIM(td_var%c_name)//".")
+            cl_dim=TRIM(fct_upper(cp_dimorder))
+            il_ndim =LEN( TRIM(ADJUSTL(cl_dim)) )
             DO ji=1,il_ndim 
                IF( INDEX(TRIM(td_var%c_axis),cl_dim(ji:ji)) == 0 )THEN
-                  IF( td_var%t_dim(ji)%i_len == 1 )THEN
-                     ! remove unuseful dimension
-                     CALL var_del_dim(td_var,td_var%t_dim(ji))
-                  ELSE
-                     CALL logger_warn("VAR CHECK DIM: variable "//&
-                     &           TRIM(td_var%c_name)//" should not use"//&
-                     &           " dimension "//TRIM(td_var%t_dim(ji)%c_name))
+                  IF( td_var%t_dim(ji)%l_use )THEN
+                     IF( td_var%t_dim(ji)%i_len == 1 )THEN
+                        ! remove unuseful dimension
+                        CALL var_del_dim(td_var,td_var%t_dim(ji))
+                     ELSE
+                        CALL logger_warn("VAR CHECK DIM: variable "//&
+                        &           TRIM(td_var%c_name)//" should not use"//&
+                        &           " dimension "//TRIM(td_var%t_dim(ji)%c_name))
+                     ENDIF
                   ENDIF
                ENDIF
@@ -6898,5 +7403,154 @@
 
    END SUBROUTINE var_check_dim
-   !> @endcode
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This subroutine reshape variable value and dimension 
+   !> in variable structure.
+   !> @details
+   !> output dimension will be ordered as defined in 
+   !> input array of dimension
+   !> Optionaly you could specify output dimension order with
+   !> string character of dimension
+   !> 
+   !> @author J.Paul
+   !> - August, 2014- Initial Version
+   !
+   !> @param[inout] td_var       variable structure
+   !> @param[in]    cd_dimorder  string character of dimension order to be used
+   !-------------------------------------------------------------------
+   SUBROUTINE var_reorder( td_var, cd_dimorder )
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR)              , INTENT(INOUT) :: td_var
+      CHARACTER(LEN=ip_maxdim), INTENT(IN   ), OPTIONAL :: cd_dimorder
+
+      ! local variable
+      CHARACTER(LEN=lc)                             :: cl_dimorder
+
+      REAL(dp)  , DIMENSION(:,:,:,:)  , ALLOCATABLE :: dl_value
+
+      TYPE(TDIM), DIMENSION(ip_maxdim)              :: tl_dim
+
+      ! loop indices
+      !----------------------------------------------------------------
+
+      cl_dimorder=TRIM(cp_dimorder)
+      IF( PRESENT(cd_dimorder) ) cl_dimorder=TRIM(ADJUSTL(cd_dimorder))
+
+      tl_dim(:)=dim_copy(td_var%t_dim(:))
+
+      CALL dim_unorder(tl_dim(:))
+      CALL dim_reorder(tl_dim(:),TRIM(cl_dimorder))
+
+      ALLOCATE(dl_value(tl_dim(1)%i_len, &
+      &                 tl_dim(2)%i_len, &
+      &                 tl_dim(3)%i_len, &
+      &                 tl_dim(4)%i_len ))
+
+      dl_value(:,:,:,:)=dim_reshape_2xyzt(tl_dim, &
+      &                                   td_var%d_value(:,:,:,:))
+
+      ! change dimension
+      td_var%t_dim(:)=dim_copy(tl_dim(:))
+      ! change value
+      DEALLOCATE( td_var%d_value )
+      CALL var_add_value(td_var, dl_value(:,:,:,:))
+
+      ! clean
+      DEALLOCATE(dl_value)
+      CALL dim_clean(tl_dim(:))
+
+   END SUBROUTINE var_reorder
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This function get the next unused unit in array of variable structure. 
+   !> 
+   !> @author J.Paul
+   !> - September, 2014- Initial Version
+   !
+   !> @param[in] td_var array of variable structure 
+   !> @return free variable id
+   !-------------------------------------------------------------------
+   FUNCTION var_get_unit(td_var)
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR), DIMENSION(:), INTENT(IN) :: td_var
+
+      ! function
+      INTEGER(i4) :: var_get_unit
+
+      ! local variable
+      ! loop indices
+      !----------------------------------------------------------------
+
+      var_get_unit=MAXVAL(td_var(:)%i_id)+1
+
+   END FUNCTION var_get_unit
+   !-------------------------------------------------------------------
+   !> @brief
+   !> This function convert a time variable structure in date structure. 
+   !> 
+   !> @author J.Paul
+   !> - November, 2014- Initial Version
+   !
+   !> @param[in] td_var time variable structure 
+   !> @return date structure
+   !-------------------------------------------------------------------
+   FUNCTION var_to_date(td_var)
+      IMPLICIT NONE
+      ! Argument
+      TYPE(TVAR), INTENT(IN) :: td_var
+
+      ! function
+      TYPE(TDATE) :: var_to_date
+
+      ! local variable
+      CHARACTER(LEN=lc) :: cl_step
+      CHARACTER(LEN=lc) :: cl_date
+
+      INTEGER(i4) :: il_attid
+
+      INTEGER(i8) :: kl_nsec
+
+      TYPE(TDATE) :: tl_dateo
+      ! loop indices
+      !----------------------------------------------------------------
+
+      IF( INDEX(TRIM(td_var%c_name),'time') /= 0 )THEN
+         IF( ASSOCIATED(td_var%d_value) )THEN
+
+            il_attid=att_get_index(td_var%t_att(:),'units')
+            IF( il_attid /=0 )THEN
+               cl_step=fct_split(td_var%t_att(il_attid)%c_value,1,'since')
+               cl_date=fct_split(td_var%t_att(il_attid)%c_value,2,'since')
+
+               SELECT CASE(TRIM(cl_step))
+                  CASE('seconds')
+                     kl_nsec=INT(td_var%d_value(1,1,1,1),i8)
+                  CASE('days')
+                     kl_nsec=INT(td_var%d_value(1,1,1,1)*86400,i8)
+                  CASE DEFAULT
+                     CALL logger_error("VAR TO DATE: unknown units format "//&
+                     &  "in variable "//TRIM(td_var%c_name))
+               END SELECT
+
+               tl_dateo=date_init(cl_date)
+
+               var_to_date=date_init(kl_nsec,tl_dateo)
+
+            ELSE
+               CALL logger_error("VAR TO DATE: no attribute units in "//&
+               &  "variable "//TRIM(td_var%c_name))
+            ENDIF
+         ELSE
+            CALL logger_error("VAR TO DATE: no value associated to "//&
+            &  "variable "//TRIM(td_var%c_name))
+         ENDIF
+      ELSE
+         CALL logger_error("VAR TO DATE: variable "//TRIM(td_var%c_name)//&
+         &  "can not be convert in date.")
+      ENDIF
+
+   END FUNCTION var_to_date
 END MODULE var
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/vgrid.f90
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/vgrid.f90	(revision 5074)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/src/vgrid.f90	(revision 5075)
@@ -6,32 +6,87 @@
 !
 ! DESCRIPTION:
-!> @brief vertical grid manager <br/>
+!> @brief This module manage vertical grid.
 !>
 !> @details
+!>    to set the depth of model levels and the resulting vertical scale
+!> factors:<br/>
+!> @code
+!>    CALL vgrid_zgr_z(dd_gdepw(:), dd_gdept(:), dd_e3w(:), dd_e3t(:), 
+!>                     dd_ppkth, dd_ppkth2, dd_ppacr, dd_ppacr2, 
+!>                     dd_ppdzmin, dd_pphmax, dd_pp_to_be_computed, 
+!>                     dd_ppa0, dd_ppa1, dd_ppa2, dd_ppsur)
+!> @endcode
+!>       - dd_gdepw is array of depth value on W point
+!>       - dd_gdept is array of depth value on T point
+!>       - dd_e3w   is array of vertical mesh size on W point
+!>       - dd_e3t   is array of vertical mesh size on T point
+!>       - dd_ppkth              see NEMO documentation
+!>       - dd_ppkth2             see NEMO documentation
+!>       - dd_ppacr              see NEMO documentation
+!>       - dd_ppdzmin            see NEMO documentation
+!>       - dd_pphmax             see NEMO documentation
+!>       - dd_pp_to_be_computed  see NEMO documentation
+!>       - dd_ppa1               see NEMO documentation
+!>       - dd_ppa2               see NEMO documentation
+!>       - dd_ppa0               see NEMO documentation
+!>       - dd_ppsur              see NEMO documentation
+!>    
 !> 
+!>    to set the depth and vertical scale factor in partial step z-coordinate
+!>  case:<br/>
+!> @code
+!>    CALL vgrid_zgr_zps(id_mbathy(:,:), dd_bathy(:,:), id_jpkmax, dd_gdepw(:), 
+!>                       dd_e3t(:), dd_e3zps_min, dd_e3zps_rat)
+!> @endcode
+!>       - id_mbathy is array of bathymetry level
+!>       - dd_bathy  is array of bathymetry
+!>       - id_jpkmax is the maximum number of level to be used
+!>       - dd_gdepw  is array of vertical mesh size on W point
+!>       - dd_e3t    is array of vertical mesh size on T point
+!>       - dd_e3zps_min    see NEMO documentation
+!>       - dd_e3zps_rat    see NEMO documentation
+!>
+!>    to check the bathymetry in levels:<br/>
+!> @code
+!>    CALL vgrid_zgr_bat_ctl(id_mbathy, id_jpkmax, id_jpk)
+!> @endcode
+!>       - id_mbathy is array of bathymetry level
+!>       - id_jpkmax is the maximum number of level to be used
+!>       - id_jpk    is the number of level
+!>   
+!>    to compute bathy level in T,U,V,F point from  Bathymetry file:<br/>
+!> @code
+!>    tl_level(:)=vgrid_get_level(td_bathy, [cd_namelist,] [td_dom,] [id_nlevel])
+!> @endcode
+!>       - td_bathy is Bathymetry file structure
+!>       - cd_namelist is namelist [optional]
+!>       - td_dom is domain structure [optional]
+!>       - id_nlevel is number of lelvel to be used [optional]
+!>    
 !> @author
 !> J.Paul
 ! REVISION HISTORY:
-!> @date Nov, 2013 - Initial Version
-!
+!> @date November, 2013 - Initial Version
+!> @date Spetember, 2014
+!> - add header
+!>
 !> @note Software governed by the CeCILL licence     (NEMOGCM/NEMO_CeCILL.txt)
-!> @todo
 !----------------------------------------------------------------------
 MODULE vgrid
-   USE netcdf
+   USE netcdf                          ! nf90 library
    USE kind                            ! F90 kind parameter
    USE fct                             ! basic usefull function
    USE global                          ! global parameter
    USE phycst                          ! physical constant
-   USE logger                             ! log file manager
+   USE logger                          ! log file manager
    USE file                            ! file manager
    USE var                             ! variable manager
    USE dim                             ! dimension manager
    USE dom                             ! domain manager
+   USE grid                            ! grid manager
    USE iom                             ! I/O manager
    USE mpp                             ! MPP manager
    USE iom_mpp                         ! I/O MPP manager
    IMPLICIT NONE
-   PRIVATE
    ! NOTE_avoid_public_variables_if_possible
 
@@ -43,7 +98,4 @@
    PUBLIC :: vgrid_zgr_bat_ctl
    PUBLIC :: vgrid_get_level
-
-!   PRIVATE :: 
-
 
 CONTAINS
@@ -86,5 +138,4 @@
    !> @param[in] dd_ppsur
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE vgrid_zgr_z( dd_gdepw, dd_gdept, dd_e3w, dd_e3t,          &
    &                       dd_ppkth, dd_ppkth2, dd_ppacr, dd_ppacr2,    &
@@ -218,5 +269,4 @@
 
    END SUBROUTINE vgrid_zgr_z
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine set the depth and vertical scale factor in partial step
@@ -231,21 +281,22 @@
    !>      function the derivative of which gives the reference vertical
    !>      scale factors.
-   !>        From  depth and scale factors reference, we compute there new value
+   !>      From  depth and scale factors reference, we compute there new value
    !>      with partial steps  on 3d arrays ( i, j, k ).
    !>
-   !>              w-level: gdepw_ps(i,j,k)  = fsdep(k)
-   !>                       e3w_ps(i,j,k) = dk(fsdep)(k)     = fse3(i,j,k)
-   !>              t-level: gdept_ps(i,j,k)  = fsdep(k+0.5)
-   !>                       e3t_ps(i,j,k) = dk(fsdep)(k+0.5) = fse3(i,j,k+0.5)
-   !>
-   !>        With the help of the bathymetric file ( bathymetry_depth_ORCA_R2.nc),
+   !>      w-level: 
+   !>          - gdepw_ps(i,j,k)  = fsdep(k)
+   !>          - e3w_ps(i,j,k) = dk(fsdep)(k)     = fse3(i,j,k)
+   !>      t-level: 
+   !>          - gdept_ps(i,j,k)  = fsdep(k+0.5)
+   !>          - e3t_ps(i,j,k) = dk(fsdep)(k+0.5) = fse3(i,j,k+0.5)
+   !>
+   !>      With the help of the bathymetric file ( bathymetry_depth_ORCA_R2.nc),
    !>      we find the mbathy index of the depth at each grid point.
    !>      This leads us to three cases:
-   !>
-   !>              - bathy = 0 => mbathy = 0
-   !>              - 1 < mbathy < jpkm1    
-   !>              - bathy > gdepw(jpk) => mbathy = jpkm1  
-   !>
-   !>        Then, for each case, we find the new depth at t- and w- levels
+   !>          - bathy = 0 => mbathy = 0
+   !>          - 1 < mbathy < jpkm1    
+   !>          - bathy > gdepw(jpk) => mbathy = jpkm1  
+   !>
+   !>      Then, for each case, we find the new depth at t- and w- levels
    !>      and the new vertical scale factors at t-, u-, v-, w-, uw-, vw- 
    !>      and f-points.
@@ -257,6 +308,7 @@
    !>      schemes.
    !>
-   !>         c a u t i o n : gdept, gdepw and e3 are positives
-   !>         - - - - - - -   gdept_ps, gdepw_ps and e3_ps are positives
+   !>  @warning 
+   !>         - gdept, gdepw and e3 are positives
+   !>         - gdept_ps, gdepw_ps and e3_ps are positives
    !
    !> @author A. Bozec, G. Madec
@@ -274,5 +326,4 @@
    !> @param[in] dd_e3zps_rat
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE vgrid_zgr_zps( id_mbathy, dd_bathy, id_jpkmax, &
    &                         dd_gdepw, dd_e3t,               &
@@ -362,5 +413,4 @@
 
    END SUBROUTINE vgrid_zgr_zps
-   !> @endcode
    !-------------------------------------------------------------------
    !> @brief This subroutine check the bathymetry in levels 
@@ -386,7 +436,8 @@
    !> - 03-08 Original code
    !
-   !> @param[in] 
+   !> @param[in] id_mbathy 
+   !> @param[in] id_jpkmax
+   !> @param[in] id_jpk
    !-------------------------------------------------------------------
-   !> @code
    SUBROUTINE vgrid_zgr_bat_ctl( id_mbathy, id_jpkmax, id_jpk)
       IMPLICIT NONE
@@ -477,38 +528,39 @@
 
    END SUBROUTINE vgrid_zgr_bat_ctl
-   !> @endcode
    !-------------------------------------------------------------------
-   !> @brief This function 
+   !> @brief This function compute bathy level in T,U,V,F point, and return 
+   !> them as array of variable structure
    !
    !> @details
+   !> Bathymetry is read on Bathymetry file, then bathy level is computed 
+   !> on T point, and finally fit to U,V,F point.
+   !>
+   !> you could specify :<br/>
+   !> - namelist where find parameter to set the depth of model levels
+   !> (default use GLORYS 75 levels parameters)
+   !> - domain structure to specify on e area to work on
+   !> - number of level to be used
+   !>
+   !> @author J.Paul
+   !> - November, 2013- Initial Version
    !
-   !> @author J.Paul
-   !> - Nov, 2013- Initial Version
-   !
-   !> @param[in] 
+   !> @param[in] td_bathy     Bathymetry file structure 
+   !> @param[in] cd_namelist  namelist 
+   !> @param[in] td_dom       domain structure
+   !> @param[in] id_nlevel    number of lelvel to be used 
+   !> @return array of level on T,U,V,F point (variable structure)
    !-------------------------------------------------------------------
-   !> @code
    FUNCTION vgrid_get_level(td_bathy, cd_namelist, td_dom, id_nlevel)
       IMPLICIT NONE
       ! Argument
-      TYPE(TFILE)     , INTENT(IN) :: td_bathy
-      CHARACTER(LEN=*), INTENT(IN) :: cd_namelist
+      TYPE(TMPP)      , INTENT(IN) :: td_bathy
+      CHARACTER(LEN=*), INTENT(IN), OPTIONAL :: cd_namelist
       TYPE(TDOM)      , INTENT(IN), OPTIONAL :: td_dom
       INTEGER(i4)     , INTENT(IN), OPTIONAL :: id_nlevel
 
       ! function
-      TYPE(TVAR), DIMENSION(ig_npoint) :: vgrid_get_level
+      TYPE(TVAR), DIMENSION(ip_npoint) :: vgrid_get_level
 
       ! local variable
-      TYPE(TFILE) :: tl_bathy
-      TYPE(TMPP)  :: tl_mppbathy
-
-      TYPE(TDOM)  :: tl_dom
-
-      TYPE(TVAR)  :: tl_var
-      TYPE(TVAR) , DIMENSION(ig_npoint)            :: tl_level
-
-      TYPE(TDIM) , DIMENSION(ip_maxdim)            :: tl_dim
-
       REAL(dp)   , DIMENSION(:)      , ALLOCATABLE :: dl_gdepw 
       REAL(dp)   , DIMENSION(:)      , ALLOCATABLE :: dl_gdept 
@@ -519,8 +571,17 @@
       INTEGER(i4)                                  :: il_fileid
       INTEGER(i4)                                  :: il_jpkmax
+      INTEGER(i4), DIMENSION(2,2)                  :: il_xghost
       INTEGER(i4), DIMENSION(:,:)    , ALLOCATABLE :: il_mbathy
       INTEGER(i4), DIMENSION(:,:,:,:), ALLOCATABLE :: il_level
       
       LOGICAL                                      :: ll_exist
+
+      TYPE(TDIM) , DIMENSION(ip_maxdim)            :: tl_dim
+
+      TYPE(TDOM)                                   :: tl_dom
+
+      TYPE(TVAR)                                   :: tl_var
+
+      TYPE(TMPP)                                   :: tl_bathy
 
       ! loop indices
@@ -567,62 +628,60 @@
       !----------------------------------------------------------------
 
-      !1- read namelist
-      INQUIRE(FILE=TRIM(cd_namelist), EXIST=ll_exist)
-      IF( ll_exist )THEN
+      IF( PRESENT(cd_namelist) )THEN
+         !1- read namelist
+         INQUIRE(FILE=TRIM(cd_namelist), EXIST=ll_exist)
+         IF( ll_exist )THEN
  
-         il_fileid=fct_getunit()
-
-         OPEN( il_fileid, FILE=TRIM(cd_namelist), &
-         &                FORM='FORMATTED',       &
-         &                ACCESS='SEQUENTIAL',    &
-         &                STATUS='OLD',           &
-         &                ACTION='READ',          &
-         &                IOSTAT=il_status)
-         CALL fct_err(il_status)
-         IF( il_status /= 0 )THEN
-            CALL logger_fatal("VGRID GET LEVEL: ERROR opening "//TRIM(cd_namelist))
+            il_fileid=fct_getunit()
+
+            OPEN( il_fileid, FILE=TRIM(cd_namelist), &
+            &                FORM='FORMATTED',       &
+            &                ACCESS='SEQUENTIAL',    &
+            &                STATUS='OLD',           &
+            &                ACTION='READ',          &
+            &                IOSTAT=il_status)
+            CALL fct_err(il_status)
+            IF( il_status /= 0 )THEN
+               CALL logger_fatal("VGRID GET LEVEL: ERROR opening "//&
+               &  TRIM(cd_namelist))
+            ENDIF
+
+            READ( il_fileid, NML = namzgr )
+            READ( il_fileid, NML = namzps )
+
+            CLOSE( il_fileid, IOSTAT=il_status )
+            CALL fct_err(il_status)
+            IF( il_status /= 0 )THEN
+               CALL logger_error("VGRID GET LEVELL: ERROR closing "//&
+               &  TRIM(cd_namelist))
+            ENDIF
+
+         ELSE
+
+            CALL logger_fatal("VGRID GET LEVEL: ERROR. can not find "//&
+            &  TRIM(cd_namelist))
+
          ENDIF
-
-         READ( il_fileid, NML = namzgr )
-         READ( il_fileid, NML = namzps )
-
-         CLOSE( il_fileid, IOSTAT=il_status )
-         CALL fct_err(il_status)
-         IF( il_status /= 0 )THEN
-            CALL logger_error("VGRID GET LEVELL: ERROR closing "//TRIM(cd_namelist))
-         ENDIF
-
+      ENDIF
+
+      ! copy structure
+      tl_bathy=mpp_copy(td_bathy)
+
+      ! get domain
+      IF( PRESENT(td_dom) )THEN
+         tl_dom=dom_copy(td_dom)
       ELSE
-
-         CALL logger_fatal("VGRID GET LEVEL: ERROR. can not find "//TRIM(cd_namelist))
-
-      ENDIF
-
-      !2- open files
-      tl_bathy=td_bathy
-      !2-1 get domain
-      IF( PRESENT(td_dom) )THEN
-         tl_dom=td_dom
-      ELSE
-         CALL iom_open(tl_bathy)
-
          CALL logger_debug("VGRID GET LEVEL: get dom from "//&
          &  TRIM(tl_bathy%c_name))
          tl_dom=dom_init(tl_bathy)
-
-         CALL iom_close(tl_bathy)
       ENDIF
 
-      !2-2 open mpp 
-      tl_mppbathy=mpp_init(tl_bathy)
-      CALL file_clean(tl_bathy)
-
-      !2-3 get processor to be used
-      CALL mpp_get_use( tl_mppbathy, tl_dom )
-
-      !2-4 open mpp files
-      CALL iom_mpp_open(tl_mppbathy)
-
-      !3- check namelist
+      ! get ghoste cell
+      il_xghost(:,:)=grid_get_ghost(tl_bathy)
+
+      ! open mpp files
+      CALL iom_dom_open(tl_bathy, tl_dom)
+
+      ! check namelist
       IF( PRESENT(id_nlevel) ) in_nlevel=id_nlevel
       IF( in_nlevel == 0 )THEN
@@ -631,16 +690,22 @@
       ENDIF
 
-      !4- read bathymetry
-      tl_var=iom_mpp_read_var(tl_mppbathy,'bathymetry',td_dom=tl_dom)
-
+      ! read bathymetry
+      tl_var=iom_dom_read_var(tl_bathy,'bathymetry',tl_dom)
+      ! clean
+      CALL dom_clean(tl_dom)
+
+      ! remove ghost cell
+      CALL grid_del_ghost(tl_var, il_xghost(:,:))
+
+      ! force _FillValue (land) to be 0
       WHERE( tl_var%d_value(:,:,1,1) == tl_var%d_fill )
          tl_var%d_value(:,:,1,1)=0
       END WHERE
 
-      !5 clean
-      CALL iom_mpp_close(tl_mppbathy)
-      CALL mpp_clean(tl_mppbathy)
-
-      !5- compute vertical grid
+      ! clean
+      CALL iom_dom_close(tl_bathy)
+      CALL mpp_clean(tl_bathy)
+
+      ! compute vertical grid
       ALLOCATE( dl_gdepw(in_nlevel), dl_gdept(in_nlevel) ) 
       ALLOCATE(   dl_e3w(in_nlevel),   dl_e3t(in_nlevel) ) 
@@ -650,5 +715,5 @@
       &                 dn_ppa0, dn_ppa1, dn_ppa2, dn_ppsur )
 
-      !6- compute bathy level on T point
+      ! compute bathy level on T point
       ALLOCATE( il_mbathy(tl_var%t_dim(1)%i_len, &
       &                   tl_var%t_dim(2)%i_len ) )
@@ -660,8 +725,8 @@
       DEALLOCATE(   dl_e3w,   dl_e3t )
 
-      !7- compute bathy level in T,U,V,F point
+      ! compute bathy level in T,U,V,F point
       ALLOCATE( il_level(tl_var%t_dim(1)%i_len, &
       &                  tl_var%t_dim(2)%i_len, &
-      &                  ig_npoint,1) )
+      &                  ip_npoint,1) )
 
       DO jj=1,tl_var%t_dim(2)%i_len
@@ -686,5 +751,6 @@
       DEALLOCATE( il_mbathy )
 
-      tl_dim(:)=tl_var%t_dim(:)
+      tl_dim(:)=dim_copy(tl_var%t_dim(:))
+      ! clean
       CALL var_clean(tl_var)
 
@@ -692,61 +758,24 @@
       tl_dim(3:4)%l_use=.FALSE.
 
-      tl_level(jp_T)=var_init('tlevel',il_level(:,:,jp_T:jp_T,:),td_dim=tl_dim(:))
-      tl_level(jp_U)=var_init('ulevel',il_level(:,:,jp_U:jp_U,:),td_dim=tl_dim(:))
-      tl_level(jp_V)=var_init('vlevel',il_level(:,:,jp_V:jp_V,:),td_dim=tl_dim(:))
-      tl_level(jp_F)=var_init('flevel',il_level(:,:,jp_F:jp_F,:),td_dim=tl_dim(:))
+      vgrid_get_level(jp_T)=var_init( 'tlevel', il_level(:,:,jp_T:jp_T,:), &
+      &                                td_dim=tl_dim(:) )
+      vgrid_get_level(jp_U)=var_init( 'ulevel', il_level(:,:,jp_U:jp_U,:), &
+      &                                td_dim=tl_dim(:))
+      vgrid_get_level(jp_V)=var_init( 'vlevel', il_level(:,:,jp_V:jp_V,:), &
+      &                                td_dim=tl_dim(:))
+      vgrid_get_level(jp_F)=var_init( 'flevel', il_level(:,:,jp_F:jp_F,:), &
+      &                                td_dim=tl_dim(:))
 
       DEALLOCATE( il_level )
 
-      ! save result
-      vgrid_get_level(:)=tl_level(:)
-
-      DO ji=1,ig_npoint
-         CALL var_clean(tl_level(ji))
-      ENDDO
+      CALL grid_add_ghost( vgrid_get_level(jp_T), il_xghost(:,:) )
+      CALL grid_add_ghost( vgrid_get_level(jp_U), il_xghost(:,:) )
+      CALL grid_add_ghost( vgrid_get_level(jp_V), il_xghost(:,:) )
+      CALL grid_add_ghost( vgrid_get_level(jp_F), il_xghost(:,:) )
+
+      ! clean
+      CALL dim_clean(tl_dim(:))
 
    END FUNCTION vgrid_get_level
-   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief This function 
-!   !
-!   !> @details
-!   !
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   FUNCTION vgrid_()
-!      IMPLICIT NONE
-!      ! Argument      
-!      ! function
-!      ! local variable
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END FUNCTION vgrid_
-!   !> @endcode
-!   !-------------------------------------------------------------------
-!   !> @brief This subroutine 
-!   !
-!   !> @details
-!   !
-!   !> @author J.Paul
-!   !> - Nov, 2013- Initial Version
-!   !
-!   !> @param[in] 
-!   !-------------------------------------------------------------------
-!   !> @code
-!   SUBROUTINE vgrid_()
-!      IMPLICIT NONE
-!      ! Argument      
-!      ! local variable
-!      ! loop indices
-!      !----------------------------------------------------------------
-!
-!   END SUBROUTINE vgrid_
-!   !> @endcode
 END MODULE vgrid
 
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_bathy.nam
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_bathy.nam	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_bathy.nam	(revision 5075)
@@ -0,0 +1,32 @@
+&namlog
+   cn_logfile="bathy_out.log"
+   cn_verbosity=
+   in_maxerror=
+/
+
+&namcfg
+   cn_varcfg="./cfg/variable.cfg"
+/
+
+&namcrs
+   cn_coord0=
+   in_perio0=
+/
+
+&namfin
+   cn_coord1=
+/
+
+&namvar
+   cn_varinfo=
+   cn_varfile=
+/
+
+&namnst
+   in_rhoi=
+   in_rhoj=
+/
+
+&namout
+   cn_fileout="bathy_out.nc"      
+/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_boundary.nam
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_boundary.nam	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_boundary.nam	(revision 5075)
@@ -0,0 +1,67 @@
+&namlog
+   cn_logfile="boundary.log"
+   cn_verbosity=
+   in_maxerror =
+/
+
+&namcfg
+   cn_varcfg="./cfg/variable.cfg"
+/
+
+&namcrs
+   cn_coord0=
+   in_perio0=
+/
+
+&namfin
+   cn_coord1=
+   cn_bathy1=
+   in_perio1=
+/
+
+&namzgr
+   dn_pp_to_be_computed=
+   dn_ppsur    =
+   dn_ppa0     =
+   dn_ppa1     =
+   dn_ppa2     = 
+   dn_ppkth    =
+   dn_ppkth2   =
+   dn_ppacr    =
+   dn_ppacr2   =
+   dn_ppdzmin  =
+   dn_pphmax   =
+   in_nlevel   =
+/
+
+&namzps
+   dn_e3zps_min =
+   dn_e3zps_rat =
+/
+
+&namvar
+   cn_varinfo=
+   cn_varfile=
+/
+
+&namnst
+   in_rhoi=
+   in_rhoj=
+/
+
+&nambdy
+   ln_north = 
+   ln_south = 
+   ln_east  = 
+   ln_west  = 
+   cn_north = 
+   cn_south = 
+   cn_east  = 
+   cn_west  = 
+   ln_oneseg= 
+   in_extrap= 
+/
+
+&namout
+   cn_fileout="boundary_out.nc"      
+/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_coord.nam
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_coord.nam	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_coord.nam	(revision 5075)
@@ -0,0 +1,33 @@
+&namlog
+   cn_logfile="coord_out.log"
+   cn_verbosity=
+   in_maxerror=
+/
+
+&namcfg
+   cn_varcfg="./cfg/variable.cfg"
+/
+
+&namcrs
+   cn_coord0=
+   in_perio0=
+/
+
+&namvar
+   cn_varinfo=
+/
+
+&namnst
+   in_imin0=
+   in_imax0=
+   in_jmin0=
+   in_jmax0=
+
+   in_rhoi=
+   in_rhoj=
+/
+
+&namout
+   cn_fileout="coord_out.nc"
+/
+
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_restart.nam
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_restart.nam	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/create_restart.nam	(revision 5075)
@@ -0,0 +1,55 @@
+&namlog
+   cn_logfile="restart_out.log"
+   cn_verbosity=
+   in_maxerror =
+/
+
+&namcfg
+   cn_varcfg="./cfg/variable.cfg"
+/
+
+&namcrs
+   cn_coord0=
+   in_perio0=
+/
+
+&namzgr
+   dn_pp_to_be_computed=
+   dn_ppsur    =
+   dn_ppa0     =
+   dn_ppa1     =
+   dn_ppa2     = 
+   dn_ppkth    =
+   dn_ppkth2   =
+   dn_ppacr    =
+   dn_ppacr2   =
+   dn_ppdzmin  =
+   dn_pphmax   =
+   in_nlevel   =
+/
+
+&namzps
+   dn_e3zps_min =
+   dn_e3zps_rat =
+/
+
+&namfin
+   cn_coord1=
+   cn_bathy1=
+   in_perio1=
+   in_extrap=
+/
+
+&namvar
+   cn_varinfo=
+   cn_varfile=
+/
+
+&namnst
+   in_rhoi=
+   in_rhoj=
+/
+
+&namout
+   cn_fileout="restart_out.nc"      
+/
Index: /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/merge_bathy.nam
===================================================================
--- /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/merge_bathy.nam	(revision 5075)
+++ /branches/2014/dev_r4650_UKMO7_STARTHOUR/NEMOGCM/TOOLS/SIREN/templates/merge_bathy.nam	(revision 5075)
@@ -0,0 +1,44 @@
+&namlog
+   cn_logfile="merge_out.log"
+   cn_verbosity=
+   in_maxerror =
+/
+
+&namcfg
+   cn_varcfg="./cfg/variable.cfg"
+/
+
+&namcrs
+   cn_bathy0=
+   in_perio0=
+/
+
+&namfin
+   cn_bathy1=
+   in_perio1=
+/
+
+&namvar
+   cn_varinfo=
+/
+
+&namnst
+   in_rhoi=
+   in_rhoj=
+/
+
+&nambdy
+   ln_north=
+   ln_south=
+   ln_east=
+   ln_west=
+   cn_north=
+   cn_south=
+   cn_east=
+   cn_west=
+   ln_oneseg=
+/
+
+&namout
+   cn_fileout="merge_out.nc"      
+/
